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
cuappdev/tempo
Tempo/Player.swift
1
3329
// // Player.swift // Tempo // // Created by Alexander Zielenski on 3/22/15. // Copyright (c) 2015 CUAppDev. All rights reserved. // import UIKit import AVFoundation class Player: NSObject, AVAudioPlayerDelegate { fileprivate var currentTask: URLSessionDataTask? fileprivate static var currentPlayer: Player? { didSet { if Player.currentPlayer != oldValue { oldValue?.pause() } } } fileprivate var player: AVAudioPlayer? { didSet { oldValue?.stop() if let oldDelegate = oldValue?.delegate as? Player { if self == oldDelegate { oldValue?.delegate = nil } } player?.delegate = self } } var wasPlayed = false var finishedPlaying = false weak var delegate: PlayerDelegate? fileprivate let fileURL: URL init(fileURL: URL) { self.fileURL = fileURL super.init() } class func keyPathsForValuesAffectingCurrentTime(key: String) -> Set<String> { return Set(["player.currentTime"]) } class func keyPathsForValuesAffectingProgress() -> Set<String> { return Set(["currentTime"]) } func prepareToPlay() { if player == nil { if fileURL.isFileURL { player = try? AVAudioPlayer(contentsOf: fileURL) } else if currentTask == nil { let request = URLRequest(url: fileURL, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 15) currentTask = URLSession.dataTaskWithCachedRequest(request) { [weak self] data, response, _ -> Void in guard let s = self else { return } if let data = data { s.player = try? AVAudioPlayer(data: data) } s.currentTask = nil if s.shouldAutoplay { s.player?.play() } } currentTask!.resume() } } } private var shouldAutoplay = false func play() { prepareToPlay() wasPlayed = true finishedPlaying = false if player != nil { player?.play() } shouldAutoplay = true } var rate: Float { get { return player?.rate ?? 0 } set { player?.rate = newValue } } func pause() { player?.stop() shouldAutoplay = false } var isPlaying: Bool { return player?.isPlaying ?? false || shouldAutoplay } func togglePlaying() { isPlaying ? pause() : play() if (isPlaying) { Player.currentPlayer = self } } dynamic var currentTime: TimeInterval { get { return player?.currentTime ?? 0 } set { guard let player = player else { return } player.currentTime = max(0, min(duration, newValue)) } } var duration: TimeInterval { return player?.duration ?? DBL_MAX } dynamic var progress: Double { get { if finishedPlaying { return 1 } return player != nil ? currentTime / duration : 0 } set { if player == nil { return } if newValue == 1.0 { finishedPlaying = true } currentTime = newValue * duration } } // MARK: - AVAudioPlayerDelegate func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { finishedPlaying = true delegate?.didFinishPlaying?() } }
mit
8c49c8584086d569d7c1c60251889b39
21.646259
114
0.583659
4.363041
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Maps/Display a map SwiftUI/DisplayMapSwiftUIView.swift
1
3516
// Copyright 2021 Esri // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import SwiftUI import ArcGIS struct DisplayMapSwiftUIView: View { struct MapOption: Equatable { let title: String let map: AGSMap static let topographic = MapOption(title: "Topographic", map: AGSMap(basemapStyle: .arcGISTopographic)) static let oceans = MapOption(title: "Oceans", map: AGSMap(basemapStyle: .arcGISOceans)) static let navigation = MapOption(title: "Navigation", map: AGSMap(basemapStyle: .arcGISNavigation)) static let allOptions: [MapOption] = [.topographic, .oceans, .navigation] } /// The graphics overlay used to initialize `SwiftUIMapView`. let graphicsOverlay: AGSGraphicsOverlay = { let overlay = AGSGraphicsOverlay() overlay.renderer = AGSSimpleRenderer( symbol: AGSSimpleMarkerSymbol(style: .circle, color: .red, size: 10) ) return overlay }() @State private var clearGraphicsButtonDisabled = true @State private var selectedMapOption: MapOption = .topographic /// A Boolean that indicates whether the action sheet is presented. @State private var showingOptions = false var body: some View { VStack { SwiftUIMapView(map: selectedMapOption.map, graphicsOverlays: [graphicsOverlay]) .onSingleTap { _, mapPoint in let graphic = AGSGraphic(geometry: mapPoint, symbol: nil) graphicsOverlay.graphics.add(graphic) updateClearGraphicsButtonState() } .edgesIgnoringSafeArea(.all) HStack { Button("Choose Map", action: { showingOptions = true }) .actionSheet(isPresented: $showingOptions) { ActionSheet( title: Text("Choose a basemap."), buttons: MapOption.allOptions.map { option in .default(Text(option.title), action: { guard option != selectedMapOption else { return } clearGraphics() selectedMapOption = option }) } + [.cancel()] ) } Spacer() Button("Clear Graphics", action: clearGraphics) .disabled(clearGraphicsButtonDisabled) } .padding() } } func clearGraphics() { graphicsOverlay.graphics.removeAllObjects() updateClearGraphicsButtonState() } func updateClearGraphicsButtonState() { clearGraphicsButtonDisabled = (graphicsOverlay.graphics as! [AGSGraphic]).isEmpty } } struct DisplayMapSwiftUIView_Previews: PreviewProvider { static var previews: some View { DisplayMapSwiftUIView() } }
apache-2.0
9460d2839367ef12ff807c1ced0b8229
38.505618
111
0.595279
5.162996
false
false
false
false
mattrubin/Bases
Sources/Base16/Base16.swift
1
4817
// // Base16.swift // Bases // // Copyright (c) 2016-2019 Matt Rubin and the Bases authors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation public enum Base16 { /// The size of a block before encoding, measured in bytes. private static let unencodedBlockSize = 1 /// The size of a block after encoding, measured in bytes. private static let encodedBlockSize = 2 public static func encode(_ data: Data) -> String { let unencodedByteCount = data.count let encodedByteCount = unencodedByteCount * encodedBlockSize let encodedBytes = UnsafeMutablePointer<EncodedChar>.allocate(capacity: encodedByteCount) data.withUnsafeBytes { unencodedBytes in var encodedWriteOffset = 0 for unencodedReadOffset in stride(from: 0, to: unencodedByteCount, by: unencodedBlockSize) { let nextUnencodedByte = unencodedBytes[unencodedReadOffset] let bigNibble = (nextUnencodedByte & 0b11110000) >> 4 let littleNibble = nextUnencodedByte & 0b00001111 let bigChar = encodingTable[Int(bigNibble)] let littleChar = encodingTable[Int(littleNibble)] encodedBytes[encodedWriteOffset + 0] = bigChar encodedBytes[encodedWriteOffset + 1] = littleChar encodedWriteOffset += encodedBlockSize } } // The Data instance takes ownership of the allocated bytes and will handle deallocation. let encodedData = Data(bytesNoCopy: encodedBytes, count: encodedByteCount, deallocator: .free) guard let encodedString = String(data: encodedData, encoding: String.Encoding.ascii) else { fatalError("Internal Error: Encoded data could not be encoded as ASCII (\(encodedData))") } return encodedString } public static func decode(_ string: String) throws -> Data { guard let encodedData = string.data(using: String.Encoding.ascii) else { throw Error.nonAlphabetCharacter } let encodedByteCount = encodedData.count let decodedByteCount = try byteCount(decoding: encodedByteCount) let decodedBytes = UnsafeMutablePointer<Byte>.allocate(capacity: decodedByteCount) try encodedData.withUnsafeBytes { encodedBytes in var decodedWriteOffset = 0 for encodedReadOffset in stride(from: 0, to: encodedByteCount, by: encodedBlockSize) { let bigChar = encodedBytes[encodedReadOffset] let littleChar = encodedBytes[encodedReadOffset + 1] let bigNibble = try byte(decoding: bigChar) let littleNibble = try byte(decoding: littleChar) let decodedByte = ((bigNibble & 0b00001111) << 4) | (littleNibble & 0b00001111) decodedBytes[decodedWriteOffset] = decodedByte decodedWriteOffset += unencodedBlockSize } } // The Data instance takes ownership of the allocated bytes and will handle deallocation. return Data(bytesNoCopy: decodedBytes, count: decodedByteCount, deallocator: .free) } private static func byteCount(decoding encodedByteCount: Int) throws -> Int { guard encodedByteCount.isMultiple(of: encodedBlockSize) else { throw Error.incompleteBlock } return (encodedByteCount / encodedBlockSize) * unencodedBlockSize } public enum Error: Swift.Error { /// The input string ends with an incomplete encoded block case incompleteBlock /// The input string contains a character not in the encoding alphabet case nonAlphabetCharacter } }
mit
c8079de9df608129f536641e21ef9713
43.601852
104
0.676977
4.996888
false
false
false
false
steelwheels/KiwiControls
Source/Controls/KCButtonCore.swift
1
2239
/* * @file KCButtonCore.swift * @brief Define KCButtonCore class * @par Copyright * Copyright (C) 2016 Steel Wheels Project */ #if os(iOS) import UIKit #else import Cocoa #endif import CoconutData public enum KCButtonSymbol { case leftArrow case rightArrow public var description: String { get { let result: String switch self { case .leftArrow: result = "left-arrow" case .rightArrow: result = "right-arrow" } return result }} } public enum KCButtonValue { case text(String) case symbol(KCButtonSymbol) } public class KCButtonCore: KCCoreView { #if os(iOS) @IBOutlet weak var mButton: UIButton! #else @IBOutlet weak var mButton: KCButtonBody! #endif public var buttonPressedCallback: (() -> Void)? = nil private var mButtonValue: KCButtonValue = .text("") public func setup(frame frm: CGRect) -> Void { super.setup(isSingleView: true, coreView: mButton) KCView.setAutolayoutMode(views: [self, mButton]) } #if os(iOS) @IBAction func buttonPressed(_ sender: UIButton) { if let callback = buttonPressedCallback { callback() } } #else @IBAction func buttonPressed(_ sender: NSButton) { if let callback = buttonPressedCallback { callback() } } #endif public var value: KCButtonValue { get { return mButtonValue } set(newval){ switch newval { case .text(let str): #if os(iOS) mButton.setTitle(str, for: .normal) #else mButton.title = str mButton.setButtonType(.momentaryPushIn) mButton.bezelStyle = .rounded mButton.imagePosition = .noImage #endif case .symbol(let sym): let img = loadSymbol(symbol: sym) #if os(OSX) mButton.bezelStyle = .regularSquare mButton.image = img mButton.imagePosition = .imageOnly #else mButton.setImage(img, for: .normal) #endif } mButtonValue = newval } } private func loadSymbol(symbol sym: KCButtonSymbol) -> CNImage { let type: CNSymbol.SymbolType switch sym { case .leftArrow: type = .chevronBackward case .rightArrow: type = .chevronForward } return CNSymbol.shared.loadImage(type: type) } public var isEnabled: Bool { get { return mButton.isEnabled } set(newval){ self.mButton.isEnabled = newval } } }
lgpl-2.1
d5f4c60cd18fa6664ac50def0c245391
18.991071
65
0.685574
3.118384
false
false
false
false
laurennicoleroth/Tindergram
Tindergram/ProfileViewController.swift
1
939
import UIKit class ProfileViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationItem.titleView = UIImageView(image: UIImage(named: "profile-header")) let rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "nav-back-button"), style: .Plain, target: self, action: "goToCards:") navigationItem.setRightBarButtonItem(rightBarButtonItem, animated: true) } override func viewDidLoad() { super.viewDidLoad() nameLabel.text = currentUser()?.name currentUser()?.getPhoto({ image in self.imageView.layer.masksToBounds = true self.imageView.contentMode = .ScaleAspectFill self.imageView.image = image }) } func goToCards(button: UIBarButtonItem) { pageController.goToNextVC() } }
mit
03e59eb2fa82c8ff6d4c0e81b931d1b7
25.828571
137
0.705005
4.890625
false
false
false
false
brentdax/swift
benchmark/single-source/Radix2CooleyTukey.swift
6
8609
// Radix2CooleyTukey benchmark // // Originally written by @owensd. Used with his permission. import Foundation import TestsUtils public var Radix2CooleyTukey = [ BenchmarkInfo( name: "Radix2CooleyTukey", runFunction: run_Radix2CooleyTukey, tags: [.validation, .algorithm], setUpFunction: setUpRadix2CooleyTukey, tearDownFunction: tearDownRadix2CooleyTukey), BenchmarkInfo( name: "Radix2CooleyTukeyf", runFunction: run_Radix2CooleyTukeyf, tags: [.validation, .algorithm], setUpFunction: setUpRadix2CooleyTukeyf, tearDownFunction: tearDownRadix2CooleyTukeyf), ] //===----------------------------------------------------------------------===// // Double Benchmark //===----------------------------------------------------------------------===// var double_input_real: UnsafeMutablePointer<Double>? var double_input_imag: UnsafeMutablePointer<Double>? var double_output_real: UnsafeMutablePointer<Double>? var double_output_imag: UnsafeMutablePointer<Double>? var double_temp_real: UnsafeMutablePointer<Double>? var double_temp_imag: UnsafeMutablePointer<Double>? let doubleN = 65_536 let doubleSize = { MemoryLayout<Double>.size * doubleN }() func setUpRadix2CooleyTukey() { let size = doubleSize double_input_real = UnsafeMutablePointer<Double>.allocate(capacity: size) double_input_imag = UnsafeMutablePointer<Double>.allocate(capacity: size) double_output_real = UnsafeMutablePointer<Double>.allocate(capacity: size) double_output_imag = UnsafeMutablePointer<Double>.allocate(capacity: size) double_temp_real = UnsafeMutablePointer<Double>.allocate(capacity: size) double_temp_imag = UnsafeMutablePointer<Double>.allocate(capacity: size) } func tearDownRadix2CooleyTukey() { double_input_real?.deallocate() double_input_imag?.deallocate() double_output_real?.deallocate() double_output_imag?.deallocate() double_temp_real?.deallocate() double_temp_imag?.deallocate() } func Radix2CooleyTukey(_ level: Int, input_real: UnsafeMutablePointer<Double>, input_imag: UnsafeMutablePointer<Double>, stride: Int, output_real: UnsafeMutablePointer<Double>, output_imag: UnsafeMutablePointer<Double>, temp_real: UnsafeMutablePointer<Double>, temp_imag: UnsafeMutablePointer<Double>) { if level == 0 { output_real[0] = input_real[0]; output_imag[0] = input_imag[0]; return } let length = 1 << level let half = length >> 1 Radix2CooleyTukey(level - 1, input_real: input_real, input_imag: input_imag, stride: stride << 1, output_real: temp_real, output_imag: temp_imag, temp_real: output_real, temp_imag: output_imag) Radix2CooleyTukey(level - 1, input_real: input_real + stride, input_imag: input_imag + stride, stride: stride << 1, output_real: temp_real + half, output_imag: temp_imag + half, temp_real: output_real + half, temp_imag: output_imag + half) for idx in 0..<half { let angle = -Double.pi * Double(idx) / Double(half) let _cos = cos(angle) let _sin = sin(angle) output_real[idx] = temp_real[idx] + _cos * temp_real[idx + half] - _sin * temp_imag[idx + half] output_imag[idx] = temp_imag[idx] + _cos * temp_imag[idx + half] + _sin * temp_real[idx + half] output_real[idx + half] = temp_real[idx] - _cos * temp_real[idx + half] + _sin * temp_imag[idx + half] output_imag[idx + half] = temp_imag[idx] - _cos * temp_imag[idx + half] - _sin * temp_real[idx + half] } } func testDouble(iter: Int) { let stride = 1 let size = doubleSize let level = Int(log2(Double(doubleN))) let input_real = double_input_real.unsafelyUnwrapped let input_imag = double_input_imag.unsafelyUnwrapped let output_real = double_output_real.unsafelyUnwrapped let output_imag = double_output_imag.unsafelyUnwrapped let temp_real = double_temp_real.unsafelyUnwrapped let temp_imag = double_temp_imag.unsafelyUnwrapped for _ in 0..<iter { memset(UnsafeMutableRawPointer(input_real), 0, size) memset(UnsafeMutableRawPointer(input_imag), 0, size) memset(UnsafeMutableRawPointer(output_real), 0, size) memset(UnsafeMutableRawPointer(output_imag), 0, size) memset(UnsafeMutableRawPointer(temp_real), 0, size) memset(UnsafeMutableRawPointer(temp_imag), 0, size) Radix2CooleyTukey(level, input_real: input_real, input_imag: input_imag, stride: stride, output_real: output_real, output_imag: output_imag, temp_real: temp_real, temp_imag: temp_imag) } } @inline(never) public func run_Radix2CooleyTukey(_ N: Int) { testDouble(iter: N) } //===----------------------------------------------------------------------===// // Float Benchmark //===----------------------------------------------------------------------===// let floatN = 65_536 let floatSize = { MemoryLayout<Float>.size * floatN }() var float_input_real: UnsafeMutablePointer<Float>? var float_input_imag: UnsafeMutablePointer<Float>? var float_output_real: UnsafeMutablePointer<Float>? var float_output_imag: UnsafeMutablePointer<Float>? var float_temp_real: UnsafeMutablePointer<Float>? var float_temp_imag: UnsafeMutablePointer<Float>? func setUpRadix2CooleyTukeyf() { let size = floatSize float_input_real = UnsafeMutablePointer<Float>.allocate(capacity: size) float_input_imag = UnsafeMutablePointer<Float>.allocate(capacity: size) float_output_real = UnsafeMutablePointer<Float>.allocate(capacity: size) float_output_imag = UnsafeMutablePointer<Float>.allocate(capacity: size) float_temp_real = UnsafeMutablePointer<Float>.allocate(capacity: size) float_temp_imag = UnsafeMutablePointer<Float>.allocate(capacity: size) } func tearDownRadix2CooleyTukeyf() { float_input_real?.deallocate() float_input_imag?.deallocate() float_output_real?.deallocate() float_output_imag?.deallocate() float_temp_real?.deallocate() float_temp_imag?.deallocate() } func Radix2CooleyTukeyf(_ level: Int, input_real: UnsafeMutablePointer<Float>, input_imag: UnsafeMutablePointer<Float>, stride: Int, output_real: UnsafeMutablePointer<Float>, output_imag: UnsafeMutablePointer<Float>, temp_real: UnsafeMutablePointer<Float>, temp_imag: UnsafeMutablePointer<Float>) { if level == 0 { output_real[0] = input_real[0]; output_imag[0] = input_imag[0]; return } let length = 1 << level let half = length >> 1 Radix2CooleyTukeyf(level - 1, input_real: input_real, input_imag: input_imag, stride: stride << 1, output_real: temp_real, output_imag: temp_imag, temp_real: output_real, temp_imag: output_imag) Radix2CooleyTukeyf(level - 1, input_real: input_real + stride, input_imag: input_imag + stride, stride: stride << 1, output_real: temp_real + half, output_imag: temp_imag + half, temp_real: output_real + half, temp_imag: output_imag + half) for idx in 0..<half { let angle = -Float.pi * Float(idx) / Float(half) let _cos = cosf(angle) let _sin = sinf(angle) output_real[idx] = temp_real[idx] + _cos * temp_real[idx + half] - _sin * temp_imag[idx + half] output_imag[idx] = temp_imag[idx] + _cos * temp_imag[idx + half] + _sin * temp_real[idx + half] output_real[idx + half] = temp_real[idx] - _cos * temp_real[idx + half] + _sin * temp_imag[idx + half] output_imag[idx + half] = temp_imag[idx] - _cos * temp_imag[idx + half] - _sin * temp_real[idx + half] } } func testFloat(iter: Int) { let stride = 1 let n = floatN let size = floatSize let input_real = float_input_real.unsafelyUnwrapped let input_imag = float_input_imag.unsafelyUnwrapped let output_real = float_output_real.unsafelyUnwrapped let output_imag = float_output_imag.unsafelyUnwrapped let temp_real = float_temp_real.unsafelyUnwrapped let temp_imag = float_temp_imag.unsafelyUnwrapped let level = Int(log2(Float(n))) for _ in 0..<iter { memset(UnsafeMutableRawPointer(input_real), 0, size) memset(UnsafeMutableRawPointer(input_imag), 0, size) memset(UnsafeMutableRawPointer(output_real), 0, size) memset(UnsafeMutableRawPointer(output_imag), 0, size) memset(UnsafeMutableRawPointer(temp_real), 0, size) memset(UnsafeMutableRawPointer(temp_imag), 0, size) Radix2CooleyTukeyf(level, input_real: input_real, input_imag: input_imag, stride: stride, output_real: output_real, output_imag: output_imag, temp_real: temp_real, temp_imag: temp_imag) } } @inline(never) public func run_Radix2CooleyTukeyf(_ N: Int) { testFloat(iter: N) }
apache-2.0
35c87cfc642824369bf206352a3d1f5e
32.368217
80
0.677663
3.666525
false
false
false
false
Pretz/SwiftGraphics
SwiftGraphics/CoreTypes/CGPoint+Trigonometry.swift
2
7251
// // CGPoint+Trigonometry.swift // SwiftGraphics // // Created by Jonathan Wight on 2/5/15. // Contibutions by Zhang Yungui <https: //github.com/rhcad> on 15/1/14. // Copyright (c) 2015 schwa.io. All rights reserved. // import CoreGraphics public func dotProduct(lhs: CGPoint, _ rhs: CGPoint) -> CGFloat { return lhs.x * rhs.x + lhs.y * rhs.y } public func crossProduct(lhs: CGPoint, _ rhs: CGPoint) -> CGFloat { return lhs.x * rhs.y - lhs.y * rhs.x } public extension CGPoint { init(magnitude: CGFloat, direction: CGFloat) { x = cos(direction) * magnitude y = sin(direction) * magnitude } var magnitude: CGFloat { get { return sqrt(x * x + y * y) } set(v) { self = CGPoint(magnitude: v, direction: direction) } } var magnitudeSquared: CGFloat { return x * x + y * y } var direction: CGFloat { get { return atan2(self) } set(v) { self = CGPoint(magnitude: magnitude, direction: v) } } var normalized: CGPoint { let len = magnitude return len ==% 0 ? self : CGPoint(x: x / len, y: y / len) } var orthogonal: CGPoint { return CGPoint(x: -y, y: x) } var transposed: CGPoint { return CGPoint(x: y, y: x) } } public func atan2(point: CGPoint) -> CGFloat { // (-M_PI, M_PI] return atan2(point.y, point.x) } // MARK: Distance and angle between two points or vectors public extension CGPoint { func distanceTo(point: CGPoint) -> CGFloat { return (self - point).magnitude } func distanceTo(p1: CGPoint, p2: CGPoint) -> CGFloat { return distanceToBeeline(p1, p2: p2).0 } // TODO: What is a beeline???? func distanceToBeeline(p1: CGPoint, p2: CGPoint) -> (CGFloat, CGPoint) { if p1 == p2 { return (distanceTo(p1), p1) } if p1.x == p2.x { return (abs(p1.x - self.x), CGPoint(x: p1.x, y: self.y)) } if p1.y == p2.y { return (abs(p1.y - self.y), CGPoint(x: self.x, y: p1.y)) } let t1 = (p2.y - p1.y) / (p2.x - p1.x) let t2 = -1 / t1 let numerator = self.y - p1.y + p1.x * t1 - self.x * t2 let perpx = numerator / (t1 - t2) let perp = CGPoint(x: perpx, y: p1.y + (perpx - p1.x) * t1) return (distanceTo(perp), perp) } // Returns the angle between this vector and another vector 'vec'. // The result sign indicates the rotation direction from this vector to 'vec': positive for counter-clockwise, negative for clockwise. func angleTo(vec: CGPoint) -> CGFloat { // [-M_PI, M_PI) return atan2(crossProduct(self, vec), dotProduct(self, vec)) } } /** Return true if a, b, and c all lie on the same line. */ public func collinear(a: CGPoint, _ b: CGPoint, _ c: CGPoint) -> Bool { return (b.x - a.x) * (c.y - a.y) ==% (c.x - a.x) * (b.y - a.y) } /** Return true if c is near to the beeline a b. */ public func collinear(a: CGPoint, _ b: CGPoint, _ c: CGPoint, tolerance: CGFloat) -> Bool { return c.distanceTo(a, p2: b) <= tolerance } /** Return the angle between vertex-p1 and vertex-vertex. */ public func angle(vertex: CGPoint, _ p1: CGPoint, _ p2: CGPoint) -> CGFloat { return abs((p1 - vertex).angleTo(p2 - vertex)) } // MARK: Relative point calculation methods like ruler tools public extension CGPoint { /** Calculate a point with polar angle and radius based on this point. - parameter angle: polar angle in radians. - parameter radius: the length of the polar radius - returns: the point relative to this point. */ func polarPoint(angle: CGFloat, radius: CGFloat) -> CGPoint { return CGPoint(x: x + radius * cos(angle), y: y + radius * sin(angle)); } /** Calculate a point along the direction from this point to 'dir' point. - parameter dir: the direction point. - parameter dx: the distance from this point to the result point. The negative value represents along the opposite direction. - returns: the point relative to this point. */ func rulerPoint(dir: CGPoint, dx: CGFloat) -> CGPoint { let len = distanceTo(dir) if len == 0 { return CGPoint(x: x + dx, y: y) } let d = dx / len return CGPoint(x: x + (dir.x - x) * d, y: y + (dir.y - y) * d) } /** Calculate a point along the direction from this point to 'dir' point. dx and dy may be negative which represents along the opposite direction. - parameter dir: the direction point. - parameter dx: the projection distance along the direction from this point to 'dir' point. - parameter dy: the perpendicular distance from the result point to the line of this point to 'dir' point. - returns: the point relative to this point. */ func rulerPoint(dir: CGPoint, dx: CGFloat, dy: CGFloat) -> CGPoint { let len = distanceTo(dir) if len == 0 { return CGPoint(x: x + dx, y: y + dy) } let dcos = (dir.x - x) / len let dsin = (dir.y - y) / len return CGPoint(x: x + dx * dcos - dy * dsin, y: y + dx * dsin + dy * dcos) } } // MARK: Vector projection public extension CGPoint { public static var vectorTolerance: CGFloat = 1e-4 //! Returns whether this vector is perpendicular to another vector. func isPerpendicularTo(vec: CGPoint) -> Bool { let sinfz = abs(crossProduct(self, vec)) if sinfz == 0 { return false } let cosfz = abs(dotProduct(self, vec)) return cosfz <= sinfz * CGPoint.vectorTolerance } /** Returns the length of the vector which perpendicular to the projection of this vector onto xAxis vector. - parameter xAxis: projection target vector. - returns: perpendicular distance which is positive if this vector is in the CCW direction of xAxis and negative if clockwise. */ func distanceToVector(xAxis: CGPoint) -> CGFloat { let len = xAxis.magnitude return len == 0 ? magnitude : crossProduct(xAxis, self) / len } //! Returns the proportion of the projection vector onto xAxis, projection==xAxis * proportion func projectScaleToVector(xAxis: CGPoint) -> CGFloat { let d2 = xAxis.magnitudeSquared return d2 == 0 ? 0.0 : dotProduct(self, xAxis) / d2 } //! Returns the projection vector and perpendicular vector, self==proj+perp func projectResolveVector(xAxis: CGPoint) -> (CGPoint, CGPoint) { let s = projectScaleToVector(xAxis) let proj = xAxis * s, perp = self - proj return (proj, perp) } //! Vector decomposition onto two vectors: self==u*uAxis + v*vAxis func resolveVector(uAxis: CGPoint, vAxis: CGPoint) -> (CGFloat, CGFloat) { let denom = crossProduct(uAxis, vAxis) if denom == 0 { return (0, 0) } let c = crossProduct(uAxis, self) return (crossProduct(self, vAxis) / denom, c / denom) // (u,v) } }
bsd-2-clause
98da02250d2ce7790c58bd37c6264d65
30.120172
138
0.588884
3.667678
false
false
false
false
HongliYu/firefox-ios
Client/Frontend/Home/BookmarksPanel.swift
1
25395
/* 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 Storage import Shared import XCGLogger private let log = Logger.browserLogger // MARK: - Placeholder strings for Bug 1232810. let deleteWarningTitle = NSLocalizedString("This folder isn’t empty.", tableName: "BookmarkPanelDeleteConfirm", comment: "Title of the confirmation alert when the user tries to delete a folder that still contains bookmarks and/or folders.") let deleteWarningDescription = NSLocalizedString("Are you sure you want to delete it and its contents?", tableName: "BookmarkPanelDeleteConfirm", comment: "Main body of the confirmation alert when the user tries to delete a folder that still contains bookmarks and/or folders.") let deleteCancelButtonLabel = NSLocalizedString("Cancel", tableName: "BookmarkPanelDeleteConfirm", comment: "Button label to cancel deletion when the user tried to delete a non-empty folder.") let deleteDeleteButtonLabel = NSLocalizedString("Delete", tableName: "BookmarkPanelDeleteConfirm", comment: "Button label for the button that deletes a folder and all of its children.") // Placeholder strings for Bug 1248034 let emptyBookmarksText = NSLocalizedString("Bookmarks you save will show up here.", comment: "Status label for the empty Bookmarks state.") // MARK: - UX constants. private struct BookmarksPanelUX { static let BookmarkFolderHeaderViewChevronInset: CGFloat = 10 static let BookmarkFolderChevronSize: CGFloat = 20 static let BookmarkFolderChevronLineWidth: CGFloat = 2.0 static let WelcomeScreenPadding: CGFloat = 15 static let WelcomeScreenItemWidth = 170 static let SeparatorRowHeight: CGFloat = 0.5 static let IconSize: CGFloat = 23 static let IconBorderWidth: CGFloat = 0.5 } class BookmarksPanel: SiteTableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? var source: BookmarksModel? var parentFolders = [BookmarkFolder]() var bookmarkFolder: BookmarkFolder? var refreshControl: UIRefreshControl? fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(longPress)) }() fileprivate lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverlayView() fileprivate let BookmarkFolderCellIdentifier = "BookmarkFolderIdentifier" fileprivate let BookmarkSeparatorCellIdentifier = "BookmarkSeparatorIdentifier" fileprivate let BookmarkFolderHeaderViewIdentifier = "BookmarkFolderHeaderIdentifier" override init(profile: Profile) { super.init(profile: profile) [ Notification.Name.FirefoxAccountChanged, Notification.Name.DynamicFontChanged, Notification.Name.DatabaseWasReopened ].forEach { NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived), name: $0, object: nil) } self.tableView.register(SeparatorTableCell.self, forCellReuseIdentifier: BookmarkSeparatorCellIdentifier) self.tableView.register(BookmarkFolderTableViewCell.self, forCellReuseIdentifier: BookmarkFolderCellIdentifier) self.tableView.register(BookmarkFolderTableViewHeader.self, forHeaderFooterViewReuseIdentifier: BookmarkFolderHeaderViewIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) self.tableView.accessibilityIdentifier = "Bookmarks List" self.refreshControl = UIRefreshControl() self.tableView.addSubview(refreshControl!) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshControl?.addTarget(self, action: #selector(refreshBookmarks), for: .valueChanged) loadData() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) refreshControl?.removeTarget(self, action: #selector(refreshBookmarks), for: .valueChanged) } func loadData() { // If we've not already set a source for this panel, fetch a new model from // the root; otherwise, just use the existing source to select a folder. guard let source = self.source else { // Get all the bookmarks split by folders if let bookmarkFolder = bookmarkFolder { profile.bookmarks.modelFactory >>== { $0.modelForFolder(bookmarkFolder).upon(self.onModelFetched) } } else { profile.bookmarks.modelFactory >>== { $0.modelForRoot().upon(self.onModelFetched) } } return } if let bookmarkFolder = bookmarkFolder { source.selectFolder(bookmarkFolder).upon(onModelFetched) } else { source.selectFolder(BookmarkRoots.MobileFolderGUID).upon(onModelFetched) } } @objc func notificationReceived(_ notification: Notification) { switch notification.name { case .FirefoxAccountChanged, .DynamicFontChanged: reloadData() case .DatabaseWasReopened: if let dbName = notification.object as? String, dbName == "browser.db" { reloadData() } default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } @objc fileprivate func refreshBookmarks() { profile.syncManager.mirrorBookmarks().upon { (_) in DispatchQueue.main.async { self.loadData() self.refreshControl?.endRefreshing() } } } fileprivate func createEmptyStateOverlayView() -> UIView { let overlayView = UIView() let logoImageView = UIImageView(image: UIImage.templateImageNamed("emptyBookmarks")) logoImageView.tintColor = UIColor.Photon.Grey60 overlayView.addSubview(logoImageView) logoImageView.snp.makeConstraints { make in make.centerX.equalTo(overlayView) make.size.equalTo(60) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(overlayView).offset(HomePanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(overlayView).offset(50) } let welcomeLabel = UILabel() overlayView.addSubview(welcomeLabel) welcomeLabel.text = emptyBookmarksText welcomeLabel.textAlignment = .center welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight welcomeLabel.numberOfLines = 0 welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp.makeConstraints { make in make.centerX.equalTo(overlayView) make.top.equalTo(logoImageView.snp.bottom).offset(BookmarksPanelUX.WelcomeScreenPadding) make.width.equalTo(BookmarksPanelUX.WelcomeScreenItemWidth) } overlayView.backgroundColor = UIColor.theme.homePanel.panelBackground welcomeLabel.textColor = UIColor.theme.homePanel.welcomeScreenText return overlayView } fileprivate func updateEmptyPanelState() { if source?.current.count == 0 && source?.current.guid == BookmarkRoots.MobileFolderGUID { if self.emptyStateOverlayView.superview == nil { self.view.addSubview(self.emptyStateOverlayView) self.view.bringSubview(toFront: self.emptyStateOverlayView) self.emptyStateOverlayView.snp.makeConstraints { make -> Void in make.edges.equalTo(self.tableView) } } } else { self.emptyStateOverlayView.removeFromSuperview() } } fileprivate func onModelFetched(_ result: Maybe<BookmarksModel>) { guard let model = result.successValue else { self.onModelFailure(result.failureValue as Any) return } self.onNewModel(model) } fileprivate func onNewModel(_ model: BookmarksModel) { if Thread.current.isMainThread { self.source = model self.tableView.reloadData() return } DispatchQueue.main.async { self.source = model self.tableView.reloadData() self.updateEmptyPanelState() } } fileprivate func onModelFailure(_ e: Any) { log.error("Error: failed to get data: \(e)") } override func reloadData() { self.source?.reloadData().upon(onModelFetched) } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == .began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } presentContextMenu(for: indexPath) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return source?.current.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let source = source, let bookmark = source.current[indexPath.row] else { return super.tableView(tableView, cellForRowAt: indexPath) } switch bookmark { case let item as BookmarkItem: let cell = super.tableView(tableView, cellForRowAt: indexPath) if item.title.isEmpty { cell.textLabel?.text = item.url } else { cell.textLabel?.text = item.title } if let url = bookmark.favicon?.url.asURL, url.scheme == "asset" { cell.imageView?.image = UIImage(named: url.host!) } else { cell.imageView?.layer.borderColor = UIColor.theme.homePanel.bookmarkIconBorder.cgColor cell.imageView?.layer.borderWidth = BookmarksPanelUX.IconBorderWidth let bookmarkURL = URL(string: item.url) cell.imageView?.setIcon(bookmark.favicon, forURL: bookmarkURL, completed: { (color, url) in if bookmarkURL == url { cell.imageView?.image = cell.imageView?.image?.createScaled(CGSize(width: BookmarksPanelUX.IconSize, height: BookmarksPanelUX.IconSize)) cell.imageView?.backgroundColor = color cell.imageView?.contentMode = .center } }) } return cell case is BookmarkSeparator: return tableView.dequeueReusableCell(withIdentifier: BookmarkSeparatorCellIdentifier, for: indexPath) case let bookmark as BookmarkFolder: let cell = tableView.dequeueReusableCell(withIdentifier: BookmarkFolderCellIdentifier, for: indexPath) cell.textLabel?.text = bookmark.title return cell default: // This should never happen. return super.tableView(tableView, cellForRowAt: indexPath) } } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let cell = cell as? BookmarkFolderTableViewCell { cell.textLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontHistoryPanel } } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // Don't show a header for the root if source == nil || parentFolders.isEmpty { return nil } guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: BookmarkFolderHeaderViewIdentifier) as? BookmarkFolderTableViewHeader else { return nil } // register as delegate to ensure we get notified when the user interacts with this header if header.delegate == nil { header.delegate = self } if parentFolders.count == 1 { header.textLabel?.text = NSLocalizedString("Bookmarks", comment: "Panel accessibility label") } else if let parentFolder = parentFolders.last { header.textLabel?.text = parentFolder.title } return header } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let it = self.source?.current[indexPath.row], it is BookmarkSeparator { return BookmarksPanelUX.SeparatorRowHeight } return super.tableView(tableView, heightForRowAt: indexPath) } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // Don't show a header for the root. If there's no root (i.e. source == nil), we'll also show no header. if source == nil || parentFolders.isEmpty { return 0 } return SiteTableViewControllerUX.RowHeight } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let header = view as? BookmarkFolderTableViewHeader { // for some reason specifying the font in header view init is being ignored, so setting it here header.textLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontHistoryPanel } } override func tableView(_ tableView: UITableView, hasFullWidthSeparatorForRowAtIndexPath indexPath: IndexPath) -> Bool { // Show a full-width border for cells above separators, so they don't have a weird step. // Separators themselves already have a full-width border, but let's force the issue // just in case. let this = self.source?.current[indexPath.row] if (indexPath.row + 1) < (self.source?.current.count)! { let below = self.source?.current[indexPath.row + 1] if this is BookmarkSeparator || below is BookmarkSeparator { return true } } return super.tableView(tableView, hasFullWidthSeparatorForRowAtIndexPath: indexPath) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) guard let source = source else { return } let bookmark = source.current[indexPath.row] switch bookmark { case let item as BookmarkItem: homePanelDelegate?.homePanel(didSelectURLString: item.url, visitType: VisitType.bookmark) LeanPlumClient.shared.track(event: .openedBookmark) UnifiedTelemetry.recordEvent(category: .action, method: .open, object: .bookmark, value: .bookmarksPanel) break case let folder as BookmarkFolder: log.debug("Selected \(folder.guid)") let nextController = BookmarksPanel(profile: profile) nextController.parentFolders = parentFolders + [source.current] nextController.bookmarkFolder = folder nextController.homePanelDelegate = self.homePanelDelegate source.modelFactory.uponQueue(.main) { maybe in guard let factory = maybe.successValue else { // Nothing we can do. return } let specificFactory = factory.factoryForIndex(indexPath.row, inFolder: source.current) nextController.source = BookmarksModel(modelFactory: specificFactory, root: folder) self.navigationController?.pushViewController(nextController, animated: true) } break default: // You can't do anything with separators. break } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { // Intentionally blank. Required to use UITableViewRowActions } private func editingStyleforRow(atIndexPath indexPath: IndexPath) -> UITableViewCellEditingStyle { guard let source = source else { return .none } if source.current[indexPath.row] is BookmarkSeparator { // Because the deletion block is too big. return .none } if source.current.itemIsEditableAtIndex(indexPath.row) { return .delete } return .none } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { guard let source = source else { return false } return source.current.itemIsEditableAtIndex(indexPath.row) } func tableView(_ tableView: UITableView, editingStyleForRowAtIndexPath indexPath: IndexPath) -> UITableViewCellEditingStyle { return editingStyleforRow(atIndexPath: indexPath) } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let editingStyle = editingStyleforRow(atIndexPath: indexPath) guard let source = self.source, editingStyle == .delete else { return nil } let title = NSLocalizedString("Delete", tableName: "BookmarkPanel", comment: "Action button for deleting bookmarks in the bookmarks panel.") let delete = UITableViewRowAction(style: .default, title: title, handler: { (action, indexPath) in self.deleteBookmark(indexPath: indexPath, source: source) UnifiedTelemetry.recordEvent(category: .action, method: .delete, object: .bookmark, value: .bookmarksPanel, extras: ["gesture": "swipe"]) }) return [delete] } func pinTopSite(_ site: Site) { _ = profile.history.addPinnedTopSite(site).value } func deleteBookmark(indexPath: IndexPath, source: BookmarksModel) { guard let bookmark = source.current[indexPath.row] else { return } assert(!(bookmark is BookmarkFolder)) if bookmark is BookmarkFolder { // TODO: check whether the folder is empty (excluding separators). If it isn't // then we must ask the user to confirm. Bug 1232810. log.debug("Not deleting folder.") return } log.debug("Removing rows \(indexPath).") // Block to do this -- this is UI code. guard let factory = source.modelFactory.value.successValue else { log.error("Couldn't get model factory. This is unexpected.") self.onModelFailure(DatabaseError(description: "Unable to get factory.")) return } let specificFactory = factory.factoryForIndex(indexPath.row, inFolder: source.current) if let err = specificFactory.removeByGUID(bookmark.guid).value.failureValue { log.debug("Failed to remove \(bookmark.guid).") self.onModelFailure(err) return } self.tableView.beginUpdates() self.source = source.removeGUIDFromCurrent(bookmark.guid) self.tableView.deleteRows(at: [indexPath], with: .left) self.tableView.endUpdates() self.updateEmptyPanelState() } override func applyTheme() { emptyStateOverlayView.removeFromSuperview() emptyStateOverlayView = createEmptyStateOverlayView() updateEmptyPanelState() super.applyTheme() } } extension BookmarksPanel: HomePanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { guard let bookmarkItem = source?.current[indexPath.row] as? BookmarkItem else { return nil } let site = Site(url: bookmarkItem.url, title: bookmarkItem.title, bookmarked: true, guid: bookmarkItem.guid) site.icon = bookmarkItem.favicon return site } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? { guard var actions = getDefaultContextMenuActions(for: site, homePanelDelegate: homePanelDelegate) else { return nil } let pinTopSite = PhotonActionSheetItem(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { action in self.pinTopSite(site) }) actions.append(pinTopSite) // Only local bookmarks can be removed guard let source = source else { return nil } if source.current.itemIsEditableAtIndex(indexPath.row) { let removeAction = PhotonActionSheetItem(title: Strings.RemoveBookmarkContextMenuTitle, iconString: "action_bookmark_remove", handler: { action in self.deleteBookmark(indexPath: indexPath, source: source) UnifiedTelemetry.recordEvent(category: .action, method: .delete, object: .bookmark, value: .bookmarksPanel, extras: ["gesture": "long-press"]) }) actions.append(removeAction) } return actions } } private protocol BookmarkFolderTableViewHeaderDelegate { func didSelectHeader() } extension BookmarksPanel: BookmarkFolderTableViewHeaderDelegate { fileprivate func didSelectHeader() { _ = self.navigationController?.popViewController(animated: true) } } class BookmarkFolderTableViewCell: TwoLineTableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) imageView?.image = UIImage(named: "bookmarkFolder") accessoryType = .disclosureIndicator separatorInset = .zero } override func layoutSubviews() { super.layoutSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func applyTheme() { super.applyTheme() self.backgroundColor = UIColor.theme.homePanel.bookmarkFolderBackground textLabel?.backgroundColor = UIColor.clear textLabel?.textColor = UIColor.theme.homePanel.bookmarkFolderText } } fileprivate class BookmarkFolderTableViewHeader: UITableViewHeaderFooterView { var delegate: BookmarkFolderTableViewHeaderDelegate? let titleLabel = UILabel() let topBorder = UIView() let bottomBorder = UIView() lazy var chevron: ChevronView = { let chevron = ChevronView(direction: .left) chevron.tintColor = UIColor.theme.general.highlightBlue chevron.lineWidth = BookmarksPanelUX.BookmarkFolderChevronLineWidth return chevron }() override var textLabel: UILabel? { return titleLabel } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) isUserInteractionEnabled = true let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewWasTapped)) tapGestureRecognizer.numberOfTapsRequired = 1 addGestureRecognizer(tapGestureRecognizer) addSubview(topBorder) addSubview(bottomBorder) contentView.addSubview(chevron) contentView.addSubview(titleLabel) chevron.snp.makeConstraints { make in make.leading.equalTo(contentView).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset) make.centerY.equalTo(contentView) make.size.equalTo(BookmarksPanelUX.BookmarkFolderChevronSize) } titleLabel.snp.makeConstraints { make in make.leading.equalTo(chevron.snp.trailing).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset) make.trailing.greaterThanOrEqualTo(contentView).offset(-BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset) make.centerY.equalTo(contentView) } topBorder.snp.makeConstraints { make in make.left.right.equalTo(self) make.top.equalTo(self).offset(-0.5) make.height.equalTo(0.5) } bottomBorder.snp.makeConstraints { make in make.left.right.bottom.equalTo(self) make.height.equalTo(0.5) } applyTheme() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc fileprivate func viewWasTapped(_ gestureRecognizer: UITapGestureRecognizer) { delegate?.didSelectHeader() } override func prepareForReuse() { super.prepareForReuse() applyTheme() } func applyTheme() { titleLabel.textColor = UIColor.theme.homePanel.bookmarkCurrentFolderText topBorder.backgroundColor = UIColor.theme.homePanel.siteTableHeaderBorder bottomBorder.backgroundColor = UIColor.theme.homePanel.siteTableHeaderBorder contentView.backgroundColor = UIColor.theme.homePanel.bookmarkBackNavCellBackground } }
mpl-2.0
4a26b2a26717ff31670834ecefd62e02
40.49183
278
0.673965
5.537069
false
false
false
false
robrix/Hammer.swift
Hammer/Fixpoint.swift
1
2376
// Copyright (c) 2014 Rob Rix. All rights reserved. func fixpoint<Parameter : Identifiable, Result> (initial: Result, body: (Parameter -> Result, Parameter) -> Result) -> Parameter -> Result { return fixpoint(initial, { $0.identity }, body) } func fixpoint<Parameter : Identifiable, Result> (initial: Result, body: ((Parameter, Parameter) -> Result, (Parameter, Parameter)) -> Result) -> (Parameter, Parameter) -> Result { return fixpoint(initial, { HashablePair($0.0, $0.1) }, body) } /// Construct a memoizing recursive function. /// /// The returned function is suitable for use in traversing cyclic graphs recursively; parameters are looked up in the cache, and if this lookup fails, then the \c initial value is memoized, the body function is called, and its result memoized. /// /// Recursion should occur via the \c recur parameter to the body function. /// /// Initially adapted from the \c memoize function in WWDC2014 session 404 Advanced Swift. func fixpoint<Parameter, Result, Decorator : Hashable>(initial: Result, wrap: Parameter -> Decorator, body: (Parameter -> Result, Parameter) -> Result) -> Parameter -> Result { var memo = Dictionary<Decorator, Result>() var recursive: (Parameter -> Result)! recursive = { parameter in let key = wrap(parameter) if let found = memo[key] { return found } memo[key] = initial let result = body(recursive, parameter) memo[key] = result return result } return recursive } /// A pair which distributes hashing and equality over its members. This is an implementation detail. struct HashablePair<T : Identifiable, U : Identifiable> { let left: T let right: U init(_ a: T, _ b: U) { left = a right = b } } /// Return an ObjectIdentifier for \c a if possible. Will be \c None for non-class instances, and \c Some for class instances. func identify<T>(a: T) -> ObjectIdentifier? { return reflect(a).objectIdentifier } /// Distribute equality over hashable pairs. func == <T, U> (a: HashablePair<T, U>, b: HashablePair<T, U>) -> Bool { return a.left.identity == b.left.identity && a.right.identity == b.right.identity } extension HashablePair : Hashable { // This is a poor way to distribute hashing over a pair; it’s convenient, but it’s not a good implementation detail to rely upon or emulate. var hashValue: Int { return left.identity.hashValue ^ right.identity.hashValue } }
mit
28de4bb1910f1c7901fba86cb386893a
37.885246
244
0.713744
3.723705
false
false
false
false
narner/AudioKit
Examples/iOS/AnalogSynthX/AnalogSynthX/SynthViewController.swift
1
24947
// // SynthViewController.swift // Swift Synth // // Created by Matthew Fecher on 1/8/16. // Copyright © 2016 AudioKit. All rights reserved. // import AudioKit import AudioKitUI import UIKit class SynthViewController: UIViewController { // ********************************************************* // MARK: - Instance Properties // ********************************************************* @IBOutlet fileprivate weak var statusLabel: UILabel! @IBOutlet fileprivate weak var octavePositionLabel: UILabel! @IBOutlet fileprivate weak var oscMixKnob: Knob! @IBOutlet fileprivate weak var osc1SemitonesKnob: Knob! @IBOutlet fileprivate weak var osc2SemitonesKnob: Knob! @IBOutlet fileprivate weak var osc2DetuneKnob: Knob! @IBOutlet fileprivate weak var lfoAmtKnob: Knob! @IBOutlet fileprivate weak var lfoRateKnob: Knob! @IBOutlet fileprivate weak var crushAmtKnob: Knob! @IBOutlet fileprivate weak var delayTimeKnob: Knob! @IBOutlet fileprivate weak var delayMixKnob: Knob! @IBOutlet fileprivate weak var reverbAmtKnob: Knob! @IBOutlet fileprivate weak var reverbMixKnob: Knob! @IBOutlet fileprivate weak var cutoffKnob: Knob! @IBOutlet fileprivate weak var rezKnob: Knob! @IBOutlet fileprivate weak var subMixKnob: Knob! @IBOutlet fileprivate weak var fmMixKnob: Knob! @IBOutlet fileprivate weak var fmModKnob: Knob! @IBOutlet fileprivate weak var noiseMixKnob: Knob! @IBOutlet fileprivate weak var morphKnob: Knob! @IBOutlet fileprivate weak var masterVolKnob: Knob! @IBOutlet fileprivate weak var attackSlider: VerticalSlider! @IBOutlet fileprivate weak var decaySlider: VerticalSlider! @IBOutlet fileprivate weak var sustainSlider: VerticalSlider! @IBOutlet fileprivate weak var releaseSlider: VerticalSlider! @IBOutlet fileprivate weak var vco1Toggle: UIButton! @IBOutlet fileprivate weak var vco2Toggle: UIButton! @IBOutlet fileprivate weak var bitcrushToggle: UIButton! @IBOutlet fileprivate weak var filterToggle: UIButton! @IBOutlet fileprivate weak var delayToggle: UIButton! @IBOutlet fileprivate weak var reverbToggle: UIButton! @IBOutlet fileprivate weak var fattenToggle: UIButton! @IBOutlet fileprivate weak var holdToggle: UIButton! @IBOutlet fileprivate weak var monoToggle: UIButton! @IBOutlet weak var audioPlot: AKNodeOutputPlot! @IBOutlet fileprivate weak var plotToggle: UIButton! enum ControlTag: Int { case cutoff = 101 case rez = 102 case vco1Waveform = 103 case vco2Waveform = 104 case vco1Semitones = 105 case vco2Semitones = 106 case vco2Detune = 107 case oscMix = 108 case subMix = 109 case fmMix = 110 case fmMod = 111 case lfoWaveform = 112 case morph = 113 case noiseMix = 114 case lfoAmt = 115 case lfoRate = 116 case crushAmt = 117 case delayTime = 118 case delayMix = 119 case reverbAmt = 120 case reverbMix = 121 case masterVol = 122 case adsrAttack = 123 case adsrDecay = 124 case adsrSustain = 125 case adsrRelease = 126 } var keyboardOctavePosition: Int = 0 var lastKey: UIButton? var monoMode: Bool = false var holdMode: Bool = false var midiNotesHeld = [MIDINoteNumber]() let blackKeys = [49, 51, 54, 56, 58, 61, 63, 66, 68, 70] var conductor = Conductor.sharedInstance // ********************************************************* // MARK: - viewDidLoad // ********************************************************* override func viewDidLoad() { super.viewDidLoad() // Create WaveformSegmentedViews createWaveFormSegmentViews() // Set Delegates setDelegates() // Set Preset Control Values setDefaultValues() // Greeting statusLabel.text = String.randomGreeting() } // ********************************************************* // MARK: - Defaults/Presets // ********************************************************* func setDefaultValues() { // Set Preset Values conductor.masterVolume.volume = 1.0 // Master Volume conductor.core.offset2 = 0 // VCO2 Semitones conductor.core.vco2.vibratoDepth = 0.0 // VCO2 Detune (Hz) conductor.core.vco2.vibratoRate = 1.0 // VCO2 Detune (Hz) conductor.core.vcoBalancer.balance = 0.5 // VCO1/VCO2 Mix conductor.core.subOscMixer.volume = 0.0 // SubOsc Mix conductor.core.fmOscMixer.volume = 0.0 // FM Mix conductor.core.fmOsc.modulationIndex = 0.0 // FM Modulation Amt conductor.core.morph = 0.0 // Morphing between waveforms conductor.core.noiseMixer.volume = 0.0 // Noise Mix conductor.filterSection.lfoAmplitude = 0.0 // LFO Amp (Hz) conductor.filterSection.lfoRate = 1.4 // LFO Rate conductor.filterSection.resonance = 0.5 // Filter Q/Rez conductor.multiDelay.time = 0.5 // Delay (seconds) conductor.multiDelay.mix = 0.5 // Dry/Wet conductor.reverb.feedback = 0.88 // Amt conductor.reverbMixer.balance = 0.4 // Dry/Wet conductor.midiBendRange = 2.0 // MIDI bend range in +/- semitones cutoffKnob.value = 0.36 // Cutoff Knob Position crushAmtKnob.value = 0.0 // Crusher Knob Position // ADSR conductor.core.attackDuration = 0.1 conductor.core.decayDuration = 0.1 conductor.core.sustainLevel = 0.66 conductor.core.releaseDuration = 0.5 // Update Knob & Slider UI Values setupKnobValues() setupSliderValues() // Update Toggle Presets displayModeToggled(plotToggle) vco1Toggled(vco1Toggle) vco2Toggled(vco2Toggle) filterToggled(filterToggle) delayToggled(delayToggle) reverbToggled(reverbToggle) } func setupKnobValues() { osc1SemitonesKnob.minimum = -12 osc1SemitonesKnob.maximum = 12 osc1SemitonesKnob.value = Double(conductor.core.offset1) osc2SemitonesKnob.minimum = -12 osc2SemitonesKnob.maximum = 12 osc2SemitonesKnob.value = Double(conductor.core.offset2) osc2DetuneKnob.minimum = -0.25 osc2DetuneKnob.maximum = 0.25 osc2DetuneKnob.value = conductor.core.vco2.vibratoDepth subMixKnob.maximum = 1.0 subMixKnob.value = conductor.core.subOscMixer.volume fmMixKnob.maximum = 1.25 fmMixKnob.value = conductor.core.fmOscMixer.volume fmModKnob.maximum = 15 morphKnob.minimum = -0.99 morphKnob.maximum = 0.99 morphKnob.value = conductor.core.morph noiseMixKnob.value = conductor.core.noiseMixer.volume oscMixKnob.value = conductor.core.vcoBalancer.balance lfoAmtKnob.maximum = 1_200 lfoAmtKnob.value = conductor.filterSection.lfoAmplitude lfoRateKnob.maximum = 5 lfoRateKnob.value = conductor.filterSection.lfoRate rezKnob.maximum = 0.99 rezKnob.value = conductor.filterSection.resonance delayTimeKnob.value = conductor.multiDelay.time delayMixKnob.value = conductor.multiDelay.mix reverbAmtKnob.maximum = 0.99 reverbAmtKnob.value = conductor.reverb.feedback reverbMixKnob.value = conductor.reverbMixer.balance masterVolKnob.maximum = 1.0 masterVolKnob.value = conductor.masterVolume.volume // Calculate Logarithmic scales based on knob position conductor.filterSection.cutoffFrequency = cutoffFreqFromValue(Double(cutoffKnob.value)) conductor.bitCrusher.sampleRate = crusherFreqFromValue(Double(crushAmtKnob.value)) conductor.bitCrusher.bitDepth = 8 } func setupSliderValues() { attackSlider.maxValue = 1.0 attackSlider.currentValue = CGFloat(conductor.core.attackDuration) decaySlider.maxValue = 1.0 decaySlider.currentValue = CGFloat(conductor.core.decayDuration) sustainSlider.currentValue = CGFloat(conductor.core.sustainLevel) releaseSlider.maxValue = 2 releaseSlider.currentValue = CGFloat(conductor.core.releaseDuration) } //***************************************************************** // MARK: - IBActions //***************************************************************** @IBAction func vco1Toggled(_ sender: UIButton) { if sender.isSelected { sender.isSelected = false statusLabel.text = "VCO 1 Off" conductor.core.vco1On = false } else { sender.isSelected = true statusLabel.text = "VCO 1 On" conductor.core.vco1On = true } } @IBAction func vco2Toggled(_ sender: UIButton) { if sender.isSelected { sender.isSelected = false statusLabel.text = "VCO 2 Off" conductor.core.vco2On = false } else { sender.isSelected = true statusLabel.text = "VCO 2 On" conductor.core.vco2On = true } } @IBAction func crusherToggled(_ sender: UIButton) { if sender.isSelected { sender.isSelected = false statusLabel.text = "Bitcrush Off" conductor.bitCrusher.bypass() } else { sender.isSelected = true statusLabel.text = "Bitcrush On" conductor.bitCrusher.start() } } @IBAction func filterToggled(_ sender: UIButton) { if sender.isSelected { sender.isSelected = false statusLabel.text = "Filter Off" conductor.filterSection.output.stop() } else { sender.isSelected = true statusLabel.text = "Filter On" conductor.filterSection.output.start() } } @IBAction func delayToggled(_ sender: UIButton) { if sender.isSelected { sender.isSelected = false statusLabel.text = "Delay Off" conductor.multiDelayMixer.balance = 0 } else { sender.isSelected = true statusLabel.text = "Delay On" conductor.multiDelayMixer.balance = 1 } } @IBAction func reverbToggled(_ sender: UIButton) { if sender.isSelected { sender.isSelected = false statusLabel.text = "Reverb Off" conductor.reverb.bypass() } else { sender.isSelected = true statusLabel.text = "Reverb On" conductor.reverb.start() } } @IBAction func stereoFattenToggled(_ sender: UIButton) { if sender.isSelected { sender.isSelected = false statusLabel.text = "Stereo Fatten Off" conductor.fatten.dryWetMix.balance = 0 } else { sender.isSelected = true statusLabel.text = "Stereo Fatten On" conductor.fatten.dryWetMix.balance = 1 } } // Keyboard @IBAction func octaveDownPressed(_ sender: UIButton) { guard keyboardOctavePosition > -2 else { statusLabel.text = "How low can you go? This low." return } keyboardOctavePosition += -1 octavePositionLabel.text = String(keyboardOctavePosition) redisplayHeldKeys() } @IBAction func octaveUpPressed(_ sender: UIButton) { guard keyboardOctavePosition < 3 else { statusLabel.text = "Captain, she can't go any higher!" return } keyboardOctavePosition += 1 octavePositionLabel.text = String(keyboardOctavePosition) redisplayHeldKeys() } @IBAction func holdModeToggled(_ sender: UIButton) { if sender.isSelected { sender.isSelected = false statusLabel.text = "Hold Mode Off" holdMode = false turnOffHeldKeys() } else { sender.isSelected = true statusLabel.text = "Hold Mode On" holdMode = true } } @IBAction func monoModeToggled(_ sender: UIButton) { if sender.isSelected { sender.isSelected = false statusLabel.text = "Mono Mode Off" monoMode = false } else { sender.isSelected = true statusLabel.text = "Mono Mode On" monoMode = true turnOffHeldKeys() } } // Universal @IBAction func midiPanicPressed(_ sender: RoundedButton) { turnOffHeldKeys() statusLabel.text = "All Notes Off" } @IBAction func displayModeToggled(_ sender: UIButton) { if sender.isSelected { sender.isSelected = false statusLabel.text = "Wave Display Filled Off" audioPlot.shouldFill = false } else { sender.isSelected = true statusLabel.text = "Wave Display Filled On" audioPlot.shouldFill = true } } // About App @IBAction func buildThisSynth(_ sender: RoundedButton) { openURL("http://audiokit.io/examples/AnalogSynthX") } @IBAction func newAppPressed(_ sender: RoundedButton) { openURL("https://audiokitpro.com/audiokit-synth-one/") } //***************************************************************** // MARK: - 🎹 Key Presses //***************************************************************** @IBAction func keyPressed(_ sender: UIButton) { let key = sender // Turn off last key press in Mono if monoMode { if let lastKey = lastKey { turnOffKey(lastKey) } } // Toggle key if in Hold mode if holdMode { if midiNotesHeld.contains(midiNoteFromTag(key.tag)) { turnOffKey(key) return } } turnOnKey(key) lastKey = key } @IBAction func keyReleased(_ sender: UIButton) { let key = sender if holdMode && monoMode { toggleMonoKeyHeld(key) } else if holdMode && !monoMode { toggleKeyHeld(key) } else { turnOffKey(key) } } // ********************************************************* // MARK: - 🎹 Key UI/UX Helpers // ********************************************************* func turnOnKey(_ key: UIButton) { updateKeyToDownPosition(key) let midiNote = midiNoteFromTag(key.tag) statusLabel.text = "Key Pressed: \(noteNameFromMidiNote(midiNote))" conductor.core.play(noteNumber: midiNote, velocity: 127) } func turnOffKey(_ key: UIButton) { updateKeyToUpPosition(key) statusLabel.text = "Key Released" conductor.core.stop(noteNumber: midiNoteFromTag(key.tag)) } func turnOffHeldKeys() { updateAllKeysToUpPosition() for note in 0...127 { conductor.core.stop(noteNumber: MIDINoteNumber(note)) } midiNotesHeld.removeAll(keepingCapacity: false) } func updateAllKeysToUpPosition() { // Key up all keys shown on display for tag in 248...272 { guard let key = self.view.viewWithTag(tag) as? UIButton else { return } updateKeyToUpPosition(key) } } func redisplayHeldKeys() { // Determine new keyboard bounds let lowerMidiNote = MIDINoteNumber(48 + (keyboardOctavePosition * 12)) let upperMidiNote = lowerMidiNote + 24 statusLabel.text = "Keyboard Range: " + "\(noteNameFromMidiNote(lowerMidiNote)) to " + "\(noteNameFromMidiNote(upperMidiNote))" guard !monoMode else { turnOffHeldKeys() return } // Refresh keyboard updateAllKeysToUpPosition() // Check notes currently in view and turn on if held for note in lowerMidiNote...upperMidiNote { if midiNotesHeld.contains(note) { let keyTag = (Int(note) - (keyboardOctavePosition * 12)) + 200 guard let key = self.view.viewWithTag(keyTag) as? UIButton else { return } updateKeyToDownPosition(key) } } } func toggleKeyHeld(_ key: UIButton) { if let i = midiNotesHeld.index(of: midiNoteFromTag(key.tag)) { midiNotesHeld.remove(at: i) } else { midiNotesHeld.append(midiNoteFromTag(key.tag)) } } func toggleMonoKeyHeld(_ key: UIButton) { if midiNotesHeld.contains(midiNoteFromTag(key.tag)) { midiNotesHeld.removeAll() } else { midiNotesHeld.removeAll() midiNotesHeld.append(midiNoteFromTag(key.tag)) } } func updateKeyToUpPosition(_ key: UIButton) { let index = key.tag - 200 if blackKeys.contains(index) { key.setImage(#imageLiteral(resourceName: "blackkey"), for: UIControlState()) } else { key.setImage(#imageLiteral(resourceName: "whitekey"), for: UIControlState()) } } func updateKeyToDownPosition(_ key: UIButton) { let index = key.tag - 200 if blackKeys.contains(index) { key.setImage(#imageLiteral(resourceName:"blackkey_selected"), for: UIControlState()) } else { key.setImage(#imageLiteral(resourceName: "whitekey_selected"), for: UIControlState()) } } func midiNoteFromTag(_ tag: Int) -> MIDINoteNumber { return MIDINoteNumber((tag - 200) + (keyboardOctavePosition * 12)) } } //***************************************************************** // MARK: - 🎛 Knob Delegates //***************************************************************** extension SynthViewController: KnobDelegate { func updateKnobValue(_ value: Double, tag: Int) { switch tag { // VCOs case ControlTag.vco1Semitones.rawValue: let intValue = Int(floor(value)) statusLabel.text = "Semitones: \(intValue)" conductor.core.offset1 = intValue case ControlTag.vco2Semitones.rawValue: let intValue = Int(floor(value)) statusLabel.text = "Semitones: \(intValue)" conductor.core.offset2 = intValue case ControlTag.vco2Detune.rawValue: statusLabel.text = "Detune: \(value.decimalString) Hz" conductor.core.vco2.vibratoDepth = value case ControlTag.oscMix.rawValue: statusLabel.text = "OscMix: \(value.decimalString)" conductor.core.vcoBalancer.balance = value case ControlTag.morph.rawValue: statusLabel.text = "Morph Waveform: \(value.decimalString)" conductor.core.morph = value // Additional OSCs case ControlTag.subMix.rawValue: statusLabel.text = "Sub Osc: \(subMixKnob.knobValue.percentageString)" conductor.core.subOscMixer.volume = value case ControlTag.fmMix.rawValue: statusLabel.text = "FM Amt: \(fmMixKnob.knobValue.percentageString)" conductor.core.fmOscMixer.volume = value case ControlTag.fmMod.rawValue: statusLabel.text = "FM Mod: \(fmModKnob.knobValue.percentageString)" conductor.core.fmOsc.modulationIndex = value case ControlTag.noiseMix.rawValue: statusLabel.text = "Noise Amt: \(noiseMixKnob.knobValue.percentageString)" conductor.core.noiseMixer.volume = value // LFO case ControlTag.lfoAmt.rawValue: statusLabel.text = "LFO Amp: \(value.decimalString) Hz" conductor.filterSection.lfoAmplitude = value case ControlTag.lfoRate.rawValue: statusLabel.text = "LFO Rate: \(value.decimalString)" conductor.filterSection.lfoRate = value // Filter case ControlTag.cutoff.rawValue: let cutOffFrequency = cutoffFreqFromValue(value) statusLabel.text = "Cutoff: \(cutOffFrequency.decimalString) Hz" conductor.filterSection.cutoffFrequency = cutOffFrequency case ControlTag.rez.rawValue: statusLabel.text = "Rez: \(value.decimalString)" conductor.filterSection.resonance = value // Crusher case ControlTag.crushAmt.rawValue: let crushAmt = crusherFreqFromValue(value) statusLabel.text = "Bitcrush: \(crushAmt.decimalString) Sample Rate" conductor.bitCrusher.sampleRate = crushAmt // Delay case ControlTag.delayTime.rawValue: statusLabel.text = "Delay Time: \(value.decimal1000String) ms" conductor.multiDelay.time = value case ControlTag.delayMix.rawValue: statusLabel.text = "Delay Mix: \(value.decimalString)" conductor.multiDelay.mix = value // Reverb case ControlTag.reverbAmt.rawValue: if value == 0.99 { statusLabel.text = "Reverb Size: Grand Canyon!" } else { statusLabel.text = "Reverb Size: \(reverbAmtKnob.knobValue.percentageString)" } conductor.reverb.feedback = value case ControlTag.reverbMix.rawValue: statusLabel.text = "Reverb Mix: \(value.decimalString)" conductor.reverbMixer.balance = value // Master case ControlTag.masterVol.rawValue: statusLabel.text = "Master Vol: \(masterVolKnob.knobValue.percentageString)" conductor.masterVolume.volume = value default: break } } } //***************************************************************** // MARK: - 🎚Slider Delegate (ADSR) //***************************************************************** extension SynthViewController: VerticalSliderDelegate { func sliderValueDidChange(_ value: Double, tag: Int) { switch tag { case ControlTag.adsrAttack.rawValue: statusLabel.text = "Attack: \(attackSlider.sliderValue.percentageString)" conductor.core.attackDuration = value case ControlTag.adsrDecay.rawValue: statusLabel.text = "Decay: \(decaySlider.sliderValue.percentageString)" conductor.core.decayDuration = value case ControlTag.adsrSustain.rawValue: statusLabel.text = "Sustain: \(sustainSlider.sliderValue.percentageString)" conductor.core.sustainLevel = value case ControlTag.adsrRelease.rawValue: statusLabel.text = "Release: \(releaseSlider.sliderValue.percentageString)" conductor.core.releaseDuration = value default: break } } } //***************************************************************** // MARK: - WaveformSegmentedView Delegate //***************************************************************** extension SynthViewController: SMSegmentViewDelegate { // SMSegment Delegate func segmentView(_ segmentView: SMBasicSegmentView, didSelectSegmentAtIndex index: Int) { switch segmentView.tag { case ControlTag.vco1Waveform.rawValue: conductor.core.waveform1 = Double(index) statusLabel.text = "VCO1 Waveform Changed" case ControlTag.vco2Waveform.rawValue: conductor.core.waveform2 = Double(index) statusLabel.text = "VCO2 Waveform Changed" case ControlTag.lfoWaveform.rawValue: statusLabel.text = "LFO Waveform Changed" conductor.filterSection.lfoIndex = min(Double(index), 3) default: break } } } //***************************************************************** // MARK: - Set Delegates //***************************************************************** extension SynthViewController { func setDelegates() { oscMixKnob.delegate = self cutoffKnob.delegate = self rezKnob.delegate = self osc1SemitonesKnob.delegate = self osc2SemitonesKnob.delegate = self osc2DetuneKnob.delegate = self lfoAmtKnob.delegate = self lfoRateKnob.delegate = self crushAmtKnob.delegate = self delayTimeKnob.delegate = self delayMixKnob.delegate = self reverbAmtKnob.delegate = self reverbMixKnob.delegate = self subMixKnob.delegate = self fmMixKnob.delegate = self fmModKnob.delegate = self morphKnob.delegate = self noiseMixKnob.delegate = self masterVolKnob.delegate = self attackSlider.delegate = self decaySlider.delegate = self sustainSlider.delegate = self releaseSlider.delegate = self } }
mit
813aa04e412b4096bcd608e231b81785
32.877717
97
0.589396
4.993791
false
false
false
false
garricn/secret
Pods/Cartography/Cartography/Property.swift
4
7569
// // Property.swift // Cartography // // Created by Robert Böhnke on 17/06/14. // Copyright (c) 2014 Robert Böhnke. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public protocol Property { var attribute: NSLayoutAttribute { get } var context: Context { get } var view: View { get } } // MARK: Equality /// Properties conforming to this protocol can use the `==` operator with /// numerical constants. public protocol NumericalEquality : Property { } /// Declares a property equal to a numerical constant. /// /// - parameter lhs: The affected property. The associated view will have /// `translatesAutoresizingMaskIntoConstraints` set to `false`. /// - parameter rhs: The numerical constant. /// /// - returns: An `NSLayoutConstraint`. /// public func == (lhs: NumericalEquality, rhs: CGFloat) -> NSLayoutConstraint { return lhs.context.addConstraint(lhs, coefficients: Coefficients(1, rhs)) } /// Properties conforming to this protocol can use the `==` operator with other /// properties of the same type. public protocol RelativeEquality : Property { } /// Declares a property equal to a the result of an expression. /// /// - parameter lhs: The affected property. The associated view will have /// `translatesAutoresizingMaskIntoConstraints` set to `false`. /// - parameter rhs: The expression. /// /// - returns: An `NSLayoutConstraint`. /// public func == <P: RelativeEquality>(lhs: P, rhs: Expression<P>) -> NSLayoutConstraint { return lhs.context.addConstraint(lhs, coefficients: rhs.coefficients[0], to: rhs.value) } /// Declares a property equal to another property. /// /// - parameter lhs: The affected property. The associated view will have /// `translatesAutoresizingMaskIntoConstraints` set to `false`. /// - parameter rhs: The other property. /// public func == <P: RelativeEquality>(lhs: P, rhs: P) -> NSLayoutConstraint { return lhs.context.addConstraint(lhs, to: rhs) } // MARK: Inequality /// Properties conforming to this protocol can use the `<=` and `>=` operators /// with numerical constants. public protocol NumericalInequality : Property { } /// Declares a property less than or equal to a numerical constant. /// /// - parameter lhs: The affected property. The associated view will have /// `translatesAutoresizingMaskIntoConstraints` set to `false`. /// - parameter rhs: The numerical constant. /// /// - returns: An `NSLayoutConstraint`. /// public func <= (lhs: NumericalInequality, rhs: CGFloat) -> NSLayoutConstraint { return lhs.context.addConstraint(lhs, coefficients: Coefficients(1, rhs), relation: NSLayoutRelation.LessThanOrEqual) } /// Declares a property greater than or equal to a numerical constant. /// /// - parameter lhs: The affected property. The associated view will have /// `translatesAutoresizingMaskIntoConstraints` set to `false`. /// - parameter rhs: The numerical constant. /// /// - returns: An `NSLayoutConstraint`. /// public func >= (lhs: NumericalInequality, rhs: CGFloat) -> NSLayoutConstraint { return lhs.context.addConstraint(lhs, coefficients: Coefficients(1, rhs), relation: NSLayoutRelation.GreaterThanOrEqual) } /// Properties conforming to this protocol can use the `<=` and `>=` operators /// with other properties of the same type. public protocol RelativeInequality : Property { } /// Declares a property less than or equal to another property. /// /// - parameter lhs: The affected property. The associated view will have /// `translatesAutoresizingMaskIntoConstraints` set to `false`. /// - parameter rhs: The other property. /// /// - returns: An `NSLayoutConstraint`. /// public func <= <P: RelativeInequality>(lhs: P, rhs: P) -> NSLayoutConstraint { return lhs.context.addConstraint(lhs, to: rhs, relation: NSLayoutRelation.LessThanOrEqual) } /// Declares a property greater than or equal to another property. /// /// - parameter lhs: The affected property. The associated view will have /// `translatesAutoresizingMaskIntoConstraints` set to `false`. /// - parameter rhs: The other property. /// /// - returns: An `NSLayoutConstraint`. /// public func >= <P: RelativeInequality>(lhs: P, rhs: P) -> NSLayoutConstraint { return lhs.context.addConstraint(lhs, to: rhs, relation: NSLayoutRelation.GreaterThanOrEqual) } /// Declares a property less than or equal to the result of an expression. /// /// - parameter lhs: The affected property. The associated view will have /// `translatesAutoresizingMaskIntoConstraints` set to `false`. /// - parameter rhs: The other property. /// /// - returns: An `NSLayoutConstraint`. /// public func <= <P: RelativeInequality>(lhs: P, rhs: Expression<P>) -> NSLayoutConstraint { return lhs.context.addConstraint(lhs, coefficients: rhs.coefficients[0], to: rhs.value, relation: NSLayoutRelation.LessThanOrEqual) } /// Declares a property greater than or equal to the result of an expression. /// /// - parameter lhs: The affected property. The associated view will have /// `translatesAutoresizingMaskIntoConstraints` set to `false`. /// - parameter rhs: The other property. /// /// - returns: An `NSLayoutConstraint`. /// public func >= <P: RelativeInequality>(lhs: P, rhs: Expression<P>) -> NSLayoutConstraint { return lhs.context.addConstraint(lhs, coefficients: rhs.coefficients[0], to: rhs.value, relation: NSLayoutRelation.GreaterThanOrEqual) } // MARK: Addition public protocol Addition : Property { } public func + <P: Addition>(c: CGFloat, rhs: P) -> Expression<P> { return Expression(rhs, [ Coefficients(1, c) ]) } public func + <P: Addition>(lhs: P, rhs: CGFloat) -> Expression<P> { return rhs + lhs } public func + <P: Addition>(c: CGFloat, rhs: Expression<P>) -> Expression<P> { return Expression(rhs.value, rhs.coefficients.map { $0 + c }) } public func + <P: Addition>(lhs: Expression<P>, rhs: CGFloat) -> Expression<P> { return rhs + lhs } public func - <P: Addition>(c: CGFloat, rhs: P) -> Expression<P> { return Expression(rhs, [ Coefficients(1, -c) ]) } public func - <P: Addition>(lhs: P, rhs: CGFloat) -> Expression<P> { return rhs - lhs } public func - <P: Addition>(c: CGFloat, rhs: Expression<P>) -> Expression<P> { return Expression(rhs.value, rhs.coefficients.map { $0 - c}) } public func - <P: Addition>(lhs: Expression<P>, rhs: CGFloat) -> Expression<P> { return rhs - lhs } #if os(iOS) || os(tvOS) public func + (lhs: LayoutSupport, c : CGFloat) -> Expression<LayoutSupport> { return Expression<LayoutSupport>(lhs, [Coefficients(1, c)]) } public func - (lhs: LayoutSupport, c : CGFloat) -> Expression<LayoutSupport> { return lhs + (-c) } #endif // MARK: Multiplication public protocol Multiplication : Property { } public func * <P: Multiplication>(m: CGFloat, rhs: Expression<P>) -> Expression<P> { return Expression(rhs.value, rhs.coefficients.map { $0 * m }) } public func * <P: Multiplication>(lhs: Expression<P>, rhs: CGFloat) -> Expression<P> { return rhs * lhs } public func * <P: Multiplication>(m: CGFloat, rhs: P) -> Expression<P> { return Expression(rhs, [ Coefficients(m, 0) ]) } public func * <P: Multiplication>(lhs: P, rhs: CGFloat) -> Expression<P> { return rhs * lhs } public func / <P: Multiplication>(lhs: Expression<P>, rhs: CGFloat) -> Expression<P> { return lhs * (1 / rhs) } public func / <P: Multiplication>(lhs: P, rhs: CGFloat) -> Expression<P> { return lhs * (1 / rhs) }
mit
7d262401a0d9f6cec60a47b104f19dbb
33.395455
138
0.690895
4.046524
false
false
false
false
Rapid-SDK/ios
Source/RapidClasses/RapidServerEvents.swift
1
3603
// // RapidSocketError.swift // Rapid // // Created by Jan Schwarz on 17/03/2017. // Copyright © 2017 Rapid. All rights reserved. // import Foundation /// Acknowledgement event object /// /// This acknowledgement is sent by server as a response to a client request class RapidServerAcknowledgement: RapidServerResponse { let eventID: String init?(json: Any?) { guard let dict = json as? [AnyHashable: Any] else { return nil } guard let eventID = dict[RapidSerialization.EventID.name] as? String else { return nil } self.eventID = eventID } init(eventID: String) { self.eventID = eventID } } /// Acknowledgement event object /// /// This acknowledgement is sent to server as a response to a server event class RapidClientAcknowledgement: RapidClientEvent { let shouldSendOnReconnect = false let eventID: String init(eventID: String) { self.eventID = eventID } } extension RapidClientAcknowledgement: RapidSerializable { func serialize(withIdentifiers identifiers: [AnyHashable : Any]) throws -> String { return try RapidSerialization.serialize(acknowledgement: self) } } // MARK: Subscription cancelled /// Subscription cancel event object /// /// Subscription cancel is a sever event which occurs /// when a client has no longer permissions to read collection after reauthorization/deauthorization class RapidSubscriptionCancelled: RapidServerEvent { let eventIDsToAcknowledge: [String] let subscriptionID: String init?(json: Any?) { guard let dict = json as? [AnyHashable: Any] else { return nil } guard let eventID = dict[RapidSerialization.EventID.name] as? String else { return nil } guard let subID = dict[RapidSerialization.CollectionSubscriptionCancelled.SubscriptionID.name] as? String else { return nil } self.eventIDsToAcknowledge = [eventID] self.subscriptionID = subID } } // MARK: On-disconnect action cancelled /// On-disconnect action cancelled event object /// /// On-disconnect action cancelled is a server event which occurs /// when a client has no longer permissions to modify a document after reauthorization/deauthorization class RapidOnDisconnectActionCancelled: RapidServerEvent { let eventIDsToAcknowledge: [String] let actionID: String init?(json: [AnyHashable: Any]) { guard let eventID = json[RapidSerialization.EventID.name] as? String else { return nil } guard let actionID = json[RapidSerialization.DisconnectActionCancelled.ActionID.name] as? String else { return nil } self.eventIDsToAcknowledge = [eventID] self.actionID = actionID } } // MARK: Server timestamp /// Server timestamp event object /// `RapidServerTimestamp` is a response for a server timestamp request class RapidServerTimestamp: RapidServerEvent { let eventIDsToAcknowledge: [String] let timestamp: TimeInterval init?(withJSON json: [AnyHashable: Any]) { guard let eventID = json[RapidSerialization.EventID.name] as? String else { return nil } guard let timestamp = json[RapidSerialization.Timestamp.Timestamp.name] as? TimeInterval else { return nil } self.eventIDsToAcknowledge = [eventID] self.timestamp = timestamp/1000 } }
mit
538560f860bcfa2b7c9fe077493bd159
26.496183
120
0.658245
4.796272
false
false
false
false
alblue/swift
test/SILGen/closures.swift
1
42205
// RUN: %target-swift-emit-silgen -module-name closures -enable-sil-ownership -parse-stdlib -parse-as-library %s | %FileCheck %s // RUN: %target-swift-emit-silgen -module-name closures -enable-sil-ownership -parse-stdlib -parse-as-library %s | %FileCheck %s --check-prefix=GUARANTEED import Swift var zero = 0 // <rdar://problem/15921334> // CHECK-LABEL: sil hidden @$s8closures46return_local_generic_function_without_captures{{[_0-9a-zA-Z]*}}F : $@convention(thin) <A, R> () -> @owned @callee_guaranteed (@in_guaranteed A) -> @out R { func return_local_generic_function_without_captures<A, R>() -> (A) -> R { func f(_: A) -> R { Builtin.int_trap() } // CHECK: [[FN:%.*]] = function_ref @$s8closures46return_local_generic_function_without_captures{{[_0-9a-zA-Z]*}} : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0) -> @out τ_0_1 // CHECK: [[FN_WITH_GENERIC_PARAMS:%.*]] = partial_apply [callee_guaranteed] [[FN]]<A, R>() : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0) -> @out τ_0_1 // CHECK: return [[FN_WITH_GENERIC_PARAMS]] : $@callee_guaranteed (@in_guaranteed A) -> @out R return f } func return_local_generic_function_with_captures<A, R>(_ a: A) -> (A) -> R { func f(_: A) -> R { _ = a } return f } // CHECK-LABEL: sil hidden @$s8closures17read_only_captureyS2iF : $@convention(thin) (Int) -> Int { func read_only_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : @trivial $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int } // SEMANTIC ARC TODO: This is incorrect. We need to do the project_box on the copy. // CHECK: [[PROJECT:%.*]] = project_box [[XBOX]] // CHECK: store [[X]] to [trivial] [[PROJECT]] func cap() -> Int { return x } return cap() // CHECK: [[XBOX_BORROW:%.*]] = begin_borrow [[XBOX]] // SEMANTIC ARC TODO: See above. This needs to happen on the copy_valued box. // CHECK: mark_function_escape [[PROJECT]] // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:\$s8closures17read_only_capture.*]] : $@convention(thin) (@guaranteed { var Int }) -> Int // CHECK: [[RET:%[0-9]+]] = apply [[CAP]]([[XBOX_BORROW]]) // CHECK: end_borrow [[XBOX_BORROW]] // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] } // CHECK: } // end sil function '$s8closures17read_only_captureyS2iF' // CHECK: sil private @[[CAP_NAME]] // CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }): // CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]] // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int // CHECK: [[X:%[0-9]+]] = load [trivial] [[ACCESS]] // CHECK: return [[X]] // } // end sil function '[[CAP_NAME]]' // SEMANTIC ARC TODO: This is a place where we have again project_box too early. // CHECK-LABEL: sil hidden @$s8closures16write_to_captureyS2iF : $@convention(thin) (Int) -> Int { func write_to_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : @trivial $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: store [[X]] to [trivial] [[XBOX_PB]] // CHECK: [[X2BOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[X2BOX_PB:%.*]] = project_box [[X2BOX]] // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XBOX_PB]] : $*Int // CHECK: copy_addr [[ACCESS]] to [initialization] [[X2BOX_PB]] // CHECK: [[X2BOX_BORROW:%.*]] = begin_borrow [[X2BOX]] // SEMANTIC ARC TODO: This next mark_function_escape should be on a projection from X2BOX_BORROW. // CHECK: mark_function_escape [[X2BOX_PB]] var x2 = x func scribble() { x2 = zero } scribble() // CHECK: [[SCRIB:%[0-9]+]] = function_ref @[[SCRIB_NAME:\$s8closures16write_to_capture.*]] : $@convention(thin) (@guaranteed { var Int }) -> () // CHECK: apply [[SCRIB]]([[X2BOX_BORROW]]) // SEMANTIC ARC TODO: This should load from X2BOX_BORROW project. There is an // issue here where after a copy_value, we need to reassign a projection in // some way. // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[X2BOX_PB]] : $*Int // CHECK: [[RET:%[0-9]+]] = load [trivial] [[ACCESS]] // CHECK: destroy_value [[X2BOX]] // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] return x2 } // CHECK: } // end sil function '$s8closures16write_to_captureyS2iF' // CHECK: sil private @[[SCRIB_NAME]] // CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }): // CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]] // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[XADDR]] : $*Int // CHECK: assign {{%[0-9]+}} to [[ACCESS]] // CHECK: return // CHECK: } // end sil function '[[SCRIB_NAME]]' // CHECK-LABEL: sil hidden @$s8closures21multiple_closure_refs{{[_0-9a-zA-Z]*}}F func multiple_closure_refs(_ x: Int) -> (() -> Int, () -> Int) { var x = x func cap() -> Int { return x } return (cap, cap) // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:\$s8closures21multiple_closure_refs.*]] : $@convention(thin) (@guaranteed { var Int }) -> Int // CHECK: [[CAP_CLOSURE_1:%[0-9]+]] = partial_apply [callee_guaranteed] [[CAP]] // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:\$s8closures21multiple_closure_refs.*]] : $@convention(thin) (@guaranteed { var Int }) -> Int // CHECK: [[CAP_CLOSURE_2:%[0-9]+]] = partial_apply [callee_guaranteed] [[CAP]] // CHECK: [[RET:%[0-9]+]] = tuple ([[CAP_CLOSURE_1]] : {{.*}}, [[CAP_CLOSURE_2]] : {{.*}}) // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden @$s8closures18capture_local_funcySiycycSiF : $@convention(thin) (Int) -> @owned @callee_guaranteed () -> @owned @callee_guaranteed () -> Int { func capture_local_func(_ x: Int) -> () -> () -> Int { // CHECK: bb0([[ARG:%.*]] : @trivial $Int): var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: store [[ARG]] to [trivial] [[XBOX_PB]] func aleph() -> Int { return x } func beth() -> () -> Int { return aleph } // CHECK: [[BETH_REF:%.*]] = function_ref @[[BETH_NAME:\$s8closures18capture_local_funcySiycycSiF4bethL_SiycyF]] : $@convention(thin) (@guaranteed { var Int }) -> @owned @callee_guaranteed () -> Int // CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]] // SEMANTIC ARC TODO: This is incorrect. This should be a project_box from XBOX_COPY. // CHECK: mark_function_escape [[XBOX_PB]] // CHECK: [[BETH_CLOSURE:%[0-9]+]] = partial_apply [callee_guaranteed] [[BETH_REF]]([[XBOX_COPY]]) return beth // CHECK: destroy_value [[XBOX]] // CHECK: return [[BETH_CLOSURE]] } // CHECK: } // end sil function '$s8closures18capture_local_funcySiycycSiF' // CHECK: sil private @[[ALEPH_NAME:\$s8closures18capture_local_funcySiycycSiF5alephL_SiyF]] : $@convention(thin) (@guaranteed { var Int }) -> Int { // CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }): // CHECK: sil private @[[BETH_NAME]] : $@convention(thin) (@guaranteed { var Int }) -> @owned @callee_guaranteed () -> Int { // CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }): // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: [[ALEPH_REF:%[0-9]+]] = function_ref @[[ALEPH_NAME]] : $@convention(thin) (@guaranteed { var Int }) -> Int // CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]] // SEMANTIC ARC TODO: This should be on a PB from XBOX_COPY. // CHECK: mark_function_escape [[XBOX_PB]] // CHECK: [[ALEPH_CLOSURE:%[0-9]+]] = partial_apply [callee_guaranteed] [[ALEPH_REF]]([[XBOX_COPY]]) // CHECK: return [[ALEPH_CLOSURE]] // CHECK: } // end sil function '[[BETH_NAME]]' // CHECK-LABEL: sil hidden @$s8closures22anon_read_only_capture{{[_0-9a-zA-Z]*}}F func anon_read_only_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : @trivial $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PB:%.*]] = project_box [[XBOX]] return ({ x })() // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:\$s8closures22anon_read_only_capture[_0-9a-zA-Z]*]] : $@convention(thin) (@inout_aliasable Int) -> Int // -- apply expression // CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]]) // -- cleanup // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] } // CHECK: sil private @[[CLOSURE_NAME]] // CHECK: bb0([[XADDR:%[0-9]+]] : @trivial $*Int): // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int // CHECK: [[X:%[0-9]+]] = load [trivial] [[ACCESS]] // CHECK: return [[X]] // CHECK-LABEL: sil hidden @$s8closures21small_closure_capture{{[_0-9a-zA-Z]*}}F func small_closure_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : @trivial $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PB:%.*]] = project_box [[XBOX]] return { x }() // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:\$s8closures21small_closure_capture[_0-9a-zA-Z]*]] : $@convention(thin) (@inout_aliasable Int) -> Int // -- apply expression // CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]]) // -- cleanup // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] } // CHECK: sil private @[[CLOSURE_NAME]] // CHECK: bb0([[XADDR:%[0-9]+]] : @trivial $*Int): // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int // CHECK: [[X:%[0-9]+]] = load [trivial] [[ACCESS]] // CHECK: return [[X]] // CHECK-LABEL: sil hidden @$s8closures35small_closure_capture_with_argument{{[_0-9a-zA-Z]*}}F func small_closure_capture_with_argument(_ x: Int) -> (_ y: Int) -> Int { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int } return { x + $0 } // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:\$s8closures35small_closure_capture_with_argument.*]] : $@convention(thin) (Int, @guaranteed { var Int }) -> Int // CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]] // CHECK: [[ANON_CLOSURE_APP:%[0-9]+]] = partial_apply [callee_guaranteed] [[ANON]]([[XBOX_COPY]]) // -- return // CHECK: destroy_value [[XBOX]] // CHECK: return [[ANON_CLOSURE_APP]] } // CHECK: sil private @[[CLOSURE_NAME]] : $@convention(thin) (Int, @guaranteed { var Int }) -> Int // CHECK: bb0([[DOLLAR0:%[0-9]+]] : @trivial $Int, [[XBOX:%[0-9]+]] : @guaranteed ${ var Int }): // CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]] // CHECK: [[INTTYPE:%[0-9]+]] = metatype $@thin Int.Type // CHECK: [[XACCESS:%[0-9]+]] = begin_access [read] [unknown] [[XADDR]] : $*Int // CHECK: [[LHS:%[0-9]+]] = load [trivial] [[XACCESS]] // CHECK: end_access [[XACCESS]] : $*Int // CHECK: [[PLUS:%[0-9]+]] = function_ref @$sSi1poiyS2i_SitFZ{{.*}} // CHECK: [[RET:%[0-9]+]] = apply [[PLUS]]([[LHS]], [[DOLLAR0]], [[INTTYPE]]) // CHECK: return [[RET]] // CHECK-LABEL: sil hidden @$s8closures24small_closure_no_capture{{[_0-9a-zA-Z]*}}F func small_closure_no_capture() -> (_ y: Int) -> Int { // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:\$s8closures24small_closure_no_captureS2icyFS2icfU_]] : $@convention(thin) (Int) -> Int // CHECK: [[ANON_THICK:%[0-9]+]] = thin_to_thick_function [[ANON]] : ${{.*}} to $@callee_guaranteed (Int) -> Int // CHECK: return [[ANON_THICK]] return { $0 } } // CHECK: sil private @[[CLOSURE_NAME]] : $@convention(thin) (Int) -> Int // CHECK: bb0([[YARG:%[0-9]+]] : @trivial $Int): // CHECK-LABEL: sil hidden @$s8closures17uncaptured_locals{{[_0-9a-zA-Z]*}}F : func uncaptured_locals(_ x: Int) -> (Int, Int) { var x = x // -- locals without captures are stack-allocated // CHECK: bb0([[XARG:%[0-9]+]] : @trivial $Int): // CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PB:%.*]] = project_box [[XADDR]] // CHECK: store [[XARG]] to [trivial] [[PB]] var y = zero // CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int } return (x, y) } class SomeClass { var x : Int = zero init() { x = { self.x }() // Closing over self. } } // Closures within destructors <rdar://problem/15883734> class SomeGenericClass<T> { deinit { var i: Int = zero // CHECK: [[C1REF:%[0-9]+]] = function_ref @$s8closures16SomeGenericClassCfdSiyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> Int // CHECK: apply [[C1REF]]([[IBOX:%[0-9]+]]) : $@convention(thin) (@inout_aliasable Int) -> Int var x = { i + zero } () // CHECK: [[C2REF:%[0-9]+]] = function_ref @$s8closures16SomeGenericClassCfdSiyXEfU0_ : $@convention(thin) () -> Int // CHECK: apply [[C2REF]]() : $@convention(thin) () -> Int var y = { zero } () // CHECK: [[C3REF:%[0-9]+]] = function_ref @$s8closures16SomeGenericClassCfdyyXEfU1_ : $@convention(thin) <τ_0_0> () -> () // CHECK: apply [[C3REF]]<T>() : $@convention(thin) <τ_0_0> () -> () var z = { _ = T.self } () } // CHECK-LABEL: sil private @$s8closures16SomeGenericClassCfdSiyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> Int // CHECK-LABEL: sil private @$s8closures16SomeGenericClassCfdSiyXEfU0_ : $@convention(thin) () -> Int // CHECK-LABEL: sil private @$s8closures16SomeGenericClassCfdyyXEfU1_ : $@convention(thin) <T> () -> () } // This is basically testing that the constraint system ranking // function conversions as worse than others, and therefore performs // the conversion within closures when possible. class SomeSpecificClass : SomeClass {} func takesSomeClassGenerator(_ fn : () -> SomeClass) {} func generateWithConstant(_ x : SomeSpecificClass) { takesSomeClassGenerator({ x }) } // CHECK-LABEL: sil private @$s8closures20generateWithConstantyyAA17SomeSpecificClassCFAA0eG0CyXEfU_ : $@convention(thin) (@guaranteed SomeSpecificClass) -> @owned SomeClass { // CHECK: bb0([[T0:%.*]] : @guaranteed $SomeSpecificClass): // CHECK: debug_value [[T0]] : $SomeSpecificClass, let, name "x", argno 1 // CHECK: [[T0_COPY:%.*]] = copy_value [[T0]] // CHECK: [[T0_COPY_CASTED:%.*]] = upcast [[T0_COPY]] : $SomeSpecificClass to $SomeClass // CHECK: return [[T0_COPY_CASTED]] // CHECK: } // end sil function '$s8closures20generateWithConstantyyAA17SomeSpecificClassCFAA0eG0CyXEfU_' // Check the annoying case of capturing 'self' in a derived class 'init' // method. We allocate a mutable box to deal with 'self' potentially being // rebound by super.init, but 'self' is formally immutable and so is captured // by value. <rdar://problem/15599464> class Base {} class SelfCapturedInInit : Base { var foo : () -> SelfCapturedInInit // CHECK-LABEL: sil hidden @$s8closures18SelfCapturedInInitC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit { // CHECK: bb0([[SELF:%.*]] : @owned $SelfCapturedInInit): // // First create our initial value for self. // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var SelfCapturedInInit }, let, name "self" // CHECK: [[UNINIT_SELF:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[UNINIT_SELF]] // CHECK: store [[SELF]] to [init] [[PB_SELF_BOX]] // // Then perform the super init sequence. // CHECK: [[TAKEN_SELF:%.*]] = load [take] [[PB_SELF_BOX]] // CHECK: [[UPCAST_TAKEN_SELF:%.*]] = upcast [[TAKEN_SELF]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[UPCAST_TAKEN_SELF]]) : $@convention(method) (@owned Base) -> @owned Base // CHECK: [[DOWNCAST_NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] : $Base to $SelfCapturedInInit // CHECK: store [[DOWNCAST_NEW_SELF]] to [init] [[PB_SELF_BOX]] // // Finally put self in the closure. // CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_SELF_BOX]] // CHECK: [[COPIED_SELF:%.*]] = load [copy] [[PB_SELF_BOX]] // CHECK: [[FOO_VALUE:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[COPIED_SELF]]) : $@convention(thin) (@guaranteed SelfCapturedInInit) -> @owned SelfCapturedInInit // CHECK: [[FOO_LOCATION:%.*]] = ref_element_addr [[BORROWED_SELF]] // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[FOO_LOCATION]] : $*@callee_guaranteed () -> @owned SelfCapturedInInit // CHECK: assign [[FOO_VALUE]] to [[ACCESS]] override init() { super.init() foo = { self } } } func takeClosure(_ fn: () -> Int) -> Int { return fn() } class TestCaptureList { var x = zero func testUnowned() { let aLet = self takeClosure { aLet.x } takeClosure { [unowned aLet] in aLet.x } takeClosure { [weak aLet] in aLet!.x } var aVar = self takeClosure { aVar.x } takeClosure { [unowned aVar] in aVar.x } takeClosure { [weak aVar] in aVar!.x } takeClosure { self.x } takeClosure { [unowned self] in self.x } takeClosure { [weak self] in self!.x } takeClosure { [unowned newVal = TestCaptureList()] in newVal.x } takeClosure { [weak newVal = TestCaptureList()] in newVal!.x } } } class ClassWithIntProperty { final var x = 42 } func closeOverLetLValue() { let a : ClassWithIntProperty a = ClassWithIntProperty() takeClosure { a.x } } // The let property needs to be captured into a temporary stack slot so that it // is loadable even though we capture the value. // CHECK-LABEL: sil private @$s8closures18closeOverLetLValueyyFSiyXEfU_ : $@convention(thin) (@guaranteed ClassWithIntProperty) -> Int { // CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassWithIntProperty): // CHECK: [[TMP_CLASS_ADDR:%.*]] = alloc_stack $ClassWithIntProperty, let, name "a", argno 1 // CHECK: [[COPY_ARG:%.*]] = copy_value [[ARG]] // CHECK: store [[COPY_ARG]] to [init] [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty // CHECK: [[BORROWED_LOADED_CLASS:%.*]] = load_borrow [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty // CHECK: [[INT_IN_CLASS_ADDR:%.*]] = ref_element_addr [[BORROWED_LOADED_CLASS]] : $ClassWithIntProperty, #ClassWithIntProperty.x // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[INT_IN_CLASS_ADDR]] : $*Int // CHECK: [[INT_IN_CLASS:%.*]] = load [trivial] [[ACCESS]] : $*Int // CHECK: end_borrow [[BORROWED_LOADED_CLASS]] // CHECK: destroy_addr [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty // CHECK: dealloc_stack %1 : $*ClassWithIntProperty // CHECK: return [[INT_IN_CLASS]] // CHECK: } // end sil function '$s8closures18closeOverLetLValueyyFSiyXEfU_' // GUARANTEED-LABEL: sil private @$s8closures18closeOverLetLValueyyFSiyXEfU_ : $@convention(thin) (@guaranteed ClassWithIntProperty) -> Int { // GUARANTEED: bb0(%0 : @guaranteed $ClassWithIntProperty): // GUARANTEED: [[TMP:%.*]] = alloc_stack $ClassWithIntProperty // GUARANTEED: [[COPY:%.*]] = copy_value %0 : $ClassWithIntProperty // GUARANTEED: store [[COPY]] to [init] [[TMP]] : $*ClassWithIntProperty // GUARANTEED: [[BORROWED:%.*]] = load_borrow [[TMP]] // GUARANTEED: end_borrow [[BORROWED]] // GUARANTEED: destroy_addr [[TMP]] // GUARANTEED: } // end sil function '$s8closures18closeOverLetLValueyyFSiyXEfU_' // Use an external function so inout deshadowing cannot see its body. @_silgen_name("takesNoEscapeClosure") func takesNoEscapeClosure(fn : () -> Int) struct StructWithMutatingMethod { var x = 42 mutating func mutatingMethod() { // This should not capture the refcount of the self shadow. takesNoEscapeClosure { x = 42; return x } } } // Check that the address of self is passed in, but not the refcount pointer. // CHECK-LABEL: sil hidden @$s8closures24StructWithMutatingMethodV08mutatingE0{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*StructWithMutatingMethod): // CHECK: [[CLOSURE:%[0-9]+]] = function_ref @$s8closures24StructWithMutatingMethodV08mutatingE0{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int // CHECK: partial_apply [callee_guaranteed] [[CLOSURE]](%0) : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int // Check that the closure body only takes the pointer. // CHECK-LABEL: sil private @$s8closures24StructWithMutatingMethodV08mutatingE0{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int { // CHECK: bb0(%0 : @trivial $*StructWithMutatingMethod): class SuperBase { func boom() {} } class SuperSub : SuperBase { override func boom() {} // CHECK-LABEL: sil hidden @$s8closures8SuperSubC1ayyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$s8closures8SuperSubC1a[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> () // CHECK: apply [[INNER]]([[SELF]]) // CHECK: } // end sil function '$s8closures8SuperSubC1ayyF' func a() { // CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub): // CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]]([[ARG]]) // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$s8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' func a1() { self.boom() super.boom() } a1() } // CHECK-LABEL: sil hidden @$s8closures8SuperSubC1byyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$s8closures8SuperSubC1b[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> () // CHECK: = apply [[INNER]]([[SELF]]) // CHECK: } // end sil function '$s8closures8SuperSubC1byyF' func b() { // CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:\$s8closures8SuperSubC1b.*]] : $@convention(thin) (@guaranteed SuperSub) -> () // CHECK: = apply [[INNER]]([[ARG]]) // CHECK: } // end sil function '[[INNER_FUNC_1]]' func b1() { // CHECK: sil private @[[INNER_FUNC_2]] : $@convention(thin) (@guaranteed SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub): // CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]]([[ARG]]) : $@convention(method) (@guaranteed SuperSub) -> () // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @$s8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed SuperBase) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: } // end sil function '[[INNER_FUNC_2]]' func b2() { self.boom() super.boom() } b2() } b1() } // CHECK-LABEL: sil hidden @$s8closures8SuperSubC1cyyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$s8closures8SuperSubC1c[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> () // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[SELF_COPY]]) // CHECK: [[BORROWED_PA:%.*]] = begin_borrow [[PA]] // CHECK: [[PA_COPY:%.*]] = copy_value [[BORROWED_PA]] // CHECK: [[B:%.*]] = begin_borrow [[PA_COPY]] // CHECK: apply [[B]]() // CHECK: end_borrow [[B]] // CHECK: destroy_value [[PA_COPY]] // CHECK: end_borrow [[BORROWED_PA]] // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '$s8closures8SuperSubC1cyyF' func c() { // CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () // CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub): // CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]]([[ARG]]) : $@convention(method) (@guaranteed SuperSub) -> () // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$s8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' let c1 = { () -> Void in self.boom() super.boom() } c1() } // CHECK-LABEL: sil hidden @$s8closures8SuperSubC1dyyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$s8closures8SuperSubC1d[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> () // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[SELF_COPY]]) // CHECK: [[BORROWED_PA:%.*]] = begin_borrow [[PA]] // CHECK: [[PA_COPY:%.*]] = copy_value [[BORROWED_PA]] // CHECK: [[B:%.*]] = begin_borrow [[PA_COPY]] // CHECK: apply [[B]]() // CHECK: end_borrow [[B]] // CHECK: destroy_value [[PA_COPY]] // CHECK: end_borrow [[BORROWED_PA]] // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '$s8closures8SuperSubC1dyyF' func d() { // CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:\$s8closures8SuperSubC1d.*]] : $@convention(thin) (@guaranteed SuperSub) -> () // CHECK: = apply [[INNER]]([[ARG]]) // CHECK: } // end sil function '[[INNER_FUNC_1]]' let d1 = { () -> Void in // CHECK: sil private @[[INNER_FUNC_2]] : $@convention(thin) (@guaranteed SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @$s8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: } // end sil function '[[INNER_FUNC_2]]' func d2() { super.boom() } d2() } d1() } // CHECK-LABEL: sil hidden @$s8closures8SuperSubC1eyyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_NAME1:\$s8closures8SuperSubC1e[_0-9a-zA-Z]*]] : $@convention(thin) // CHECK: = apply [[INNER]]([[SELF]]) // CHECK: } // end sil function '$s8closures8SuperSubC1eyyF' func e() { // CHECK: sil private @[[INNER_FUNC_NAME1]] : $@convention(thin) // CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_NAME2:\$s8closures8SuperSubC1e.*]] : $@convention(thin) // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[ARG_COPY]]) // CHECK: [[BORROWED_PA:%.*]] = begin_borrow [[PA]] // CHECK: [[PA_COPY:%.*]] = copy_value [[BORROWED_PA]] // CHECK: [[B:%.*]] = begin_borrow [[PA_COPY]] // CHECK: apply [[B]]() : $@callee_guaranteed () -> () // CHECK: end_borrow [[B]] // CHECK: destroy_value [[PA_COPY]] // CHECK: end_borrow [[BORROWED_PA]] // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '[[INNER_FUNC_NAME1]]' func e1() { // CHECK: sil private @[[INNER_FUNC_NAME2]] : $@convention(thin) // CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPERCAST:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @$s8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPERCAST]]) // CHECK: destroy_value [[ARG_COPY_SUPERCAST]] // CHECK: return // CHECK: } // end sil function '[[INNER_FUNC_NAME2]]' let e2 = { super.boom() } e2() } e1() } // CHECK-LABEL: sil hidden @$s8closures8SuperSubC1fyyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$s8closures8SuperSubC1fyyFyycfU_]] : $@convention(thin) (@guaranteed SuperSub) -> () // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[SELF_COPY]]) // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '$s8closures8SuperSubC1fyyF' func f() { // CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:\$s8closures8SuperSubC1fyyFyycfU_yyKXKfu_]] : $@convention(thin) (@guaranteed SuperSub) -> @error Error // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[ARG_COPY]]) // CHECK: [[CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[PA]] // CHECK: [[REABSTRACT_PA:%.*]] = partial_apply [callee_guaranteed] {{.*}}([[CVT]]) // CHECK: [[REABSTRACT_CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[REABSTRACT_PA]] // CHECK: [[TRY_APPLY_AUTOCLOSURE:%.*]] = function_ref @$ss2qqoiyxxSg_xyKXKtKlF : $@convention(thin) <τ_0_0> (@in_guaranteed Optional<τ_0_0>, @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error) // CHECK: try_apply [[TRY_APPLY_AUTOCLOSURE]]<()>({{.*}}, {{.*}}, [[REABSTRACT_CVT]]) : $@convention(thin) <τ_0_0> (@in_guaranteed Optional<τ_0_0>, @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]] // CHECK: [[NORMAL_BB]]{{.*}} // CHECK: } // end sil function '[[INNER_FUNC_1]]' let f1 = { // CHECK: sil private [transparent] @[[INNER_FUNC_2]] // CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @$s8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: } // end sil function '[[INNER_FUNC_2]]' nil ?? super.boom() } } // CHECK-LABEL: sil hidden @$s8closures8SuperSubC1gyyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : @guaranteed $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:\$s8closures8SuperSubC1g[_0-9a-zA-Z]*]] : $@convention(thin) (@guaranteed SuperSub) -> () // CHECK: = apply [[INNER]]([[SELF]]) // CHECK: } // end sil function '$s8closures8SuperSubC1gyyF' func g() { // CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@guaranteed SuperSub) -> () // CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:\$s8closures8SuperSubC1g.*]] : $@convention(thin) (@guaranteed SuperSub) -> @error Error // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[INNER]]([[ARG_COPY]]) // CHECK: [[CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed () -> @error Error to $@noescape @callee_guaranteed () -> @error Error // CHECK: [[REABSTRACT_PA:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[CVT]]) : $@convention(thin) (@noescape @callee_guaranteed () -> @error Error) -> (@out (), @error Error) // CHECK: [[REABSTRACT_CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[REABSTRACT_PA]] // CHECK: [[TRY_APPLY_FUNC:%.*]] = function_ref @$ss2qqoiyxxSg_xyKXKtKlF : $@convention(thin) <τ_0_0> (@in_guaranteed Optional<τ_0_0>, @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error) // CHECK: try_apply [[TRY_APPLY_FUNC]]<()>({{.*}}, {{.*}}, [[REABSTRACT_CVT]]) : $@convention(thin) <τ_0_0> (@in_guaranteed Optional<τ_0_0>, @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]] // CHECK: [[NORMAL_BB]]{{.*}} // CHECK: } // end sil function '[[INNER_FUNC_1]]' func g1() { // CHECK: sil private [transparent] @[[INNER_FUNC_2]] : $@convention(thin) (@guaranteed SuperSub) -> @error Error { // CHECK: bb0([[ARG:%.*]] : @guaranteed $SuperSub): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @$s8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: } // end sil function '[[INNER_FUNC_2]]' nil ?? super.boom() } g1() } } // CHECK-LABEL: sil hidden @$s8closures24UnownedSelfNestedCaptureC06nestedE0{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed UnownedSelfNestedCapture) -> () // -- We enter with an assumed strong +1. // CHECK: bb0([[SELF:%.*]] : @guaranteed $UnownedSelfNestedCapture): // CHECK: [[OUTER_SELF_CAPTURE:%.*]] = alloc_box ${ var @sil_unowned UnownedSelfNestedCapture } // CHECK: [[PB:%.*]] = project_box [[OUTER_SELF_CAPTURE]] // -- strong +2 // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[UNOWNED_SELF:%.*]] = ref_to_unowned [[SELF_COPY]] : // -- TODO: A lot of fussy r/r traffic and owned/unowned conversions here. // -- strong +2, unowned +1 // CHECK: [[UNOWNED_SELF_COPY:%.*]] = copy_value [[UNOWNED_SELF]] // CHECK: store [[UNOWNED_SELF_COPY]] to [init] [[PB]] // SEMANTIC ARC TODO: This destroy_value should probably be /after/ the load from PB on the next line. // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[UNOWNED_SELF:%.*]] = load_borrow [[PB]] // -- strong +2, unowned +1 // CHECK: [[SELF:%.*]] = copy_unowned_value [[UNOWNED_SELF]] // CHECK: end_borrow [[UNOWNED_SELF]] // CHECK: [[UNOWNED_SELF2:%.*]] = ref_to_unowned [[SELF]] // -- strong +2, unowned +2 // CHECK: [[UNOWNED_SELF2_COPY:%.*]] = copy_value [[UNOWNED_SELF2]] // -- strong +1, unowned +2 // CHECK: destroy_value [[SELF]] // -- closure takes unowned ownership // CHECK: [[OUTER_CLOSURE:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[UNOWNED_SELF2_COPY]]) // CHECK: [[OUTER_CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[OUTER_CLOSURE]] // -- call consumes closure // -- strong +1, unowned +1 // CHECK: [[INNER_CLOSURE:%.*]] = apply [[OUTER_CONVERT]] // CHECK: [[B:%.*]] = begin_borrow [[INNER_CLOSURE]] // CHECK: [[CONSUMED_RESULT:%.*]] = apply [[B]]() // CHECK: destroy_value [[CONSUMED_RESULT]] // CHECK: destroy_value [[INNER_CLOSURE]] // -- destroy_values unowned self in box // -- strong +1, unowned +0 // CHECK: destroy_value [[OUTER_SELF_CAPTURE]] // -- strong +0, unowned +0 // CHECK: } // end sil function '$s8closures24UnownedSelfNestedCaptureC06nestedE0{{[_0-9a-zA-Z]*}}F' // -- outer closure // -- strong +0, unowned +1 // CHECK: sil private @[[OUTER_CLOSURE_FUN:\$s8closures24UnownedSelfNestedCaptureC06nestedE0yyFACycyXEfU_]] : $@convention(thin) (@guaranteed @sil_unowned UnownedSelfNestedCapture) -> @owned @callee_guaranteed () -> @owned UnownedSelfNestedCapture { // CHECK: bb0([[CAPTURED_SELF:%.*]] : @guaranteed $@sil_unowned UnownedSelfNestedCapture): // -- strong +0, unowned +2 // CHECK: [[CAPTURED_SELF_COPY:%.*]] = copy_value [[CAPTURED_SELF]] : // -- closure takes ownership of unowned ref // CHECK: [[INNER_CLOSURE:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[CAPTURED_SELF_COPY]]) // -- strong +0, unowned +1 (claimed by closure) // CHECK: return [[INNER_CLOSURE]] // CHECK: } // end sil function '[[OUTER_CLOSURE_FUN]]' // -- inner closure // -- strong +0, unowned +1 // CHECK: sil private @[[INNER_CLOSURE_FUN:\$s8closures24UnownedSelfNestedCaptureC06nestedE0yyFACycyXEfU_ACycfU_]] : $@convention(thin) (@guaranteed @sil_unowned UnownedSelfNestedCapture) -> @owned UnownedSelfNestedCapture { // CHECK: bb0([[CAPTURED_SELF:%.*]] : @guaranteed $@sil_unowned UnownedSelfNestedCapture): // -- strong +1, unowned +1 // CHECK: [[SELF:%.*]] = copy_unowned_value [[CAPTURED_SELF:%.*]] : // -- strong +1, unowned +0 (claimed by return) // CHECK: return [[SELF]] // CHECK: } // end sil function '[[INNER_CLOSURE_FUN]]' class UnownedSelfNestedCapture { func nestedCapture() { {[unowned self] in { self } }()() } } // Check that capturing 'self' via a 'super' call also captures the generic // signature if the base class is concrete and the derived class is generic class ConcreteBase { func swim() {} } // CHECK-LABEL: sil private @$s8closures14GenericDerivedC4swimyyFyyXEfU_ : $@convention(thin) <Ocean> (@guaranteed GenericDerived<Ocean>) -> () // CHECK: bb0([[ARG:%.*]] : @guaranteed $GenericDerived<Ocean>): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $GenericDerived<Ocean> to $ConcreteBase // CHECK: [[METHOD:%.*]] = function_ref @$s8closures12ConcreteBaseC4swimyyF // CHECK: apply [[METHOD]]([[ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed ConcreteBase) -> () // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: } // end sil function '$s8closures14GenericDerivedC4swimyyFyyXEfU_' class GenericDerived<Ocean> : ConcreteBase { override func swim() { withFlotationAid { super.swim() } } func withFlotationAid(_ fn: () -> ()) {} } // Don't crash on this func r25993258_helper(_ fn: (inout Int, Int) -> ()) {} func r25993258() { r25993258_helper { _, _ in () } } // rdar://29810997 // // Using a let from a closure in an init was causing the type-checker // to produce invalid AST: 'self.fn' was an l-value, but 'self' was already // loaded to make an r-value. This was ultimately because CSApply was // building the member reference correctly in the context of the closure, // where 'fn' is not settable, but CSGen / CSSimplify was processing it // in the general DC of the constraint system, i.e. the init, where // 'fn' *is* settable. func r29810997_helper(_ fn: (Int) -> Int) -> Int { return fn(0) } struct r29810997 { private let fn: (Int) -> Int private var x: Int init(function: @escaping (Int) -> Int) { fn = function x = r29810997_helper { fn($0) } } } // DI will turn this into a direct capture of the specific stored property. // CHECK-LABEL: sil hidden @$s8closures16r29810997_helperyS3iXEF : $@convention(thin) (@noescape @callee_guaranteed (Int) -> Int) -> Int // rdar://problem/37790062 protocol P_37790062 { associatedtype T var elt: T { get } } func rdar37790062() { struct S<T> { init(_ a: () -> T, _ b: () -> T) {} } class C1 : P_37790062 { typealias T = Int var elt: T { return 42 } } class C2 : P_37790062 { typealias T = (String, Int, Void) var elt: T { return ("question", 42, ()) } } func foo() -> Int { return 42 } func bar() -> Void {} func baz() -> (String, Int) { return ("question", 42) } func bzz<T>(_ a: T) -> T { return a } func faz<T: P_37790062>(_ a: T) -> T.T { return a.elt } // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU_ // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU0_ // CHECK: function_ref @$s8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC _ = S({ foo() }, { bar() }) // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU1_ // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU2_ // CHECK: function_ref @$s8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC _ = S({ baz() }, { bar() }) // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU3_ // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU4_ // CHECK: function_ref @$s8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC _ = S({ bzz(("question", 42)) }, { bar() }) // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU5_ // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU6_ // CHECK: function_ref @$s8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC _ = S({ bzz(String.self) }, { bar() }) // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU7_ // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU8_ // CHECK: function_ref @$s8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC _ = S({ bzz(((), (()))) }, { bar() }) // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU9_ // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU10_ // CHECK: function_ref @$s8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC _ = S({ bzz(C1()) }, { bar() }) // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU11_ // CHECK: function_ref @$s8closures12rdar37790062yyFyyXEfU12_ // CHECK: function_ref @$s8closures12rdar37790062yyF1SL_VyADyxGxyXE_xyXEtcfC _ = S({ faz(C2()) }, { bar() }) }
apache-2.0
9166e342e0033e52870924419809109a
48.975118
296
0.604353
3.368392
false
false
false
false
OverSwift/VisualReader
MangaReader/Classes/Presentation/Scenes/Reader/ReaderCollectionViewController.swift
1
3427
// // ReaderCollectionViewController.swift // MangaReader // // Created by Sergiy Loza on 25.01.17. // Copyright (c) 2017 Serhii Loza. All rights reserved. // import UIKit protocol ReaderCollectionViewProtocol: class { } class ReaderCollectionViewController: UICollectionViewController { // MARK: - Public properties weak var presenter:ReaderPresenterProtocol! private var cellsCount = 0 { didSet { navigationController?.navigationBar.topItem?.prompt = "\(cellsCount)" collectionView?.reloadData() collectionView?.collectionViewLayout.invalidateLayout() } } // MARK: - Private properties // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setToolbarHidden(true, animated: false) self.navigationController?.setToolbarHidden(false, animated: false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.navigationController?.hidesBarsOnSwipe = true self.navigationController?.hidesBarsOnTap = true cellsCount = 60 } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.hidesBarsOnSwipe = false self.navigationController?.hidesBarsOnTap = false self.navigationController?.setToolbarHidden(false, animated: false) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } // MARK: - Navigation // MARK: - Display logic // MARK: - Actions // MARK: - Overrides override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return true } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return cellsCount } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PageCell", for: indexPath) return cell } override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { } override func scrollViewDidScroll(_ scrollView: UIScrollView) { print("Content offset \(scrollView.contentOffset.y)") // guard let collection = collectionView else { // return // } // if collection.contentSize.height - collection.bounds.height < scrollView.contentOffset.y { // OperationQueue.main.addOperation { // self.cellsCount += 10 // } // } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { super.willTransition(to: newCollection, with: coordinator) } // MARK: - Private functions } extension ReaderCollectionViewController: UICollectionViewDelegateFlowLayout { } extension ReaderCollectionViewController: ReaderCollectionViewProtocol { }
bsd-3-clause
19c1bef44c041bf562f1a40704a465d1
27.090164
140
0.730376
5.379906
false
false
false
false
morbrian/udacity-nano-onthemap
OnTheMap/OnTheMapBaseViewController.swift
1
9521
// // OnTheMapBaseViewController.swift // OnTheMap // // Created by Brian Moriarty on 4/29/15. // Copyright (c) 2015 Brian Moriarty. All rights reserved. // import UIKit import FBSDKLoginKit // OnTheMapBaseViewController // Base class for each view of the On The Map TabBar Controller. // Configures top-bar buttons, and provides basic data loading capabilities to child view controllers. class OnTheMapBaseViewController: UIViewController { // default max number of items per fetch let FetchLimit = 100 let PreFetchTrigger = 20 let BatchedFetchLimit = 10 let KeyForAllowedMultipleEntries = "AllowedMultipleEntries" // access point for all data loading and in memory cache var dataManager: StudentDataAccessManager? // decides whether requests should be made for additional data var preFetchEnabled = true // MARK: ViewController Lifecycle override func viewDidLoad() { if let tabBarController = self.tabBarController as? ManagingTabBarController { dataManager = tabBarController.dataManager if let dm = dataManager { dm.userAllowedMultiplEntries = NSUserDefaults.standardUserDefaults().boolForKey(KeyForAllowedMultipleEntries) dm.fetchLimit = FetchLimit if dm.studentLocationCount == 0 { fetchNextPage() { self.performBatchedFetch(self.BatchedFetchLimit) } } if dm.loggedInUser != nil { fetchCurrentUserLocationData() } let refreshButton = produceRefreshButton() let addLocationButton = produceAddLocationButton() addLocationButton.enabled = dm.authenticated navigationItem.rightBarButtonItems = [refreshButton, addLocationButton] navigationItem.leftBarButtonItem = produceLogoutBarButtonItem() } } } override func viewWillAppear(animated: Bool) { navigationController?.navigationBar.hidden = false tabBarController?.tabBar.hidden = false preFetchEnabled = true } func performBatchedFetch(fetchLimit: Int) { if (self.preFetchEnabled && fetchLimit > 0) { // batched data loading requests after the first fetch do not interrupt user viewing self.fetchNextPage(false) { self.performBatchedFetch(fetchLimit - 1) } } } // MARK: UIBarButonItem Producers // return configured Add Location button private func produceAddLocationButton() -> UIBarButtonItem { return UIBarButtonItem(image: UIImage(named: "Pin"), style: UIBarButtonItemStyle.Plain, target: self, action: "addLocationAction:") } // return configured Refresh button private func produceRefreshButton() -> UIBarButtonItem { return UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "refreshAction:") } // return a button with appropriate label for the logout position on the navigation bar private func produceLogoutBarButtonItem() -> UIBarButtonItem? { var logoutBarButtonItem: UIBarButtonItem? = nil if let dm = dataManager { switch dm.authenticationTypeUsed { case .UdacityUsernameAndPassword, .FacebookToken: logoutBarButtonItem = UIBarButtonItem(title: "Logout", style: UIBarButtonItemStyle.Done, target: self, action: "returnToLoginScreen:") case .NotAuthenticated: logoutBarButtonItem = UIBarButtonItem(title: "Login", style: UIBarButtonItemStyle.Done, target: self, action: "returnToLoginScreen:") } } return logoutBarButtonItem } // MARK: Methods for Subclass to Override // perform work that must be done to keep display in sync with model // basically an abstract method that should be implemented by subclasses func updateDisplayFromModel() {} // provide basic status bar activity indicator. // subclasses can call super, then perform any additional work as appropriate. // when true, intrusive suggests it is acceptable for network indicators // such as animations to overlap the user's work until the activity completes. func networkActivity(active: Bool, intrusive: Bool = true) { dispatch_async(dispatch_get_main_queue()) { UIApplication.sharedApplication().networkActivityIndicatorVisible = active } } // MARK: Base Functionality // called when the current user's data is loaded, does nothing by default // sub-classes should override to provide custom actions func currentUserDataNowAvailable() {} // fetch all items created by the currently logged in user // this helps us get items for the current user that may not // be in the top 100 when all users are included. func fetchCurrentUserLocationData() { networkActivity(true) dataManager?.fetchDataForCurrentUser() { success, error in self.networkActivity(false) if success { self.currentUserDataNowAvailable() } } } // Make another fetch request for the next available data // TODO: [limitation] this will not detect DELETE operations made by other users after initial load. func fetchNextPage(intrusive: Bool = true, completionHandler: (() -> Void)? = nil) { let oldCount = self.dataManager?.studentLocationCount ?? 0 networkActivity(true, intrusive: intrusive) dataManager?.fetchNextStudentInformationSubset() { success, error in self.networkActivity(false, intrusive: intrusive) if let completionHandler = completionHandler { completionHandler() } if let newCount = self.dataManager?.studentLocationCount { if newCount - oldCount > 0 { // if we received any new data, update the table self.updateDisplayFromModel() } else if success { // if we received no new data, we are likely at the end of the stream and shouldn't ask again // until the user explicitly asks us to with a refresh. self.preFetchEnabled = false } else if let error = error { ToolKit.showErrorAlert(viewController: self, title: "Failed to Fetch Data", message: error.localizedDescription) } else { // this message should never occur, we think we differentiate all errors with a non-nil error object. // if it does happen, it means we messed up, so hopefully the user will have a good laugh and not hate us. ToolKit.showErrorAlert(viewController: self, title: "Uh Oh, Spaghettios!", message: "An unspecified error occurred, Please take a moment to 'Like' us on Facebook.") } } } } // fetch additional data, includes recent updates or data older than func refreshAction(sender: AnyObject!) { fetchNextPage() } func sendToUrlString(urlString: String) { dataManager?.validateUrlString(urlString) { success, errorMessage in if success { UIApplication.sharedApplication().openURL(NSURL(string: urlString)!) } else if let errorMessage = errorMessage { ToolKit.showErrorAlert(viewController: self, title: "URL Inaccessible", message: errorMessage) } else { ToolKit.showErrorAlert(viewController:self, title: "URL Inaccessible", message: "Unidentified Failure Connecting To \(urlString)") } } } // action when "Add Location" button is tapped // pop up Alert dialog if user needs to confirm overwriting old data. func addLocationAction(sender: AnyObject!) { if let dataManager = dataManager where dataManager.loggedInUserDoesHaveLocation() && !dataManager.userAllowedMultiplEntries { let alert = UIAlertController(title: "Add Study Location", message: "Would you like to overwrite your previously entered location?", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in // nothing to do }) alert.addAction(UIAlertAction(title: "Continue", style: .Default) { action -> Void in self.performSegueWithIdentifier(Constants.GeocodeSegue, sender: self) }) presentViewController(alert, animated: true, completion: nil) } else { performSegueWithIdentifier(Constants.GeocodeSegue, sender: self) } } // segue to GeocodeViewController to ad new location override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let destination = segue.destinationViewController as? GeocodeViewController { destination.dataManager = dataManager } } // log out and pop to root login viewcontroller func returnToLoginScreen(sender: AnyObject) { if dataManager?.authenticationTypeUsed == .FacebookToken { FBSDKLoginManager().logOut() } performSegueWithIdentifier(Constants.ReturnToLoginScreenSegue, sender: self) } }
mit
a4b2edf8a00b11d89a7aceb932831c64
44.555024
190
0.652663
5.516222
false
false
false
false
yasuoza/graphPON
graphPON iOS/ViewControllers/ErrorAlertController.swift
1
2001
import UIKit import GraphPONDataKit class ErrorAlertController: UIAlertController { class func initWithError(error: NSError) -> ErrorAlertController { let (title, message) = self.buildTitleAndMessageFromError(error) let alert = ErrorAlertController( title: title, message: message, preferredStyle: .Alert ) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) return alert } private class func buildTitleAndMessageFromError(error: NSError) -> (String, String) { switch error.domain { case String(OAuth2Router.APIErrorDomain): switch error.code { case Int(OAuth2Router.AuthorizationFailureErrorCode): let title = NSLocalizedString("AuthenticationFailed", comment: "Authentication failed alert title") let message = NSLocalizedString("AuthorizationFailedPleaseLoginIIJmio", comment: "Authorization falied alert message") return (title, message) case Int(OAuth2Router.TooManyRequestErrorCode): let title = NSLocalizedString("TooManyRequest", comment: "Too many request alert title") let message = NSLocalizedString("TooManyRequestPleaseRequestLater", comment: "Too many request alert message") return (title, message) default: let title = NSLocalizedString("UnknownError", comment: "Unknown error alert title") let message = NSLocalizedString("UnknownErrorHappendPleaseRequestLater", comment: "Unkown error alert message") return (title, message) } default: let title = NSLocalizedString("RequestFailed", comment: "Request failed error alert title") let message = NSLocalizedString("PleaseCheckNetworkConnectionAndMakeRequestOnceAgain", comment: "Request failed error alert message") return (title, message) } } }
mit
de8f92b2738a5c9a390d5f71bba1e6b4
47.804878
145
0.662169
5.452316
false
false
false
false
blue42u/swift-t
stc/tests/1672-autowrap-struct.swift
4
1100
// Check returning structs with nested arrays type person { string name; int age; } type megastruct { person people[]; person person; } type uberstruct { person person; megastruct mega; } (megastruct o) fmt(person person, person ppl[]) "turbine" "0" [ "set <<o>> [ dict create person <<person>> people <<ppl>>]" ]; (uberstruct o) fmt2(person person, person ppl[]) "turbine" "0" [ "set <<o>> [ dict create mega [ dict create person <<person>> people <<ppl>> ] person <<person>> ]" ]; import assert; main { person p1, p2; p1.name = "Bob"; p1.age = 100; p2.name = "Jane"; p2.age = 101; person ppl[] = [p1, p2, p1]; assertEqual(fmt(p1, ppl).person.name, "Bob", "a"); assertEqual(fmt(p1, ppl).person.age, 100, "b"); assertEqual(fmt(p1, ppl).people[0].name, "Bob", "c"); assertEqual(fmt(p1, ppl).people[1].name, "Jane", "d"); assertEqual(fmt2(p1, ppl).person.name, "Bob", "e"); assertEqual(fmt2(p1, ppl).person.age, 100, "f"); assertEqual(fmt2(p1, ppl).mega.people[0].name, "Bob", "g"); assertEqual(fmt2(p1, ppl).mega.people[1].name, "Jane", "h"); }
apache-2.0
5e8a7a945f491fd65c4386ee9dfe80ac
22.913043
101
0.618182
2.702703
false
false
false
false
caicai0/ios_demo
Broadcast/BroadcastStarter/BroadcastStarter/ViewController.swift
1
1934
// // ViewController.swift // BroadcastStarter // // Created by 李玉峰 on 2018/4/24. // Copyright © 2018年 cai. All rights reserved. // import UIKit import ReplayKit class ViewController: UIViewController,RPBroadcastActivityViewControllerDelegate { var broadcastActivityController:RPBroadcastActivityViewController? = nil var broadcastController:RPBroadcastController? = nil 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. } @IBAction func start(_ sender: UIButton) { if sender.isSelected { sender.isSelected = false guard (self.broadcastController == nil) else { self.broadcastController?.finishBroadcast(handler: { (error) in print(error) }) return } }else{ RPBroadcastActivityViewController .load { (activity, error) in if error == nil { self.broadcastActivityController = activity activity?.delegate = self as! RPBroadcastActivityViewControllerDelegate self .present(activity!, animated: true, completion: nil) } } } } func broadcastActivityViewController(_ broadcastActivityViewController: RPBroadcastActivityViewController, didFinishWith broadcastController: RPBroadcastController?, error: Error?) { broadcastActivityController?.dismiss(animated: true, completion: nil) print(broadcastController,error) self.broadcastController = broadcastController broadcastController?.startBroadcast(handler: { (error) in print(error) }) } }
mit
291d066edfeb2b0fa207db083478735e
32.77193
186
0.641558
5.437853
false
false
false
false
dnevera/ImageMetalling
ImageMetalling-05/ImageMetalling-05/IMPHistogramRangeSolver.swift
1
1851
// // IMPHistogramRangeSolver.swift // ImageMetalling-05 // // Created by denis svinarchuk on 01.12.15. // Copyright © 2015 IMetalling. All rights reserved. // import UIKit /// /// Солвер вычисляет диапазон интенсивностей для интересных нам условий клиппинга. /// class IMPHistogramRangeSolver: IMPHistogramSolver { struct clippingType { /// /// Клипинг теней (все тени, которые будут перекрыты растяжением), по умолчанию 0.1% /// var shadows:Float = 0.1/100.0 /// /// Клипинг светов, по умолчанию 0.1% /// var highlights:Float = 0.1/100.0 } var clipping = clippingType() /// /// Минимальная интенсивность в пространстве RGB(Y) /// var min = DPVector4(v: (0, 0, 0, 0)) /// /// Максимальная интенсивность в пространстве RGB(Y) /// var max = DPVector4(v: (1, 1, 1, 1)) func analizerDidUpdate(analizer: IMPHistogramAnalyzer, histogram: IMPHistogram, imageSize: CGSize) { min.v = ( histogram.low(channel: 0, clipping: clipping.shadows), histogram.low(channel: 1, clipping: clipping.shadows), histogram.low(channel: 2, clipping: clipping.shadows), histogram.low(channel: 3, clipping: clipping.shadows) ) max.v = ( histogram.high(channel: 0, clipping: clipping.highlights), histogram.high(channel: 1, clipping: clipping.highlights), histogram.high(channel: 2, clipping: clipping.highlights), histogram.high(channel: 3, clipping: clipping.highlights) ) } }
mit
ae0778da2e0732af604493deaa8133b0
29.018519
104
0.61358
3.360996
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Login/PennCashNetworkManager.swift
1
4115
// // PennCashNetworkManager.swift // PennMobile // // Created by Josh Doman on 5/14/19. // Copyright © 2019 PennLabs. All rights reserved. // import Foundation class PennCashNetworkManager { static let instance = PennCashNetworkManager() private init() {} typealias TransactionHandler = (_ csvData: Data?) -> Void } extension PennCashNetworkManager: PennAuthRequestable { private var baseUrl: String { return "https://www.penncash.com" } private var transactionsUrl1: String { return "https://www.penncash.com/statementnew.php?cid=82&acctto=14&fullscreen=1&wason=/statementnew.php" } private var loginUrl: String { return "https://www.penncash.com/login.php" } private var shibbolethUrl: String { return "https://www.penncash.com/Shibboleth.sso/SAML2/POST" } func getTransactionHistory(callback: @escaping TransactionHandler) { getCid { (cid) in guard let cid = cid else { callback(nil) return } self.getSkey(cid: cid) { (skey) in guard let skey = skey else { callback(nil) return } self.validateSkey(skey: skey, startTime: Date(), timeLimit: 10) { (isValidated) in if isValidated { self.getCSV(cid: cid, skey: skey, callback: callback) } else { callback(nil) } } } } } private func getCid(_ callback: @escaping (_ cid: String?) -> Void) { makeAuthRequest(targetUrl: loginUrl, shibbolethUrl: shibbolethUrl, { (data, _, _) in if let data = data, let html = String(bytes: data, encoding: .utf8) { let cidMatches = html.getMatches(for: "cid=(.*?)&") if let cid = cidMatches.first { callback(cid) return } } callback(nil) }) } private func getSkey(cid: String, _ callback: @escaping (_ skey: String?) -> Void) { let url = "\(self.baseUrl)/login.php?cid=\(cid)&fullscreen=1&wason=/statementnew.php" makeAuthRequest(targetUrl: url, shibbolethUrl: shibbolethUrl, { (data, _, _) in if let data = data, let html = String(bytes: data, encoding: .utf8) { let skeyMatches = html.getMatches(for: "skey=(.*?)\";") if let skey = skeyMatches.first { callback(skey) return } } callback(nil) }) } private func validateSkey(skey: String, startTime: Date, timeLimit: TimeInterval, _ callback: @escaping (_ isValidated: Bool) -> Void) { if Date().timeIntervalSince(startTime) > timeLimit { callback(false) return } let url = "\(baseUrl)/login-check.php?skey=\(skey)" makeAuthRequest(targetUrl: url, shibbolethUrl: shibbolethUrl) { (data, _, _) in if let data = data, let html = String(bytes: data, encoding: .utf8) { let isValidated = html.contains("<message>1</message>") if isValidated { callback(true) } else { self.validateSkey(skey: skey, startTime: startTime, timeLimit: timeLimit, callback) } } else { callback(false) } } } private func getCSV(cid: String, skey: String, callback: @escaping TransactionHandler) { let tomorrow = Date().tomorrow let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let dateStr = formatter.string(from: tomorrow) let csvUrl = "https://www.penncash.com/statementdetail.php?cid=\(cid)&skey=\(skey)&format=csv&startdate=2000-01-01&enddate=\(dateStr)&acct=14" makeAuthRequest(targetUrl: csvUrl, shibbolethUrl: shibbolethUrl, { (data, _, _) in callback(data) }) } }
mit
3b2aa5649bf2059d4bf6204973219f03
33.864407
150
0.546913
4.138833
false
false
false
false
iCodeForever/ifanr
ifanr/ifanr/Controllers/Base/BasePageController.swift
1
2706
// // BasePageController.swift // ifanr // // Created by sys on 16/7/4. // Copyright © 2016年 ifanrOrg. All rights reserved. // import UIKit import Alamofire class BasePageController: UIViewController, ScrollViewControllerReusable { //MARK: --------------------------- life cycle -------------------------- override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black setupTableView() setupPullToRefreshView() } override var prefersStatusBarHidden : Bool { return true } //MARK: --------------------------- Getter and Setter -------------------------- var tableView: UITableView! /// 下拉刷新 var pullToRefresh: PullToRefreshView! /// 下拉刷新代理 var scrollViewReusableDataSource: ScrollViewControllerReusableDataSource! var scrollViewReusableDelegate: ScrollViewControllerReusableDelegate! /// 是否正在刷新 var isRefreshing = false /// 记录当前列表页码 var page = 1 /// 上拉加载更多触发零界点 var happenY: CGFloat = UIConstant.SCREEN_HEIGHT+20 var differY: CGFloat = 0 /// scrollView方向 var direction: ScrollViewDirection! = ScrollViewDirection.none var lastContentOffset: CGFloat = 0 } extension BasePageController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { // 计算contentsize与offset的差值 let contentSizeY = scrollView.contentSize.height let contentOffsetY = scrollView.contentOffset.y differY = contentSizeY-contentOffsetY // 判断滚动方向 if contentOffsetY > 0 { ChangeScrollViewDirection(contentOffsetY) } } /** 判断滚动方向 */ fileprivate func ChangeScrollViewDirection(_ contentOffsetY: CGFloat) { // print("contentoffsety:\(contentOffsetY) last: \(lastContentOffset) dir: \(direction)") if contentOffsetY > lastContentOffset { lastContentOffset = contentOffsetY guard direction != .down else { return } scrollViewReusableDelegate.ScrollViewControllerDirectionDidChange(.down) direction = .down } else if lastContentOffset > contentOffsetY { lastContentOffset = contentOffsetY guard direction != .up else { return } scrollViewReusableDelegate.ScrollViewControllerDirectionDidChange(.up) direction = .up } } }
mit
bd6dcfd478854baab8a591af0c904861
26.585106
102
0.595064
5.84009
false
false
false
false
fletcher89/SwiftyRC
Sources/SwiftyRC/Types/Client/Commands/Client+PART.swift
1
1710
// // Client+PART.swift // SwiftyRC // // Created by Christian on 12.08.17. // public extension IRC.Client { // MARK: PART Methods /// Leaves a number of Channels with an optional message. /// /// - Parameters: /// - channel: Channels to leave /// - message: Part Message func part(_ channels: [IRC.Channel], with message: IRC.MessageText? = nil) { let channelArgument = channels.map { $0.makeIRCChannel() }.joined(separator: ",") let rawMessage = [ "PART", channelArgument, message == nil ? nil : ":\(message!)" ].flatMap { $0 }.joined(separator: " ") do { try send(raw: rawMessage) } catch let error { handle(error) } } /// Convenience Method for `part(channels:with:)` /// /// - Parameters: /// - channel: Channel to leave /// - message: Part Message func part(_ channel: IRC.Channel, with message: IRC.MessageText? = nil) { part([channel], with: message) } // MARK: Convenience Methods using leave instead of part /// Convenience Method for `part(channels:with:)` /// /// - Parameters: /// - channel: Channel to leave /// - message: Part Message func leave(channel: IRC.Channel, with message: IRC.MessageText? = nil) { part([channel], with: message) } /// Convenience Method for `part(channels:with:)` /// /// - Parameters: /// - channel: Channels to leave /// - message: Part Message func leave(channels: [IRC.Channel], with message: IRC.MessageText? = nil) { part(channels, with: message) } }
mit
0080306b0766b02c790e9824681bb7bb
27.5
89
0.553216
4.201474
false
false
false
false
gizmosachin/VolumeBar
Sources/VolumeBarStyle+Presets.swift
1
4820
// // VolumeBarStyle+Presets.swift // // Copyright (c) 2016-Present Sachin Patel (http://gizmosachin.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 public extension VolumeBarStyle { // MARK: Presets /// A volume bar style like Instagram, where the bar is a continuous progress view /// that displays to the left of the notch on iPhone X and covers the full width /// of the iOS status bar on all other iOS devices. static let likeInstagram: VolumeBarStyle = UIDevice.current.volumeBar_isiPhoneX ? .leftOfNotch : .fullWidthContinuous /// A volume bar style like Snapchat, where the bar is a segmented progress view /// that displays under the notch and status bar on iPhone X (respecting the device's /// safe area insets) and covers the iOS status bar on all other iOS devices. static let likeSnapchat: VolumeBarStyle = { var style = VolumeBarStyle() style.height = 5 style.respectsSafeAreaInsets = UIDevice.current.volumeBar_isiPhoneX style.edgeInsets = UIEdgeInsets(top: 2, left: 2, bottom: 0, right: 2) style.segmentSpacing = 2 style.segmentCount = 8 style.progressTintColor = #colorLiteral(red: 0.2558486164, green: 0.2558816075, blue: 0.2558295727, alpha: 1) style.trackTintColor = .white style.backgroundColor = .white return style }() /// A volume bar style that displays a continuous progress view and has minimal insets. static let fullWidthContinuous: VolumeBarStyle = { var style = VolumeBarStyle() style.height = 5 style.cornerRadius = 3 style.edgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 10) style.progressTintColor = #colorLiteral(red: 0.2558486164, green: 0.2558816075, blue: 0.2558295727, alpha: 1) style.trackTintColor = #colorLiteral(red: 0.8537222743, green: 0.8538187146, blue: 0.8536666036, alpha: 1) style.backgroundColor = .white return style }() /// A volume bar style that displays to the left of the notch on iPhone X. static let leftOfNotch: VolumeBarStyle = { var style = VolumeBarStyle() style.height = 5 style.cornerRadius = 3 style.edgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 5, right: 300) style.progressTintColor = #colorLiteral(red: 0.2558486164, green: 0.2558816075, blue: 0.2558295727, alpha: 1) style.trackTintColor = #colorLiteral(red: 0.8537222743, green: 0.8538187146, blue: 0.8536666036, alpha: 1) style.backgroundColor = .white return style }() /// A volume bar style that displays to the right of the notch on iPhone X. static let rightOfNotch: VolumeBarStyle = { var style = VolumeBarStyle() style.height = 5 style.cornerRadius = 3 style.edgeInsets = UIEdgeInsets(top: 20, left: 300, bottom: 5, right: 20) style.progressTintColor = #colorLiteral(red: 0.2558486164, green: 0.2558816075, blue: 0.2558295727, alpha: 1) style.trackTintColor = #colorLiteral(red: 0.8537222743, green: 0.8538187146, blue: 0.8536666036, alpha: 1) style.backgroundColor = .white return style }() } /// :nodoc: public extension UIDevice { var volumeBar_isiPhoneX: Bool { #if arch(i386) || arch(x86_64) // We're running on the simulator, so use that to get the simulated model identifier. let identifier = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] #else // From https://github.com/dennisweissmann/DeviceKit/blob/master/Source/Device.generated.swift var systemInfo = utsname() uname(&systemInfo) let mirror = Mirror(reflecting: systemInfo.machine) let identifier = mirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } #endif return identifier == "iPhone10,3" || identifier == "iPhone10,6" } }
mit
a2fcbddd8bf95dafda8acadd19df27cc
42.035714
118
0.735477
3.654284
false
false
false
false
huangboju/Moots
算法学习/LeetCode/LeetCode/BackPack.swift
1
5740
// // BackPack.swift // LeetCode // // Created by xiAo_Ju on 2018/11/1. // Copyright © 2018 伯驹 黄. All rights reserved. // import Foundation /// 单次选择+最大体积 /// Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack? /// Notice /// You can not divide any item into small pieces. /// Example /// If we have 4 items with size [2, 3, 5, 7], the backpack size is 11, we can select [2, 3, 5], so that the max size we can fill this backpack is 10. If the backpack size is 12. we can select [2, 3, 7] so that we can fulfill the backpack. /// You function should return the max size we can fill in the given backpack. /// Challenge /// O(n x m) time and O(m) memory. /// O(n x m) memory is also acceptable if you do not know how to optimize memory. public func backPack1(_ m: Int, a: [Int]) -> Int { var result: [Int] = Array(repeating: 0, count: m + 1) ///1 [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] /// ///3 [0, 1, 1, 3, 4, 4, 4, 4, 4, 4, 4, 4] /// ///3 [0, 1, 1, 3, 4, 4, 6, 7, 7, 7, 7, 7] /// ///6 [0, 1, 1, 3, 4, 4, 6, 7, 7, 9, 10, 10] for v in a { for volume in (1 ... m).reversed() where volume >= v { result[volume] = max(result[volume-v] + v, result[volume]) } print(v, result, "\n") } return result[m] } /// 单次选择+最大价值 ///Given n items with size Ai and value Vi, and a backpack with size m. What's the maximum value can you put into the backpack? ///Notice ///You cannot divide item into small pieces and the total size of items you choose should smaller or equal to m. ///Example ///Given 4 items with size [2, 3, 5, 7] and value [1, 5, 2, 4], and a backpack with size 10. The maximum value is 9. ///Challenge ///O(n x m) memory is acceptable, can you do it in O(m) memory? public func backPackII(_ m: Int, size: [Int], value: [Int]) -> Int { var result: [Int] = Array(repeating: 0, count: m + 1) for (n, value) in zip(size, value) { for v in (1 ... m).reversed() where v >= n { result[v] = max(result[v], result[v - n] + value) } } return result[m] } /// 重复选择+最大价值 ///Given n kind of items with size Ai and value Vi( each item has an infinite number available) and a backpack with size m. What's the maximum value can you put into the backpack? ///Notice ///You cannot divide item into small pieces and the total size of items you choose should smaller or equal to m. ///Example ///Given 4 items with size [2, 3, 5, 7] and value [1, 5, 2, 4], and a backpack with size 10. The maximum value is 15 public func backPackIII(_ m: Int, size: [Int], value: [Int]) -> Int { var result: [Int] = Array(repeating: 0, count: m + 1) for (n, v) in zip(size, value) { for j in 1 ... m where j >= n { result[j] = max(result[j], result[j - n] + v) } } return result[m] } /// 重复选择+唯一排列+装满可能性总数 ///Given n items with size nums[i] which an integer array and all positive numbers, no duplicates. An integer target denotes the size of a backpack. Find the number of possible fill the backpack. ///Each item may be chosen unlimited number of times. ///Example ///Given candidate items [2,3,6,7] and target 7, ///A solution set is: ///[7] ///[2, 2, 3] public func backPackIV(_ m: Int, a: [Int]) -> Int { var result: [Int] = Array(repeating: 0, count: m + 1) result[0] = 1 for n in a { for j in (n ... m) { result[j] += result[j - n] } } return result[m] } /// 单次选择+装满可能性总数 ///Given n items with size nums[i] which an integer array and all positive numbers. An integer target denotes the size of a backpack. Find the number of possible fill the backpack. ///Each item may only be used once. ///Example ///Given candidate items [1,2,3,3,7] and target 7, ///A solution set is: ///[7] ///[1, 3, 3] public func backPackV(_ m: Int, nums: [Int]) -> Int { var result: [Int] = Array(repeating: 0, count: m + 1) result[0] = 1 for n in nums { for j in (1 ... m).reversed() where j >= n { result[j] += result[j - n] print(j, result, n) } print("\n") } return result[m] } /// 重复选择+不同排列+装满可能性总数 ///Given an integer array nums with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. ///Notice ///The different sequences are counted as different combinations. ///Example ///Given nums = [1, 2, 4], target = 4 ///The possible combination ways are: ///[1, 1, 1, 1] ///[1, 1, 2] ///[1, 2, 1] ///[2, 1, 1] ///[2, 2] ///[4] public func backPackVI(_ target: Int, nums: [Int]) -> Int { var result: [Int] = Array(repeating: 0, count: target + 1) result[0] = 1 for i in 1 ... target { for n in nums where i >= n { result[i] += result[i - n] } } return result[target] } // https://labuladong.github.io/algo/3/27/81/ //int knapsack(int W, int N, int[] wt, int[] val) { // // base case 已初始化 // int[][] dp = new int[N + 1][W + 1]; // for (int i = 1; i <= N; i++) { // for (int w = 1; w <= W; w++) { // if (w - wt[i - 1] < 0) { // // 这种情况下只能选择不装入背包 // dp[i][w] = dp[i - 1][w]; // } else { // // 装入或者不装入背包,择优 // dp[i][w] = Math.max( // dp[i - 1][w - wt[i-1]] + val[i-1], // dp[i - 1][w] // ); // } // } // } // // return dp[N][W]; //}
mit
5c316a09a6499a8387290d35dad7d914
30.494318
240
0.566119
2.98814
false
false
false
false
grpc/grpc-swift
Sources/protoc-gen-grpc-swift/options.swift
1
5733
/* * Copyright 2017, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import SwiftProtobufPluginLibrary enum GenerationError: Error { /// Raised when parsing the parameter string and found an unknown key case unknownParameter(name: String) /// Raised when a parameter was giving an invalid value case invalidParameterValue(name: String, value: String) /// Raised to wrap another error but provide a context message. case wrappedError(message: String, error: Error) var localizedDescription: String { switch self { case let .unknownParameter(name): return "Unknown generation parameter '\(name)'" case let .invalidParameterValue(name, value): return "Unknown value for generation parameter '\(name)': '\(value)'" case let .wrappedError(message, error): return "\(message): \(error.localizedDescription)" } } } final class GeneratorOptions { enum Visibility: String { case `internal` = "Internal" case `public` = "Public" var sourceSnippet: String { switch self { case .internal: return "internal" case .public: return "public" } } } private(set) var visibility = Visibility.internal private(set) var generateServer = true private(set) var generateClient = true private(set) var generateTestClient = false private(set) var keepMethodCasing = false private(set) var protoToModuleMappings = ProtoFileToModuleMappings() private(set) var fileNaming = FileNaming.FullPath private(set) var extraModuleImports: [String] = [] private(set) var gRPCModuleName = "GRPC" private(set) var swiftProtobufModuleName = "SwiftProtobuf" init(parameter: String?) throws { for pair in GeneratorOptions.parseParameter(string: parameter) { switch pair.key { case "Visibility": if let value = Visibility(rawValue: pair.value) { self.visibility = value } else { throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value) } case "Server": if let value = Bool(pair.value) { self.generateServer = value } else { throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value) } case "Client": if let value = Bool(pair.value) { self.generateClient = value } else { throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value) } case "TestClient": if let value = Bool(pair.value) { self.generateTestClient = value } else { throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value) } case "KeepMethodCasing": if let value = Bool(pair.value) { self.keepMethodCasing = value } else { throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value) } case "ProtoPathModuleMappings": if !pair.value.isEmpty { do { self.protoToModuleMappings = try ProtoFileToModuleMappings(path: pair.value) } catch let e { throw GenerationError.wrappedError( message: "Parameter 'ProtoPathModuleMappings=\(pair.value)'", error: e ) } } case "FileNaming": if let value = FileNaming(rawValue: pair.value) { self.fileNaming = value } else { throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value) } case "ExtraModuleImports": if !pair.value.isEmpty { self.extraModuleImports.append(pair.value) } else { throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value) } case "GRPCModuleName": if !pair.value.isEmpty { self.gRPCModuleName = pair.value } else { throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value) } case "SwiftProtobufModuleName": if !pair.value.isEmpty { self.swiftProtobufModuleName = pair.value } else { throw GenerationError.invalidParameterValue(name: pair.key, value: pair.value) } default: throw GenerationError.unknownParameter(name: pair.key) } } } static func parseParameter(string: String?) -> [(key: String, value: String)] { guard let string = string, !string.isEmpty else { return [] } let parts = string.components(separatedBy: ",") // Partitions the string into the section before the = and after the = let result = parts.map { string -> (key: String, value: String) in // Finds the equal sign and exits early if none guard let index = string.range(of: "=")?.lowerBound else { return (string, "") } // Creates key/value pair and trims whitespace let key = string[..<index] .trimmingCharacters(in: .whitespacesAndNewlines) let value = string[string.index(after: index)...] .trimmingCharacters(in: .whitespacesAndNewlines) return (key: key, value: value) } return result } }
apache-2.0
fd5f26b10a47286c6f95ec9dba7827d3
31.573864
88
0.648177
4.468433
false
false
false
false
grigaci/RateMyTalkAtMobOS
RateMyTalkAtMobOS/Classes/Helpers/Extensions/NSUserDefaults+Extra.swift
1
840
// // NSUserDefaults+Extra.swift // RateMyTalkAtMobOS // // Created by Bogdan Iusco on 10/12/14. // Copyright (c) 2014 Grigaci. All rights reserved. // import Foundation extension NSUserDefaults { var userUUID: String { get { let uuid = self.objectForKey("userUUID") as? String if uuid == nil { let newUUID = NSUUID().UUIDString self.setObject(newUUID, forKey: "userUUID") self.synchronize() return newUUID } return uuid! } } var iCloudDataDownloaded: Bool { get { let isDownloaded = self.boolForKey("iCloudDataDownloaded") return isDownloaded } set { self.setBool(newValue, forKey: "iCloudDataDownloaded") } } }
bsd-3-clause
6a360e49efab3af14472a13b8be07d0b
23
70
0.544048
4.565217
false
false
false
false
VladislavJevremovic/WebcamViewer
WebcamViewer/Common/Extensions/UIKit/UIImageView+Extensions.swift
1
1282
// // Copyright © 2019 Vladislav Jevremović. All rights reserved. // import UIKit extension UIImageView { internal enum ImageError: Error { case download } func download( from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit, completion: ((Result<UIImage, Error>) -> Void)? = nil ) { contentMode = mode URLSession.shared.dataTask(with: url) { data, response, error in guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let mimeType = response?.mimeType, mimeType.hasPrefix("image"), let data = data, error == nil, let image = UIImage(data: data) else { DispatchQueue.main.async { self.image = nil } completion?(.failure(error ?? ImageError.download)) return } DispatchQueue.main.async { self.image = image } completion?(.success(image)) } .resume() } func download( from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit, completion: ((Result<UIImage, Error>) -> Void)? = nil ) { guard let url = URL(string: link) else { return } download(from: url, contentMode: mode, completion: completion) } }
mit
fc8447efc04b0af745d65f65350b44e1
25.666667
94
0.619531
4.398625
false
false
false
false
arcontrerasa/SwiftParseRestClient
ParseRestClient/ParseGenericResponse.swift
1
2238
// // ParseGenericResponse.swift // Pods // // Created by Armando Contreras on 9/15/15. // // import Foundation class ParseGenericResponse<T: ParseModelProtocol> { var response = [T]() var networkResponseState: NetworkResponseState = .Loading func parseJSON(data: NSData) -> [String: AnyObject]? { do { // Try parsing some valid JSON let json = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions(rawValue: 0)) as? [String: AnyObject] return json } catch let error as NSError { // Catch fires here, with an NSErrro being thrown from the JSONObjectWithData method print("A JSON parsing error occurred, here are the details:\n \(error)") } return nil } func parseJSONArray(data: NSData) -> [[String: AnyObject]]? { do { // Try parsing some valid JSON let json = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions(rawValue: 0)) as? [[String: AnyObject]] return json } catch let error as NSError { // Catch fires here, with an NSErrro being thrown from the JSONObjectWithData method print("A JSON parsing error occurred, here are the details:\n \(error)") } return nil } func getJsonModel(dictionary: [String: AnyObject]) -> T? { let parseModel = T(dictionary: dictionary) return parseModel } func parseDictionary(data: NSData) { if let dictionary = self.parseJSON(data) { let parseArray = dictionary["results"] as! [JSONParameters]? if let parseList = parseArray { for item in parseList { let parsedItem = self.getJsonModel(item) if let result = parsedItem { self.response.append(result) } } } } else { print("Expected a dictionary") } } func getData() -> [T] { return response } }
mit
70ca8614d2a08baa655daec9c44d6abb
27.705128
140
0.545576
5.192575
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/What's New/Data store/AnnouncementsStore.swift
1
5360
import WordPressFlux import WordPressKit /// Genric type that renders announcements upon requesting them by calling `getAnnouncements()` protocol AnnouncementsStore: Observable { var announcements: [WordPressKit.Announcement] { get } var versionHasAnnouncements: Bool { get } func getAnnouncements() } protocol AnnouncementsVersionProvider { var version: String? { get } } extension Bundle: AnnouncementsVersionProvider { var version: String? { shortVersionString() } } /// Announcement store with a local cache of "some sort" class CachedAnnouncementsStore: AnnouncementsStore { private let service: AnnouncementServiceRemote private let versionProvider: AnnouncementsVersionProvider private var cache: AnnouncementsCache let changeDispatcher = Dispatcher<Void>() enum State { case loading case ready([WordPressKit.Announcement]) case error(Error) var isLoading: Bool { switch self { case .loading: return true case .error, .ready: return false } } } private(set) var state: State = .ready([]) { didSet { guard !state.isLoading else { return } emitChange() } } private var cacheState: State = .ready([]) var announcements: [WordPressKit.Announcement] { switch state { case .loading, .error: return [] case .ready(let announcements): return announcements } } var versionHasAnnouncements: Bool { cacheIsValid(for: cache.announcements ?? []) } init(cache: AnnouncementsCache, service: AnnouncementServiceRemote, versionProvider: AnnouncementsVersionProvider = Bundle.main) { self.cache = cache self.service = service self.versionProvider = versionProvider } func getAnnouncements() { guard !state.isLoading else { return } state = .loading if let announcements = cache.announcements, cacheIsValid(for: announcements) { state = .ready(announcements) updateCacheIfNeeded() return } // clear cache if it's invalid cache.announcements = nil service.getAnnouncements(appId: Identifiers.appId, appVersion: Identifiers.appVersion, locale: Locale.current.identifier) { [weak self] result in switch result { case .success(let announcements): DispatchQueue.global().async { self?.cache.announcements = announcements } self?.state = .ready(announcements) case .failure(let error): self?.state = .error(error) DDLogError("Feature announcements error: unable to fetch remote announcements - \(error.localizedDescription)") } } } } private extension CachedAnnouncementsStore { func cacheIsValid(for announcements: [Announcement]) -> Bool { guard let minimumVersion = announcements.first?.minimumAppVersion, // there should not be more than one announcement let maximumVersion = announcements.first?.maximumAppVersion, // per version, but if there is, each of them must match the version let targetVersions = announcements.first?.appVersionTargets, // so we might as well choose the first let version = versionProvider.version, ((minimumVersion...maximumVersion).contains(version) || targetVersions.contains(version)) else { return false } return true } var cacheExpired: Bool { guard let date = cache.date, let elapsedTime = Calendar.current.dateComponents([.hour], from: date, to: Date()).hour else { return true } return elapsedTime >= Self.cacheExpirationTime } // Time, in hours, after which the cache expires static let cacheExpirationTime = 24 // Asynchronously update cache without triggering state changes func updateCacheIfNeeded() { guard cacheExpired, !cacheState.isLoading else { return } cacheState = .loading DispatchQueue.global().async { self.service.getAnnouncements(appId: Identifiers.appId, appVersion: Identifiers.appVersion, locale: Locale.current.identifier) { [weak self] result in switch result { case .success(let announcements): self?.cache.announcements = announcements self?.cacheState = .ready([]) case .failure(let error): DDLogError("Feature announcements error: unable to fetch remote announcements - \(error.localizedDescription)") self?.cacheState = .error(error) } } } } enum Identifiers { // 2 is the identifier of WordPress-iOS in the backend static let appId = "2" static var appVersion: String { Bundle.main.shortVersionString() ?? "" } } }
gpl-2.0
5702a9adf68727d68e489a6122cb9ba4
31.095808
145
0.593657
5.59499
false
false
false
false
abunur/quran-ios
Quran/QuranImageHighlightingView.swift
1
3779
// // QuranImageHighlightingView.swift // Quran // // Created by Mohamed Afifi on 4/24/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import UIKit // This class is expected to be implemented using CoreAnimation with CAShapeLayers. // It's also expected to reuse layers instead of dropping & creating new ones. class QuranImageHighlightingView: UIView { var highlights: [QuranHighlightType: Set<AyahNumber>] = [:] { didSet { updateRectangleBounds() } } var ayahInfoData: [AyahNumber: [AyahInfo]]? { didSet { updateRectangleBounds() } } var imageScale: CGRect.Scale = .zero { didSet { updateRectangleBounds() } } var highlightedPosition: AyahWord.Position? { didSet { updateRectangleBounds() } } var highlightingRectangles: [QuranHighlightType: [CGRect]] = [:] func reset() { highlights = [:] ayahInfoData = nil imageScale = .zero } override func draw(_ rect: CGRect) { super.draw(rect) guard !highlights.isEmpty else { return } let context = UIGraphicsGetCurrentContext() for (highlightType, rectangles) in highlightingRectangles { context?.setFillColor(highlightType.color.cgColor) for rect in rectangles { context?.fill(rect) } } } private func updateRectangleBounds() { highlightingRectangles.removeAll() var filteredHighlightAyats: [QuranHighlightType: Set<AyahNumber>] = [:] for type in QuranHighlightType.sortedTypes { let existingAyahts = filteredHighlightAyats.reduce(Set<AyahNumber>()) { $0.union($1.value) } var ayats = highlights[type] ?? Set<AyahNumber>() ayats.subtract(existingAyahts) filteredHighlightAyats[type] = ayats } for (type, ayat) in filteredHighlightAyats { var rectangles: [CGRect] = [] for ayah in ayat { guard let ayahInfo = ayahInfoData?[ayah] else { continue } for piece in ayahInfo { let rectangle = piece.rect.scaled(by: imageScale) rectangles.append(rectangle) } } highlightingRectangles[type] = rectangles } if let position = highlightedPosition, let infos = ayahInfoData?[position.ayah] { for info in infos where info.position == position.position { highlightingRectangles[.wordByWord] = [info.rect.scaled(by: imageScale)] break } } setNeedsDisplay() } // MARK: - Location of ayah func ayahWordPosition(at location: CGPoint, view: UIView) -> AyahWord.Position? { guard let ayahInfoData = ayahInfoData else { return nil } for (ayahNumber, ayahInfos) in ayahInfoData { for piece in ayahInfos { let rectangle = piece.rect.scaled(by: imageScale) if rectangle.contains(location) { return AyahWord.Position(ayah: ayahNumber, position: piece.position, frame: convert(rectangle, to: view)) } } } return nil } }
gpl-3.0
ec0f19f8af7f46018dd597d87b3553c9
33.354545
125
0.622122
4.619804
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Views/Custom/FlashMessageView.swift
1
10384
// // FlasMessage.swift // Inbbbox // // Created by Blazej Wdowikowski on 11/2/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit final class FlashMessageView: UIView { fileprivate let defaultPadding:CGFloat = 15.0 /// Struct for styling message struct Style { /// background color of message view let backgroundColor: UIColor /// text color of title in message view let textColor: UIColor /// font used for title in messsage view let titleFont: UIFont? /// array of corners that will be rounded, by default is nil let roundedCorners: UIRectCorner? /// vartical and horizontal size for rouded corners let roundSize: CGSize? /// padding for title in message view, by default is 15.0 let padding: CGFloat /// Initializer for sytle with default values for majority of parameters /// /// - parameter background: background color of message view /// - parameter textColor: text color of title in message view /// - parameter titleFont: font used for title in messsage view /// - parameter roundedCorners: array of corners that will be rounded, by default is nil /// - parameter roundSize: vartical and horizontal size for rouded corners /// - parameter padding: padding for title in message view, by default is 15.0 init (backgroundColor: UIColor, textColor: UIColor, titleFont: UIFont? = nil, roundedCorners: UIRectCorner? = nil, roundSize: CGSize? = nil, padding: CGFloat = 15.0){ self.backgroundColor = backgroundColor self.textColor = textColor self.titleFont = titleFont self.roundedCorners = roundedCorners self.roundSize = roundSize self.padding = padding } } /// The displayed title of this message let title: String /// The view controller this message is displayed in weak var viewController: UIViewController? /// View that message will be displayed in. Based on displayInViewController var displayInView: UIView? { return displayInViewController ? viewController?.view : UIApplication.shared.keyWindow } /// Flag for view if you want to display message in view or current keyWindow var displayInViewController: Bool = true /// The duration of the displayed message. var duration: FlashMessageDuration = .automatic /// The position of the message (top or bottom or as overlay) var messagePosition: FlashMessageNotificationPosition /// Is the message currenlty fully displayed? Is set as soon as the message is really fully visible var messageIsFullyDisplayed = false /// Function to customize style globally, initialized to default style. Priority will be This customOptions in init > styleForMessageType static var defaultStyle: Style = { return Style( backgroundColor: UIColor.black, textColor: UIColor.white, titleFont: UIFont.systemFont(ofSize: 16) ) }() /// Method called when user use gesture to dissmis message by himself var fadeOut: (() -> Void)? fileprivate let titleLabel = UILabel() fileprivate let backgroundView = UIView() fileprivate var textSpaceLeft: CGFloat = 0 fileprivate var textSpaceRight: CGFloat = 0 fileprivate var callback: (()-> Void)? fileprivate let padding: CGFloat fileprivate let style: Style! // MARK: Lifecycle /// Inits the notification view. Do not call this from outside this library. /// /// - parameter title: The title of the notification view /// - parameter duration: The duration this notification should be displayed /// - parameter viewController: The view controller this message should be displayed in /// - parameter callback: The block that should be executed, when the user tapped on the message /// - parameter position: The position of the message on the screen /// - parameter dismissingEnabled: Should this message be dismissed when the user taps/swipes it? /// - parameter style: Override default/global style init(viewController: UIViewController?, title: String, duration: FlashMessageDuration?, position: FlashMessageNotificationPosition, style customStyle: Style?, dismissingEnabled: Bool, displayInViewController: Bool, callback: (()-> Void)?) { self.style = customStyle ?? FlashMessageView.defaultStyle self.title = title self.duration = duration ?? .automatic self.viewController = viewController self.messagePosition = position self.callback = callback self.displayInViewController = displayInViewController self.padding = messagePosition == .navigationBarOverlay ? style.padding + 10 : style.padding super.init(frame: CGRect.zero) setupBackground() setupTitle() setupPosition() setupGestureForDismiss(ifNeeded: dismissingEnabled) } @available(*, unavailable, message: "Use init(viewController:title:duration:position:style:dismissingEnabled:callback:) instead") required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) guard let roundedCorners = style.roundedCorners, let roundSize = style.roundSize else { return } let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: roundedCorners, cornerRadii: roundSize) let mask = CAShapeLayer() mask.frame = bounds mask.path = path.cgPath layer.mask = mask } override func layoutSubviews() { super.layoutSubviews() _ = updateHeightOfMessageView() } override func didMoveToWindow() { super.didMoveToWindow() if duration == .endless && superview != nil && window == nil { // view controller was dismissed, let's fade out fadeMeOut() } } // MARK: Setups fileprivate func setupBackground() { backgroundColor = UIColor.clear backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight] backgroundView.backgroundColor = style.backgroundColor addSubview(backgroundView) } fileprivate func setupTitle() { let fontColor = style.textColor textSpaceLeft = padding titleLabel.text = title titleLabel.textColor = fontColor titleLabel.backgroundColor = UIColor.clear titleLabel.font = style.titleFont ?? UIFont.boldSystemFont(ofSize: 14) titleLabel.numberOfLines = 0 titleLabel.lineBreakMode = .byWordWrapping addSubview(titleLabel) } fileprivate func setupPosition() { let screenWidth = displayInView?.bounds.size.width ?? 0 let actualHeight = updateHeightOfMessageView() var topPosition = -actualHeight if messagePosition == .bottom { topPosition = displayInView?.bounds.size.height ?? 0 } frame = CGRect(x: 0.0, y: topPosition, width: screenWidth, height: actualHeight) autoresizingMask = [.flexibleWidth, .flexibleTopMargin, .flexibleBottomMargin] } fileprivate func setupGestureForDismiss(ifNeeded dismissingEnabled: Bool) { guard dismissingEnabled else { return } let gestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(fadeMeOut)) gestureRecognizer.direction = (messagePosition == .top ? .up : .down) addGestureRecognizer(gestureRecognizer) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(fadeMeOut)) addGestureRecognizer(tapGestureRecognizer) } // MARK: Private methods fileprivate func updateHeightOfMessageView() -> CGFloat { let screenWidth = displayInView?.bounds.size.width ?? 0 titleLabel.frame = CGRect(x: textSpaceLeft, y: padding, width: screenWidth - padding - textSpaceLeft - textSpaceRight, height: 0.0) titleLabel.sizeToFit() var currentHeight = titleLabel.frame.origin.y + titleLabel.frame.size.height currentHeight += padding frame = CGRect(x: 0.0, y: frame.origin.y, width: frame.size.width, height: currentHeight) var backgroundFrame = CGRect(x: 0, y: 0, width: screenWidth, height: currentHeight) // increase frame of background view because of the spring animation if messagePosition == .top { var topOffset: CGFloat = 0.0 let navigationController: UINavigationController? = viewController as? UINavigationController ?? viewController?.navigationController if let navigationController = navigationController { let isNavigationBarHidden = navigationController.isNavigationBarHidden || navigationController.navigationBar.isHidden let isNavigationBarOpaque = !navigationController.navigationBar.isTranslucent && navigationController.navigationBar.alpha == 1 if isNavigationBarHidden || isNavigationBarOpaque { topOffset = -30.0 } } backgroundFrame = UIEdgeInsetsInsetRect(backgroundFrame, UIEdgeInsetsMake(topOffset, 0.0, 0.0, 0.0)) } else if messagePosition == .bottom { backgroundFrame = UIEdgeInsetsInsetRect(backgroundFrame, UIEdgeInsetsMake(0.0, 0.0, -30.0, 0.0)) } backgroundView.frame = backgroundFrame return currentHeight } @objc fileprivate func fadeMeOut() { fadeOut?() } } // MARK: UIGestureRecognizerDelegate extension FlashMessageView: UIGestureRecognizerDelegate { func handleTap(_ tapGesture: UITapGestureRecognizer) { if tapGesture.state == .recognized { callback?() } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return touch.view is UIControl } }
gpl-3.0
fd118efde858efe17da7dc9adad8fb76
39.877953
244
0.657036
5.519936
false
false
false
false
cburrows/swift-protobuf
Sources/SwiftProtobuf/BinaryDecoder.swift
1
55465
// Sources/SwiftProtobuf/BinaryDecoder.swift - Binary decoding // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Protobuf binary format decoding engine. /// /// This provides the Decoder interface that interacts directly /// with the generated code. /// // ----------------------------------------------------------------------------- import Foundation internal struct BinaryDecoder: Decoder { // Current position private var p : UnsafeRawPointer // Remaining bytes in input. private var available : Int // Position of start of field currently being parsed private var fieldStartP : UnsafeRawPointer // Position of end of field currently being parsed, nil if we don't know. private var fieldEndP : UnsafeRawPointer? // Whether or not the field value has actually been parsed private var consumed = true // Wire format for last-examined field internal var fieldWireFormat = WireFormat.varint // Field number for last-parsed field tag private var fieldNumber: Int = 0 // Collection of extension fields for this decode private var extensions: ExtensionMap? // The current group number. See decodeFullGroup(group:fieldNumber:) for how // this is used. private var groupFieldNumber: Int? // The options for decoding. private var options: BinaryDecodingOptions private var recursionBudget: Int // Collects the unknown data found while decoding a message. private var unknownData: Data? // Custom data to use as the unknown data while parsing a field. Used only by // packed repeated enums; see below private var unknownOverride: Data? private var complete: Bool {return available == 0} internal init( forReadingFrom pointer: UnsafeRawPointer, count: Int, options: BinaryDecodingOptions, extensions: ExtensionMap? = nil ) { // Assuming baseAddress is not nil. p = pointer available = count fieldStartP = p self.extensions = extensions self.options = options recursionBudget = options.messageDepthLimit } internal init( forReadingFrom pointer: UnsafeRawPointer, count: Int, parent: BinaryDecoder ) { self.init(forReadingFrom: pointer, count: count, options: parent.options, extensions: parent.extensions) recursionBudget = parent.recursionBudget } private mutating func incrementRecursionDepth() throws { recursionBudget -= 1 if recursionBudget < 0 { throw BinaryDecodingError.messageDepthLimit } } private mutating func decrementRecursionDepth() { recursionBudget += 1 // This should never happen, if it does, something is probably corrupting memory, and // simply throwing doesn't make much sense. if recursionBudget > options.messageDepthLimit { fatalError("Somehow BinaryDecoding unwound more objects than it started") } } internal mutating func handleConflictingOneOf() throws { /// Protobuf simply allows conflicting oneof values to overwrite } /// Return the next field number or nil if there are no more fields. internal mutating func nextFieldNumber() throws -> Int? { // Since this is called for every field, I've taken some pains // to optimize it, including unrolling a tweaked version of // the varint parser. if fieldNumber > 0 { if let override = unknownOverride { assert(!options.discardUnknownFields) assert(fieldWireFormat != .startGroup && fieldWireFormat != .endGroup) if unknownData == nil { unknownData = override } else { unknownData!.append(override) } unknownOverride = nil } else if !consumed { if options.discardUnknownFields { try skip() } else { let u = try getRawField() if unknownData == nil { unknownData = u } else { unknownData!.append(u) } } } } // Quit if end of input if available == 0 { return nil } // Get the next field number fieldStartP = p fieldEndP = nil let start = p let c0 = start[0] if let wireFormat = WireFormat(rawValue: c0 & 7) { fieldWireFormat = wireFormat } else { throw BinaryDecodingError.malformedProtobuf } if (c0 & 0x80) == 0 { p += 1 available -= 1 fieldNumber = Int(c0) >> 3 } else { fieldNumber = Int(c0 & 0x7f) >> 3 if available < 2 { throw BinaryDecodingError.malformedProtobuf } let c1 = start[1] if (c1 & 0x80) == 0 { p += 2 available -= 2 fieldNumber |= Int(c1) << 4 } else { fieldNumber |= Int(c1 & 0x7f) << 4 if available < 3 { throw BinaryDecodingError.malformedProtobuf } let c2 = start[2] fieldNumber |= Int(c2 & 0x7f) << 11 if (c2 & 0x80) == 0 { p += 3 available -= 3 } else { if available < 4 { throw BinaryDecodingError.malformedProtobuf } let c3 = start[3] fieldNumber |= Int(c3 & 0x7f) << 18 if (c3 & 0x80) == 0 { p += 4 available -= 4 } else { if available < 5 { throw BinaryDecodingError.malformedProtobuf } let c4 = start[4] if c4 > 15 { throw BinaryDecodingError.malformedProtobuf } fieldNumber |= Int(c4 & 0x7f) << 25 p += 5 available -= 5 } } } } if fieldNumber != 0 { consumed = false if fieldWireFormat == .endGroup { if groupFieldNumber == fieldNumber { // Reached the end of the current group, single the // end of the message. return nil } else { // .endGroup when not in a group or for a different // group is an invalid binary. throw BinaryDecodingError.malformedProtobuf } } return fieldNumber } throw BinaryDecodingError.malformedProtobuf } internal mutating func decodeSingularFloatField(value: inout Float) throws { guard fieldWireFormat == WireFormat.fixed32 else { return } try decodeFourByteNumber(value: &value) consumed = true } internal mutating func decodeSingularFloatField(value: inout Float?) throws { guard fieldWireFormat == WireFormat.fixed32 else { return } value = try decodeFloat() consumed = true } internal mutating func decodeRepeatedFloatField(value: inout [Float]) throws { switch fieldWireFormat { case WireFormat.fixed32: let i = try decodeFloat() value.append(i) consumed = true case WireFormat.lengthDelimited: let bodyBytes = try decodeVarint() if bodyBytes > 0 { let itemSize = UInt64(MemoryLayout<Float>.size) let itemCount = bodyBytes / itemSize if bodyBytes % itemSize != 0 || bodyBytes > available { throw BinaryDecodingError.truncated } value.reserveCapacity(value.count + Int(truncatingIfNeeded: itemCount)) for _ in 1...itemCount { value.append(try decodeFloat()) } } consumed = true default: return } } internal mutating func decodeSingularDoubleField(value: inout Double) throws { guard fieldWireFormat == WireFormat.fixed64 else { return } value = try decodeDouble() consumed = true } internal mutating func decodeSingularDoubleField(value: inout Double?) throws { guard fieldWireFormat == WireFormat.fixed64 else { return } value = try decodeDouble() consumed = true } internal mutating func decodeRepeatedDoubleField(value: inout [Double]) throws { switch fieldWireFormat { case WireFormat.fixed64: let i = try decodeDouble() value.append(i) consumed = true case WireFormat.lengthDelimited: let bodyBytes = try decodeVarint() if bodyBytes > 0 { let itemSize = UInt64(MemoryLayout<Double>.size) let itemCount = bodyBytes / itemSize if bodyBytes % itemSize != 0 || bodyBytes > available { throw BinaryDecodingError.truncated } value.reserveCapacity(value.count + Int(truncatingIfNeeded: itemCount)) for _ in 1...itemCount { let i = try decodeDouble() value.append(i) } } consumed = true default: return } } internal mutating func decodeSingularInt32Field(value: inout Int32) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = Int32(truncatingIfNeeded: varint) consumed = true } internal mutating func decodeSingularInt32Field(value: inout Int32?) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = Int32(truncatingIfNeeded: varint) consumed = true } internal mutating func decodeRepeatedInt32Field(value: inout [Int32]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() value.append(Int32(truncatingIfNeeded: varint)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let varint = try decoder.decodeVarint() value.append(Int32(truncatingIfNeeded: varint)) } consumed = true default: return } } internal mutating func decodeSingularInt64Field(value: inout Int64) throws { guard fieldWireFormat == WireFormat.varint else { return } let v = try decodeVarint() value = Int64(bitPattern: v) consumed = true } internal mutating func decodeSingularInt64Field(value: inout Int64?) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = Int64(bitPattern: varint) consumed = true } internal mutating func decodeRepeatedInt64Field(value: inout [Int64]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() value.append(Int64(bitPattern: varint)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let varint = try decoder.decodeVarint() value.append(Int64(bitPattern: varint)) } consumed = true default: return } } internal mutating func decodeSingularUInt32Field(value: inout UInt32) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = UInt32(truncatingIfNeeded: varint) consumed = true } internal mutating func decodeSingularUInt32Field(value: inout UInt32?) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = UInt32(truncatingIfNeeded: varint) consumed = true } internal mutating func decodeRepeatedUInt32Field(value: inout [UInt32]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() value.append(UInt32(truncatingIfNeeded: varint)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let t = try decoder.decodeVarint() value.append(UInt32(truncatingIfNeeded: t)) } consumed = true default: return } } internal mutating func decodeSingularUInt64Field(value: inout UInt64) throws { guard fieldWireFormat == WireFormat.varint else { return } value = try decodeVarint() consumed = true } internal mutating func decodeSingularUInt64Field(value: inout UInt64?) throws { guard fieldWireFormat == WireFormat.varint else { return } value = try decodeVarint() consumed = true } internal mutating func decodeRepeatedUInt64Field(value: inout [UInt64]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() value.append(varint) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let t = try decoder.decodeVarint() value.append(t) } consumed = true default: return } } internal mutating func decodeSingularSInt32Field(value: inout Int32) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() let t = UInt32(truncatingIfNeeded: varint) value = ZigZag.decoded(t) consumed = true } internal mutating func decodeSingularSInt32Field(value: inout Int32?) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() let t = UInt32(truncatingIfNeeded: varint) value = ZigZag.decoded(t) consumed = true } internal mutating func decodeRepeatedSInt32Field(value: inout [Int32]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() let t = UInt32(truncatingIfNeeded: varint) value.append(ZigZag.decoded(t)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let varint = try decoder.decodeVarint() let t = UInt32(truncatingIfNeeded: varint) value.append(ZigZag.decoded(t)) } consumed = true default: return } } internal mutating func decodeSingularSInt64Field(value: inout Int64) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = ZigZag.decoded(varint) consumed = true } internal mutating func decodeSingularSInt64Field(value: inout Int64?) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = ZigZag.decoded(varint) consumed = true } internal mutating func decodeRepeatedSInt64Field(value: inout [Int64]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() value.append(ZigZag.decoded(varint)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let varint = try decoder.decodeVarint() value.append(ZigZag.decoded(varint)) } consumed = true default: return } } internal mutating func decodeSingularFixed32Field(value: inout UInt32) throws { guard fieldWireFormat == WireFormat.fixed32 else { return } var i: UInt32 = 0 try decodeFourByteNumber(value: &i) value = UInt32(littleEndian: i) consumed = true } internal mutating func decodeSingularFixed32Field(value: inout UInt32?) throws { guard fieldWireFormat == WireFormat.fixed32 else { return } var i: UInt32 = 0 try decodeFourByteNumber(value: &i) value = UInt32(littleEndian: i) consumed = true } internal mutating func decodeRepeatedFixed32Field(value: inout [UInt32]) throws { switch fieldWireFormat { case WireFormat.fixed32: var i: UInt32 = 0 try decodeFourByteNumber(value: &i) value.append(UInt32(littleEndian: i)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value.reserveCapacity(value.count + n / MemoryLayout<UInt32>.size) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) var i: UInt32 = 0 while !decoder.complete { try decoder.decodeFourByteNumber(value: &i) value.append(UInt32(littleEndian: i)) } consumed = true default: return } } internal mutating func decodeSingularFixed64Field(value: inout UInt64) throws { guard fieldWireFormat == WireFormat.fixed64 else { return } var i: UInt64 = 0 try decodeEightByteNumber(value: &i) value = UInt64(littleEndian: i) consumed = true } internal mutating func decodeSingularFixed64Field(value: inout UInt64?) throws { guard fieldWireFormat == WireFormat.fixed64 else { return } var i: UInt64 = 0 try decodeEightByteNumber(value: &i) value = UInt64(littleEndian: i) consumed = true } internal mutating func decodeRepeatedFixed64Field(value: inout [UInt64]) throws { switch fieldWireFormat { case WireFormat.fixed64: var i: UInt64 = 0 try decodeEightByteNumber(value: &i) value.append(UInt64(littleEndian: i)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value.reserveCapacity(value.count + n / MemoryLayout<UInt64>.size) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) var i: UInt64 = 0 while !decoder.complete { try decoder.decodeEightByteNumber(value: &i) value.append(UInt64(littleEndian: i)) } consumed = true default: return } } internal mutating func decodeSingularSFixed32Field(value: inout Int32) throws { guard fieldWireFormat == WireFormat.fixed32 else { return } var i: Int32 = 0 try decodeFourByteNumber(value: &i) value = Int32(littleEndian: i) consumed = true } internal mutating func decodeSingularSFixed32Field(value: inout Int32?) throws { guard fieldWireFormat == WireFormat.fixed32 else { return } var i: Int32 = 0 try decodeFourByteNumber(value: &i) value = Int32(littleEndian: i) consumed = true } internal mutating func decodeRepeatedSFixed32Field(value: inout [Int32]) throws { switch fieldWireFormat { case WireFormat.fixed32: var i: Int32 = 0 try decodeFourByteNumber(value: &i) value.append(Int32(littleEndian: i)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value.reserveCapacity(value.count + n / MemoryLayout<Int32>.size) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) var i: Int32 = 0 while !decoder.complete { try decoder.decodeFourByteNumber(value: &i) value.append(Int32(littleEndian: i)) } consumed = true default: return } } internal mutating func decodeSingularSFixed64Field(value: inout Int64) throws { guard fieldWireFormat == WireFormat.fixed64 else { return } var i: Int64 = 0 try decodeEightByteNumber(value: &i) value = Int64(littleEndian: i) consumed = true } internal mutating func decodeSingularSFixed64Field(value: inout Int64?) throws { guard fieldWireFormat == WireFormat.fixed64 else { return } var i: Int64 = 0 try decodeEightByteNumber(value: &i) value = Int64(littleEndian: i) consumed = true } internal mutating func decodeRepeatedSFixed64Field(value: inout [Int64]) throws { switch fieldWireFormat { case WireFormat.fixed64: var i: Int64 = 0 try decodeEightByteNumber(value: &i) value.append(Int64(littleEndian: i)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value.reserveCapacity(value.count + n / MemoryLayout<Int64>.size) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) var i: Int64 = 0 while !decoder.complete { try decoder.decodeEightByteNumber(value: &i) value.append(Int64(littleEndian: i)) } consumed = true default: return } } internal mutating func decodeSingularBoolField(value: inout Bool) throws { guard fieldWireFormat == WireFormat.varint else { return } value = try decodeVarint() != 0 consumed = true } internal mutating func decodeSingularBoolField(value: inout Bool?) throws { guard fieldWireFormat == WireFormat.varint else { return } value = try decodeVarint() != 0 consumed = true } internal mutating func decodeRepeatedBoolField(value: inout [Bool]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() value.append(varint != 0) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let t = try decoder.decodeVarint() value.append(t != 0) } consumed = true default: return } } internal mutating func decodeSingularStringField(value: inout String) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var n: Int = 0 let p = try getFieldBodyBytes(count: &n) if let s = utf8ToString(bytes: p, count: n) { value = s consumed = true } else { throw BinaryDecodingError.invalidUTF8 } } internal mutating func decodeSingularStringField(value: inout String?) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var n: Int = 0 let p = try getFieldBodyBytes(count: &n) if let s = utf8ToString(bytes: p, count: n) { value = s consumed = true } else { throw BinaryDecodingError.invalidUTF8 } } internal mutating func decodeRepeatedStringField(value: inout [String]) throws { switch fieldWireFormat { case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) if let s = utf8ToString(bytes: p, count: n) { value.append(s) consumed = true } else { throw BinaryDecodingError.invalidUTF8 } default: return } } internal mutating func decodeSingularBytesField(value: inout Data) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value = Data(bytes: p, count: n) consumed = true } internal mutating func decodeSingularBytesField(value: inout Data?) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value = Data(bytes: p, count: n) consumed = true } internal mutating func decodeRepeatedBytesField(value: inout [Data]) throws { switch fieldWireFormat { case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value.append(Data(bytes: p, count: n)) consumed = true default: return } } internal mutating func decodeSingularEnumField<E: Enum>(value: inout E?) throws where E.RawValue == Int { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() if let v = E(rawValue: Int(Int32(truncatingIfNeeded: varint))) { value = v consumed = true } } internal mutating func decodeSingularEnumField<E: Enum>(value: inout E) throws where E.RawValue == Int { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() if let v = E(rawValue: Int(Int32(truncatingIfNeeded: varint))) { value = v consumed = true } } internal mutating func decodeRepeatedEnumField<E: Enum>(value: inout [E]) throws where E.RawValue == Int { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() if let v = E(rawValue: Int(Int32(truncatingIfNeeded: varint))) { value.append(v) consumed = true } case WireFormat.lengthDelimited: var n: Int = 0 var extras: [Int32]? let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var subdecoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !subdecoder.complete { let u64 = try subdecoder.decodeVarint() let i32 = Int32(truncatingIfNeeded: u64) if let v = E(rawValue: Int(i32)) { value.append(v) } else if !options.discardUnknownFields { if extras == nil { extras = [] } extras!.append(i32) } } if let extras = extras { let fieldTag = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited) let bodySize = extras.reduce(0) { $0 + Varint.encodedSize(of: Int64($1)) } let fieldSize = Varint.encodedSize(of: fieldTag.rawValue) + Varint.encodedSize(of: Int64(bodySize)) + bodySize var field = Data(count: fieldSize) field.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in if let baseAddress = body.baseAddress, body.count > 0 { var encoder = BinaryEncoder(forWritingInto: baseAddress) encoder.startField(tag: fieldTag) encoder.putVarInt(value: Int64(bodySize)) for v in extras { encoder.putVarInt(value: Int64(v)) } } } unknownOverride = field } consumed = true default: return } } internal mutating func decodeSingularMessageField<M: Message>(value: inout M?) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var count: Int = 0 let p = try getFieldBodyBytes(count: &count) if value == nil { value = M() } var subDecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self) try subDecoder.decodeFullMessage(message: &value!) consumed = true } internal mutating func decodeRepeatedMessageField<M: Message>(value: inout [M]) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var count: Int = 0 let p = try getFieldBodyBytes(count: &count) var newValue = M() var subDecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self) try subDecoder.decodeFullMessage(message: &newValue) value.append(newValue) consumed = true } internal mutating func decodeFullMessage<M: Message>(message: inout M) throws { assert(unknownData == nil) try incrementRecursionDepth() try message.decodeMessage(decoder: &self) decrementRecursionDepth() guard complete else { throw BinaryDecodingError.trailingGarbage } if let unknownData = unknownData { message.unknownFields.append(protobufData: unknownData) } } internal mutating func decodeSingularGroupField<G: Message>(value: inout G?) throws { var group = value ?? G() if try decodeFullGroup(group: &group, fieldNumber: fieldNumber) { value = group consumed = true } } internal mutating func decodeRepeatedGroupField<G: Message>(value: inout [G]) throws { var group = G() if try decodeFullGroup(group: &group, fieldNumber: fieldNumber) { value.append(group) consumed = true } } private mutating func decodeFullGroup<G: Message>(group: inout G, fieldNumber: Int) throws -> Bool { guard fieldWireFormat == WireFormat.startGroup else { return false } try incrementRecursionDepth() // This works by making a clone of the current decoder state and // setting `groupFieldNumber` to signal `nextFieldNumber()` to watch // for that as a marker for having reached the end of a group/message. // Groups within groups works because this effectively makes a stack // of decoders, each one looking for their ending tag. var subDecoder = self subDecoder.groupFieldNumber = fieldNumber // startGroup was read, so current tag/data is done (otherwise the // startTag will end up in the unknowns of the first thing decoded). subDecoder.consumed = true // The group (message) doesn't get any existing unknown fields from // the parent. subDecoder.unknownData = nil try group.decodeMessage(decoder: &subDecoder) guard subDecoder.fieldNumber == fieldNumber && subDecoder.fieldWireFormat == .endGroup else { throw BinaryDecodingError.truncated } if let groupUnknowns = subDecoder.unknownData { group.unknownFields.append(protobufData: groupUnknowns) } // Advance over what was parsed. consume(length: available - subDecoder.available) assert(recursionBudget == subDecoder.recursionBudget) decrementRecursionDepth() return true } internal mutating func decodeMapField<KeyType, ValueType: MapValueType>(fieldType: _ProtobufMap<KeyType, ValueType>.Type, value: inout _ProtobufMap<KeyType, ValueType>.BaseType) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var k: KeyType.BaseType? var v: ValueType.BaseType? var count: Int = 0 let p = try getFieldBodyBytes(count: &count) var subdecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self) while let tag = try subdecoder.getTag() { if tag.wireFormat == .endGroup { throw BinaryDecodingError.malformedProtobuf } let fieldNumber = tag.fieldNumber switch fieldNumber { case 1: try KeyType.decodeSingular(value: &k, from: &subdecoder) case 2: try ValueType.decodeSingular(value: &v, from: &subdecoder) default: // Skip any other fields within the map entry object try subdecoder.skip() } } if !subdecoder.complete { throw BinaryDecodingError.trailingGarbage } // A map<> definition can't provide a default value for the keys/values, // so it is safe to use the proto3 default to get the right // integer/string/bytes. The one catch is a proto2 enum (which can be the // value) can have a non zero value, but that case is the next // custom decodeMapField<>() method and handles it. value[k ?? KeyType.proto3DefaultValue] = v ?? ValueType.proto3DefaultValue consumed = true } internal mutating func decodeMapField<KeyType, ValueType>(fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type, value: inout _ProtobufEnumMap<KeyType, ValueType>.BaseType) throws where ValueType.RawValue == Int { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var k: KeyType.BaseType? var v: ValueType? var count: Int = 0 let p = try getFieldBodyBytes(count: &count) var subdecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self) while let tag = try subdecoder.getTag() { if tag.wireFormat == .endGroup { throw BinaryDecodingError.malformedProtobuf } let fieldNumber = tag.fieldNumber switch fieldNumber { case 1: // Keys are basic types try KeyType.decodeSingular(value: &k, from: &subdecoder) case 2: // Value is an Enum type try subdecoder.decodeSingularEnumField(value: &v) if v == nil && tag.wireFormat == .varint { // Enum decode fail and wire format was varint, so this had to // have been a proto2 unknown enum value. This whole map entry // into the parent message's unknown fields. If the wire format // was wrong, treat it like an unknown field and drop it with // the map entry. return } default: // Skip any other fields within the map entry object try subdecoder.skip() } } if !subdecoder.complete { throw BinaryDecodingError.trailingGarbage } // A map<> definition can't provide a default value for the keys, so it // is safe to use the proto3 default to get the right integer/string/bytes. value[k ?? KeyType.proto3DefaultValue] = v ?? ValueType() consumed = true } internal mutating func decodeMapField<KeyType, ValueType>(fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type, value: inout _ProtobufMessageMap<KeyType, ValueType>.BaseType) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var k: KeyType.BaseType? var v: ValueType? var count: Int = 0 let p = try getFieldBodyBytes(count: &count) var subdecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self) while let tag = try subdecoder.getTag() { if tag.wireFormat == .endGroup { throw BinaryDecodingError.malformedProtobuf } let fieldNumber = tag.fieldNumber switch fieldNumber { case 1: // Keys are basic types try KeyType.decodeSingular(value: &k, from: &subdecoder) case 2: // Value is a message type try subdecoder.decodeSingularMessageField(value: &v) default: // Skip any other fields within the map entry object try subdecoder.skip() } } if !subdecoder.complete { throw BinaryDecodingError.trailingGarbage } // A map<> definition can't provide a default value for the keys, so it // is safe to use the proto3 default to get the right integer/string/bytes. value[k ?? KeyType.proto3DefaultValue] = v ?? ValueType() consumed = true } internal mutating func decodeExtensionField( values: inout ExtensionFieldValueSet, messageType: Message.Type, fieldNumber: Int ) throws { if let ext = extensions?[messageType, fieldNumber] { try decodeExtensionField(values: &values, messageType: messageType, fieldNumber: fieldNumber, messageExtension: ext) } } /// Helper to reuse between Extension decoding and MessageSet Extension decoding. private mutating func decodeExtensionField( values: inout ExtensionFieldValueSet, messageType: Message.Type, fieldNumber: Int, messageExtension ext: AnyMessageExtension ) throws { assert(!consumed) assert(fieldNumber == ext.fieldNumber) try values.modify(index: fieldNumber) { fieldValue in // Message/Group extensions both will call back into the matching // decode methods, so the recursion depth will be tracked there. if fieldValue != nil { try fieldValue!.decodeExtensionField(decoder: &self) } else { fieldValue = try ext._protobuf_newField(decoder: &self) } if consumed && fieldValue == nil { // Really things should never get here, if the decoder says // the bytes were consumed, then there should have been a // field that consumed them (existing or created). This // specific error result is to allow this to be more detectable. throw BinaryDecodingError.internalExtensionError } } } internal mutating func decodeExtensionFieldsAsMessageSet( values: inout ExtensionFieldValueSet, messageType: Message.Type ) throws { // Spin looking for the Item group, everything else will end up in unknown fields. while let fieldNumber = try self.nextFieldNumber() { guard fieldNumber == WireFormat.MessageSet.FieldNumbers.item && fieldWireFormat == WireFormat.startGroup else { continue } // This is similiar to decodeFullGroup try incrementRecursionDepth() var subDecoder = self subDecoder.groupFieldNumber = fieldNumber subDecoder.consumed = true let itemResult = try subDecoder.decodeMessageSetItem(values: &values, messageType: messageType) switch itemResult { case .success: // Advance over what was parsed. consume(length: available - subDecoder.available) consumed = true case .handleAsUnknown: // Nothing to do. break case .malformed: throw BinaryDecodingError.malformedProtobuf } assert(recursionBudget == subDecoder.recursionBudget) decrementRecursionDepth() } } private enum DecodeMessageSetItemResult { case success case handleAsUnknown case malformed } private mutating func decodeMessageSetItem( values: inout ExtensionFieldValueSet, messageType: Message.Type ) throws -> DecodeMessageSetItemResult { // This is loosely based on the C++: // ExtensionSet::ParseMessageSetItem() // WireFormat::ParseAndMergeMessageSetItem() // (yes, there have two versions that are almost the same) var msgExtension: AnyMessageExtension? var fieldData: Data? // In this loop, if wire types are wrong, things don't decode, // just bail instead of letting things go into unknown fields. // Wrongly formed MessageSets don't seem don't have real // spelled out behaviors. while let fieldNumber = try self.nextFieldNumber() { switch fieldNumber { case WireFormat.MessageSet.FieldNumbers.typeId: var extensionFieldNumber: Int32 = 0 try decodeSingularInt32Field(value: &extensionFieldNumber) if extensionFieldNumber == 0 { return .malformed } guard let ext = extensions?[messageType, Int(extensionFieldNumber)] else { return .handleAsUnknown // Unknown extension. } msgExtension = ext // If there already was fieldData, decode it. if let data = fieldData { var wasDecoded = false try data.withUnsafeBytes { (body: UnsafeRawBufferPointer) in if let baseAddress = body.baseAddress, body.count > 0 { var extDecoder = BinaryDecoder(forReadingFrom: baseAddress, count: body.count, parent: self) // Prime the decode to be correct. extDecoder.consumed = false extDecoder.fieldWireFormat = .lengthDelimited try extDecoder.decodeExtensionField(values: &values, messageType: messageType, fieldNumber: fieldNumber, messageExtension: ext) wasDecoded = extDecoder.consumed } } if !wasDecoded { return .malformed } fieldData = nil } case WireFormat.MessageSet.FieldNumbers.message: if let ext = msgExtension { assert(consumed == false) try decodeExtensionField(values: &values, messageType: messageType, fieldNumber: ext.fieldNumber, messageExtension: ext) if !consumed { return .malformed } } else { // The C++ references ends up appending the blocks together as length // delimited blocks, but the parsing will only use the first block. // So just capture a block, and then skip any others that happen to // be found. if fieldData == nil { var d: Data? try decodeSingularBytesField(value: &d) guard let data = d else { return .malformed } // Save it as length delimited let payloadSize = Varint.encodedSize(of: Int64(data.count)) + data.count var payload = Data(count: payloadSize) payload.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in if let baseAddress = body.baseAddress, body.count > 0 { var encoder = BinaryEncoder(forWritingInto: baseAddress) encoder.putBytesValue(value: data) } } fieldData = payload } else { guard fieldWireFormat == .lengthDelimited else { return .malformed } try skip() consumed = true } } default: // Skip everything else try skip() consumed = true } } return .success } // // Private building blocks for the parsing above. // // Having these be private gives the compiler maximum latitude for // inlining. // /// Private: Advance the current position. private mutating func consume(length: Int) { available -= length p += length } /// Private: Skip the body for the given tag. If the given tag is /// a group, it parses up through the corresponding group end. private mutating func skipOver(tag: FieldTag) throws { switch tag.wireFormat { case .varint: // Don't need the value, just ensuring it is validly encoded. let _ = try decodeVarint() case .fixed64: if available < 8 { throw BinaryDecodingError.truncated } p += 8 available -= 8 case .lengthDelimited: let n = try decodeVarint() if n <= UInt64(available) { p += Int(n) available -= Int(n) } else { throw BinaryDecodingError.truncated } case .startGroup: try incrementRecursionDepth() while true { if let innerTag = try getTagWithoutUpdatingFieldStart() { if innerTag.wireFormat == .endGroup { if innerTag.fieldNumber == tag.fieldNumber { decrementRecursionDepth() break } else { // .endGroup for a something other than the current // group is an invalid binary. throw BinaryDecodingError.malformedProtobuf } } else { try skipOver(tag: innerTag) } } else { throw BinaryDecodingError.truncated } } case .endGroup: throw BinaryDecodingError.malformedProtobuf case .fixed32: if available < 4 { throw BinaryDecodingError.truncated } p += 4 available -= 4 } } /// Private: Skip to the end of the current field. /// /// Assumes that fieldStartP was bookmarked by a previous /// call to getTagType(). /// /// On exit, fieldStartP points to the first byte of the tag, fieldEndP points /// to the first byte after the field contents, and p == fieldEndP. private mutating func skip() throws { if let end = fieldEndP { p = end } else { // Rewind to start of current field. available += p - fieldStartP p = fieldStartP guard let tag = try getTagWithoutUpdatingFieldStart() else { throw BinaryDecodingError.truncated } try skipOver(tag: tag) fieldEndP = p } } /// Private: Parse the next raw varint from the input. private mutating func decodeVarint() throws -> UInt64 { if available < 1 { throw BinaryDecodingError.truncated } var start = p var length = available var c = start.load(fromByteOffset: 0, as: UInt8.self) start += 1 length -= 1 if c & 0x80 == 0 { p = start available = length return UInt64(c) } var value = UInt64(c & 0x7f) var shift = UInt64(7) while true { if length < 1 || shift > 63 { throw BinaryDecodingError.malformedProtobuf } c = start.load(fromByteOffset: 0, as: UInt8.self) start += 1 length -= 1 value |= UInt64(c & 0x7f) << shift if c & 0x80 == 0 { p = start available = length return value } shift += 7 } } /// Private: Get the tag that starts a new field. /// This also bookmarks the start of field for a possible skip(). internal mutating func getTag() throws -> FieldTag? { fieldStartP = p fieldEndP = nil return try getTagWithoutUpdatingFieldStart() } /// Private: Parse and validate the next tag without /// bookmarking the start of the field. This is used within /// skip() to skip over fields within a group. private mutating func getTagWithoutUpdatingFieldStart() throws -> FieldTag? { if available < 1 { return nil } let t = try decodeVarint() if t < UInt64(UInt32.max) { guard let tag = FieldTag(rawValue: UInt32(truncatingIfNeeded: t)) else { throw BinaryDecodingError.malformedProtobuf } fieldWireFormat = tag.wireFormat fieldNumber = tag.fieldNumber return tag } else { throw BinaryDecodingError.malformedProtobuf } } /// Private: Return a Data containing the entirety of /// the current field, including tag. private mutating func getRawField() throws -> Data { try skip() return Data(bytes: fieldStartP, count: fieldEndP! - fieldStartP) } /// Private: decode a fixed-length four-byte number. This generic /// helper handles all four-byte number types. private mutating func decodeFourByteNumber<T>(value: inout T) throws { guard available >= 4 else {throw BinaryDecodingError.truncated} withUnsafeMutableBytes(of: &value) { dest -> Void in dest.copyMemory(from: UnsafeRawBufferPointer(start: p, count: 4)) } consume(length: 4) } /// Private: decode a fixed-length eight-byte number. This generic /// helper handles all eight-byte number types. private mutating func decodeEightByteNumber<T>(value: inout T) throws { guard available >= 8 else {throw BinaryDecodingError.truncated} withUnsafeMutableBytes(of: &value) { dest -> Void in dest.copyMemory(from: UnsafeRawBufferPointer(start: p, count: 8)) } consume(length: 8) } private mutating func decodeFloat() throws -> Float { var littleEndianBytes: UInt32 = 0 try decodeFourByteNumber(value: &littleEndianBytes) var nativeEndianBytes = UInt32(littleEndian: littleEndianBytes) var float: Float = 0 let n = MemoryLayout<Float>.size memcpy(&float, &nativeEndianBytes, n) return float } private mutating func decodeDouble() throws -> Double { var littleEndianBytes: UInt64 = 0 try decodeEightByteNumber(value: &littleEndianBytes) var nativeEndianBytes = UInt64(littleEndian: littleEndianBytes) var double: Double = 0 let n = MemoryLayout<Double>.size memcpy(&double, &nativeEndianBytes, n) return double } /// Private: Get the start and length for the body of // a length-delimited field. private mutating func getFieldBodyBytes(count: inout Int) throws -> UnsafeRawPointer { let length = try decodeVarint() if length <= UInt64(available) { count = Int(length) let body = p consume(length: count) return body } throw BinaryDecodingError.truncated } }
apache-2.0
ee89f0c1d728c2cf18ec3a226b837cc3
36.451047
216
0.562643
5.220727
false
false
false
false
movabletype/mt-data-api-sdk-swift
SDK/DataAPI.swift
1
85941
// // DataAPI.swift // MTDataAPI // // Created by CHEEBOW on 2015/03/23. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import Foundation import Alamofire import SwiftyJSON public class DataAPI: NSObject { //MARK: - Properties fileprivate(set) var token = "" fileprivate(set) var sessionID = "" public var endpointVersion = "v3" public var APIBaseURL = "http://localhost/cgi-bin/MT-6.1/mt-data-api.cgi" fileprivate(set) var apiVersion = "" public var clientID = "MTDataAPIClient" public struct BasicAuth { public var username = "" public var password = "" } public var basicAuth: BasicAuth = BasicAuth() public static var sharedInstance = DataAPI() //MARK: - Methods fileprivate func APIURL() -> String! { return APIBaseURL + "/\(endpointVersion)" } fileprivate func APIURL_V2() -> String! { return APIBaseURL + "/v2" } func urlencoding(_ src: String) -> String! { return src.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) } func urldecoding(_ src: String) -> String! { return src.removingPercentEncoding } func parseParams(_ originalUrl: String) -> [String: String] { let url = originalUrl.components(separatedBy: "?") let core = url[1] let params = core.components(separatedBy: "&") var dict : [String: String] = [:] for param in params{ let keyValue = param.components(separatedBy: "=") dict[keyValue[0]] = keyValue[1] } return dict } fileprivate func errorJSON()->JSON { return JSON(["code":"-1", "message":NSLocalizedString("The operation couldn’t be completed.", comment: "The operation couldn’t be completed.")]) } func resetAuth() { token = "" sessionID = "" } fileprivate func makeRequest(_ method: HTTPMethod, url: URLConvertible, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, useSession: Bool = (false)) -> DataRequest { var headers: [String: String] = [:] if token != "" { headers["X-MT-Authorization"] = "MTAuth accessToken=" + token } if useSession { if sessionID != "" { headers["X-MT-Authorization"] = "MTAuth sessionId=" + sessionID } } var request = Alamofire.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers) if !self.basicAuth.username.isEmpty && !self.basicAuth.password.isEmpty { request = request.authenticate(user: self.basicAuth.username, password: self.basicAuth.password) } return request } public func fetchList(_ url: String, params: Parameters? = nil, success: @escaping ((_ items:[JSON]?, _ total:Int?) -> Void!), failure: ((JSON?) -> Void)!)->Void { let request = makeRequest(.get, url: url, parameters: params) request.responseJSON { response in switch response.result { case .success(let data): let json = JSON(data) if json["error"].dictionary != nil { failure(json["error"]) return } let items = json["items"].array let total = json["totalResults"].intValue success(items, total) case .failure(_): failure(self.errorJSON()) } } } fileprivate func actionCommon(_ action: HTTPMethod, url: String, params: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let request = makeRequest(action, url: url, parameters: params) request.responseJSON { response in switch response.result { case .success(let data): let json = JSON(data) if json["error"].dictionary != nil { failure(json["error"]) return } success(json) case .failure(_): failure(self.errorJSON()) } } } func action(_ name: String, action: HTTPMethod, url: String, object: Parameters? = nil, options: Parameters?, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var params: Parameters = [:] if let options = options { params = options } if let object = object { let json = JSON(object).rawString() params[name] = json as AnyObject? } actionCommon(action, url: url, params: params, success: success, failure: failure) } fileprivate func get(_ url: String, params: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { actionCommon(.get, url: url, params: params, success: success, failure: failure) } fileprivate func post(_ url: String, params: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { actionCommon(.post, url: url, params: params, success: success, failure: failure) } fileprivate func put(_ url: String, params: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { actionCommon(.put, url: url, params: params, success: success, failure: failure) } fileprivate func delete(_ url: String, params: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { actionCommon(.delete, url: url, params: params, success: success, failure: failure) } fileprivate func repeatAction(_ action: HTTPMethod, url: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let request = makeRequest(action, url: url, parameters: options) request.responseJSON { response in switch response.result { case .success(let data): let json = JSON(data) if json["error"].dictionary != nil { failure(json["error"]) return } if json["status"].string == "Complete" || json["restIds"].string == "" { success(json) } else { let headers: NSDictionary = response.response!.allHeaderFields as NSDictionary if let nextURL = headers["X-MT-Next-Phase-URL"] as? String { let url = self.APIURL() + "/" + nextURL self.repeatAction(action, url: url, options: options, success: success, failure: failure) } else { failure(self.errorJSON()) } } case .failure(_): failure(self.errorJSON()) } } } func upload(_ data: Data, fileName: String, url: String, parameters: Parameters? = nil, progress: ((Double) -> Void)? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var headers = Dictionary<String, String>() if token != "" { headers["X-MT-Authorization"] = "MTAuth accessToken=" + token } Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(data, withName: "file", fileName: fileName, mimeType: "application/octet-stream") if let params = parameters { for (key, value) in params { multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key) } } }, to: url, method: .post, headers: headers, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): if !self.basicAuth.username.isEmpty && !self.basicAuth.password.isEmpty { upload.authenticate(user: self.basicAuth.username, password: self.basicAuth.password) } upload.uploadProgress(queue: DispatchQueue.global(qos: .utility)) { uploadProgress in progress?(uploadProgress.fractionCompleted) }.responseJSON { response in switch response.result { case .success(let data): let json = JSON(data) if json["error"].dictionary != nil { failure(json["error"]) return } success(json) case .failure(_): failure(self.errorJSON()) } } case .failure(_): failure(self.errorJSON()) } } ) } //MARK: - APIs //MARK: - # V2 //MARK: - System public func endpoints(_ success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/endpoints" self.fetchList(url, params: nil, success: success, failure: failure) } //MARK: - Authentication func authenticationCommon(_ url: String, username: String, password: String, remember: Bool, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { resetAuth() let params = ["username":username, "password":password, "remember":remember ? "1":"0", "clientId":self.clientID] let request = makeRequest(.post, url: url, parameters: params) request.responseJSON { response in switch response.result { case .success(let data): let json = JSON(data) if json["error"].dictionary != nil { failure(json["error"]) return } if let accessToken = json["accessToken"].string { self.token = accessToken } if let session = json["sessionId"].string { self.sessionID = session } success(json) case .failure(_): failure(self.errorJSON()) } } } public func authentication(_ username: String, password: String, remember: Bool, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/authentication" self.authenticationCommon(url, username: username, password: password, remember: remember, success: success, failure: failure) } public func authenticationV2(_ username: String, password: String, remember: Bool, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL_V2() + "/authentication" self.authenticationCommon(url, username: username, password: password, remember: remember, success: success, failure: failure) } public func getToken(_ success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/token" let request = makeRequest(.post, url: url, useSession: true) if sessionID == "" { failure(self.errorJSON()) return } request.responseJSON { response in switch response.result { case .success(let data): let json = JSON(data) if json["error"].dictionary != nil { failure(json["error"]) return } if let accessToken = json["accessToken"].string { self.token = accessToken } success(json) case .failure(_): failure(self.errorJSON()) } } } public func revokeAuthentication(_ success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/authentication" let request = makeRequest(.delete, url: url) if sessionID == "" { failure(self.errorJSON()) return } request.responseJSON { response in switch response.result { case .success(let data): let json = JSON(data) if json["error"].dictionary != nil { failure(json["error"]) return } self.sessionID = "" success(json) case .failure(_): failure(self.errorJSON()) } } } public func revokeToken(_ success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/token" self.delete(url, success: { (result: JSON?)-> Void in self.token = "" success(result) }, failure: failure) } //MARK: - Search public func search(_ query: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/search" var params: Parameters = [:] if let options = options { params = options } params["search"] = query as AnyObject? self.fetchList(url, params: params, success: success, failure: failure) } //MARK: - Site public func listSites(_ options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites" self.fetchList(url, params: options, success: success, failure: failure) } public func listSitesByParent(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/children" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func siteAction(_ action: HTTPMethod, siteID: String?, site: Parameters?, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites" if action != .post { if let id = siteID { url += "/" + id } } self.action("website", action: action, url: url, object: site, options: options, success: success, failure: failure) } public func createSite(_ site: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.siteAction(.post, siteID: nil, site: site, options: options, success: success, failure: failure) } public func getSite(siteID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.siteAction(.get, siteID: siteID, site: nil, options: options, success: success, failure: failure) } public func updateSite(siteID: String, site: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.siteAction(.put, siteID: siteID, site: site, options: options, success: success, failure: failure) } public func deleteSite(siteID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.siteAction(.delete, siteID: siteID, site: nil, options: options, success: success, failure: failure) } public func backupSite(siteID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/backup" self.get(url, params: options, success: success, failure: failure) } //MARK: - Blog public func listBlogsForUser(_ userID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/users/\(userID)/sites" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func blogAction(_ action: HTTPMethod, blogID: String?, blog: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites" if let id = blogID { url += "/" + id } self.action("blog", action: action, url: url, object: blog, options: options, success: success, failure: failure) } public func createBlog(_ blog: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.blogAction(.post, blogID: nil, blog: blog, options: options, success: success, failure: failure) } public func getBlog(_ blogID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.blogAction(.get, blogID: blogID, blog: nil, options: options, success: success, failure: failure) } public func updateBlog(_ blogID: String, blog: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.blogAction(.put, blogID: blogID, blog: blog, options: options, success: success, failure: failure) } public func deleteBlog(_ blogID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.blogAction(.delete, blogID: blogID, blog: nil, options: options, success: success, failure: failure) } //MARK: - Entry public func listEntries(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/entries" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func entryAction(_ action: HTTPMethod, siteID: String, entryID: String? = nil, entry: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/entries" if action != .post { if let id = entryID { url += "/" + id } } self.action("entry", action: action, url: url, object: entry, options: options, success: success, failure: failure) } public func createEntry(siteID: String, entry: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.entryAction(.post, siteID: siteID, entryID: nil, entry: entry, options: options, success: success, failure: failure) } public func getEntry(siteID: String, entryID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.entryAction(.get, siteID: siteID, entryID: entryID, entry: nil, options: options, success: success, failure: failure) } public func updateEntry(siteID: String, entryID: String, entry: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.entryAction(.put, siteID: siteID, entryID: entryID, entry: entry, options: options, success: success, failure: failure) } public func deleteEntry(siteID: String, entryID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.entryAction(.delete, siteID: siteID, entryID: entryID, entry: nil, options: options, success: success, failure: failure) } fileprivate func listEntriesForObject(_ objectName: String, siteID: String, objectID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { //objectName:categories,assets,tags let url = APIURL() + "/sites/\(siteID)/\(objectName)/\(objectID)/entries" self.fetchList(url, params: options, success: success, failure: failure) } public func listEntriesForCategory(siteID: String, categoryID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listEntriesForObject("categories", siteID: siteID, objectID: categoryID, options: options, success: success, failure: failure) } public func listEntriesForAsset(siteID: String, assetID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listEntriesForObject("assets", siteID: siteID, objectID: assetID, options: options, success: success, failure: failure) } public func listEntriesForSiteAndTag(siteID: String, tagID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listEntriesForObject("tags", siteID: siteID, objectID: tagID, options: options, success: success, failure: failure) } public func exportEntries(siteID: String, options: Parameters? = nil, success: ((String?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/entries/export" let request = makeRequest(.get, url: url, parameters: options) request.responseData{(response) -> Void in switch response.result { case .success(let data): let result: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String if (result.hasPrefix("{\"error\":")) { let json = JSON(data:data) failure(json["error"]) return } success(result) case .failure(_): failure(self.errorJSON()) } } } public func publishEntries(_ entryIDs: [String], options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/publish/entries" var params: Parameters = [:] if let options = options { params = options } params["ids"] = entryIDs.joined(separator: ",") as AnyObject? self.repeatAction(.get, url: url, options: params, success: success, failure: failure) } fileprivate func importEntriesWithFile(siteID: String, importData: Data, options: Parameters? = nil, progress: ((Double) -> Void)? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/entries/import" self.upload(importData, fileName: "import.dat", url: url, parameters: options, progress: progress, success: success, failure: failure) } public func importEntries(siteID: String, importData: Data? = nil, options: Parameters? = nil, progress: ((Double) -> Void)? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { if importData != nil { self.importEntriesWithFile(siteID: siteID, importData: importData!, options: options, progress: progress, success: success, failure: failure) return } let url = APIURL() + "/sites/\(siteID)/entries/import" self.post(url, params: options as [String : AnyObject]?, success: success, failure: failure) } public func previewEntry(siteID: String, entryID: String? = nil, entry: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/entries" if let id = entryID { url += "/\(id)/preview" } else { url += "/preview" } self.action("entry", action: .post, url: url, object: entry, options: options, success: success, failure: failure) } //MARK: - Page public func listPages(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/pages" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func pageAction(_ action: HTTPMethod, siteID: String, pageID: String? = nil, page: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/pages" if action != .post { if let id = pageID { url += "/" + id } } self.action("page", action: action, url: url, object: page, options: options, success: success, failure: failure) } public func createPage(siteID: String, page: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.pageAction(.post, siteID: siteID, pageID: nil, page: page, options: options, success: success, failure: failure) } public func getPage(siteID: String, pageID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.pageAction(.get, siteID: siteID, pageID: pageID, page: nil, options: options, success: success, failure: failure) } public func updatePage(siteID: String, pageID: String, page: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.pageAction(.put, siteID: siteID, pageID: pageID, page: page, options: options, success: success, failure: failure) } public func deletePage(siteID: String, pageID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.pageAction(.delete, siteID: siteID, pageID: pageID, page: nil, options: options, success: success, failure: failure) } fileprivate func listPagesForObject(_ objectName: String, siteID: String, objectID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { //objectName:assets,tags,folders let url = APIURL() + "/sites/\(siteID)/\(objectName)/\(objectID)/pages" self.fetchList(url, params: options, success: success, failure: failure) } public func listPagesForFolder(siteID: String, folderID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listPagesForObject("folders", siteID: siteID, objectID: folderID, options: options, success: success, failure: failure) } public func listPagesForAsset(siteID: String, assetID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listPagesForObject("assets", siteID: siteID, objectID: assetID, options: options, success: success, failure: failure) } public func listPagesForSiteAndTag(siteID: String, tagID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listPagesForObject("tags", siteID: siteID, objectID: tagID, options: options, success: success, failure: failure) } public func previewPage(siteID: String, pageID: String? = nil, entry: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/pages" if let id = pageID { url += "/\(id)/preview" } else { url += "/preview" } self.action("page", action: .post, url: url, object: entry, options: options, success: success, failure: failure) } //MARK: - Category public func listCategories(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/categories" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func categoryAction(_ action: HTTPMethod, siteID: String, categoryID: String? = nil, category: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/categories" if action != .post { if let id = categoryID { url += "/" + id } } self.action("category", action: action, url: url, object: category, options: options, success: success, failure: failure) } public func createCategory(siteID: String, category: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.categoryAction(.post, siteID: siteID, categoryID: nil, category: category, options: options, success: success, failure: failure) } public func getCategory(siteID: String, categoryID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.categoryAction(.get, siteID: siteID, categoryID: categoryID, category: nil, options: options, success: success, failure: failure) } public func updateCategory(siteID: String, categoryID: String, category: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.categoryAction(.put, siteID: siteID, categoryID: categoryID, category: category, options: options, success: success, failure: failure) } public func deleteCategory(siteID: String, categoryID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.categoryAction(.delete, siteID: siteID, categoryID: categoryID, category: nil, options: options, success: success, failure: failure) } public func listCategoriesForEntry(siteID: String, entryID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/entries/\(entryID)/categories" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func listCategoriesForRelation(_ relation: String, siteID: String, categoryID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { //relation:parents,siblings,children let url = APIURL() + "/sites/\(siteID)/categories/\(categoryID)/\(relation)" self.fetchList(url, params: options, success: success, failure: failure) } public func listParentCategories(siteID: String, categoryID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listCategoriesForRelation("parents", siteID: siteID, categoryID: categoryID, options: options, success: success, failure: failure) } public func listSiblingCategories(siteID: String, categoryID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listCategoriesForRelation("siblings", siteID: siteID, categoryID: categoryID, options: options, success: success, failure: failure) } public func listChildCategories(siteID: String, categoryID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listCategoriesForRelation("children", siteID: siteID, categoryID: categoryID, options: options, success: success, failure: failure) } public func permutateCategories(siteID: String, categories: [Parameters]? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/categories/permutate" var params: Parameters = [:] if let options = options { params = options } if let categories = categories { let json = JSON(categories).rawString() params["categories"] = json as AnyObject? } self.post(url, params: params, success: success, failure: failure) } //MARK: - Folder public func listFolders(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/folders" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func folderAction(_ action: HTTPMethod, siteID: String, folderID: String? = nil, folder: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/folders" if let id = folderID { url += "/" + id } self.action("folder", action: action, url: url, object: folder, options: options, success: success, failure: failure) } public func createFolder(siteID: String, folder: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.folderAction(.post, siteID: siteID, folderID: nil, folder: folder, options: options, success: success, failure: failure) } public func getFolder(siteID: String, folderID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.folderAction(.get, siteID: siteID, folderID: folderID, folder: nil, options: options, success: success, failure: failure) } public func updateFolder(siteID: String, folderID: String, folder: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.folderAction(.put, siteID: siteID, folderID: folderID, folder: folder, options: options, success: success, failure: failure) } public func deleteFolder(siteID: String, folderID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.folderAction(.delete, siteID: siteID, folderID: folderID, folder: nil, options: options, success: success, failure: failure) } fileprivate func listFoldersForRelation(_ relation: String, siteID: String, folderID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { //relation:parents,siblings,children let url = APIURL() + "/sites/\(siteID)/folders/\(folderID)/\(relation)" self.fetchList(url, params: options, success: success, failure: failure) } public func listParentFolders(siteID: String, folderID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listFoldersForRelation("parents", siteID: siteID, folderID: folderID, options: options, success: success, failure: failure) } public func listSiblingFolders(siteID: String, folderID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listFoldersForRelation("siblings", siteID: siteID, folderID: folderID, options: options, success: success, failure: failure) } public func listChildFolders(siteID: String, folderID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listFoldersForRelation("children", siteID: siteID, folderID: folderID, options: options, success: success, failure: failure) } public func permutateFolders(siteID: String, folders: [Parameters]? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/folders/permutate" var params: Parameters = [:] if let options = options { params = options } if let folders = folders { let json = JSON(folders).rawString() params["folders"] = json as AnyObject? } self.post(url, params: params, success: success, failure: failure) } //MARK: - Tag public func listTags(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/tags" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func tagAction(_ action: HTTPMethod, siteID: String, tagID: String, tag: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { if action == .post { failure(self.errorJSON()) return } let url = APIURL() + "/sites/\(siteID)/tags/\(tagID)" self.action("tag", action: action, url: url, object: tag, options: options, success: success, failure: failure) } public func getTag(siteID: String, tagID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.tagAction(.get, siteID: siteID, tagID: tagID, tag: nil, options: options, success: success, failure: failure) } public func updateTag(siteID: String, tagID: String, tag: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.tagAction(.put, siteID: siteID, tagID: tagID, tag: tag, options: options, success: success, failure: failure) } public func deleteTag(siteID: String, tagID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.tagAction(.delete, siteID: siteID, tagID: tagID, tag: nil, options: options, success: success, failure: failure) } //MARK: - User public func listUsers(_ options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/users" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func userAction(_ action: HTTPMethod, userID: String? = nil, user: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/users" if action != .post { if let id = userID { url += "/" + id } } self.action("user", action: action, url: url, object: user, options: options, success: success, failure: failure) } public func createUser(_ user: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.userAction(.post, userID: nil, user: user, options: options, success: success, failure: failure) } public func getUser(_ userID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.userAction(.get, userID: userID, user: nil, options: options, success: success, failure: failure) } public func updateUser(_ userID: String, user: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.userAction(.put, userID: userID, user: user, options: options, success: success, failure: failure) } public func deleteUser(_ userID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.userAction(.delete, userID: userID, user: nil, options: options, success: success, failure: failure) } public func unlockUser(_ userID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/users/\(userID)/unlock" self.post(url, params: options, success: success, failure: failure) } public func recoverPasswordForUser(_ userID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/users/\(userID)/recover_password" self.post(url, params: options, success: success, failure: failure) } public func recoverPassword(_ name: String, email: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/recover_password" var params: Parameters = [:] if let options = options { params = options } params["name"] = name as AnyObject? params["email"] = email as AnyObject? self.post(url, params: params, success: success, failure: failure) } //MARK: - Asset public func listAssets(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/assets" self.fetchList(url, params: options, success: success, failure: failure) } public func uploadAsset(_ assetData: Data, fileName: String, options: Parameters? = nil, progress: ((Double) -> Void)? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.uploadAssetForSite(nil, assetData: assetData, fileName: fileName, options: options, progress: progress, success: success, failure: failure) } public func uploadAssetForSite(_ siteID: String? = nil, assetData: Data, fileName: String, options: Parameters? = nil, progress: ((Double) -> Void)? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/" if let siteID = siteID { url += "sites/\(siteID)/assets/upload" } else { url += "assets/upload" } self.upload(assetData, fileName: fileName, url: url, parameters: options, progress: progress, success: success, failure: failure) } fileprivate func assetAction(_ action: HTTPMethod, siteID: String, assetID: String, asset: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/assets" if action != .post { url += "/" + assetID } else { failure(self.errorJSON()) return } self.action("asset", action: action, url: url, object: asset, options: options, success: success, failure: failure) } public func getAsset(siteID: String, assetID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.assetAction(.get, siteID: siteID, assetID: assetID, asset: nil, options: options, success: success, failure: failure) } public func updateAsset(siteID: String, assetID: String, asset: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.assetAction(.put, siteID: siteID, assetID: assetID, asset: asset, options: options, success: success, failure: failure) } public func deleteAsset(siteID: String, assetID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.assetAction(.delete, siteID: siteID, assetID: assetID, asset: nil, options: options, success: success, failure: failure) } fileprivate func listAssetsForObject(_ objectName: String, siteID: String, objectID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { //objectName:entries,pages,tags let url = APIURL() + "/sites/\(siteID)/\(objectName)/\(objectID)/assets" self.fetchList(url, params: options, success: success, failure: failure) } public func listAssetsForEntry(siteID: String, entryID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listAssetsForObject("entries", siteID: siteID, objectID: entryID, options: options, success: success, failure: failure) } public func listAssetsForPage(siteID: String, pageID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listAssetsForObject("pages", siteID: siteID, objectID: pageID, options: options, success: success, failure: failure) } public func listAssetsForSiteAndTag(siteID: String, tagID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listAssetsForObject("tags", siteID: siteID, objectID: tagID, options: options, success: success, failure: failure) } public func getThumbnail(siteID: String, assetID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/assets/\(assetID)/thumbnail" self.get(url, params: options, success: success, failure: failure) } //MARK: - Comment public func listComments(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/comments" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func commentAction(_ action: HTTPMethod, siteID: String, commentID: String, comment: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/comments" if action != .post { url += "/" + commentID } else { //use createCommentForEntry or createCommentForPage failure(self.errorJSON()) return } self.action("comment", action: action, url: url, object: comment, options: options, success: success, failure: failure) } public func getComment(siteID: String, commentID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.commentAction(.get, siteID: siteID, commentID: commentID, comment: nil, options: options, success: success, failure: failure) } public func updateComment(siteID: String, commentID: String, comment: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.commentAction(.put, siteID: siteID, commentID: commentID, comment: comment, options: options, success: success, failure: failure) } public func deleteComment(siteID: String, commentID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.commentAction(.delete, siteID: siteID, commentID: commentID, comment: nil, options: options, success: success, failure: failure) } fileprivate func listCommentsForObject(_ objectName: String, siteID: String, objectID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { //objectName:entries,pages let url = APIURL() + "/sites/\(siteID)/\(objectName)/\(objectID)/comments" self.fetchList(url, params: options, success: success, failure: failure) } public func listCommentsForEntry(siteID: String, entryID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listCommentsForObject("entries", siteID: siteID, objectID: entryID, options: options, success: success, failure: failure) } public func listCommentsForPage(siteID: String, pageID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listCommentsForObject("pages", siteID: siteID, objectID: pageID, options: options, success: success, failure: failure) } fileprivate func createCommentForObject(_ objectName: String, siteID: String, objectID: String, comment: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { //objectName:entries,pages let url = APIURL() + "/sites/\(siteID)/\(objectName)/\(objectID)/comments" self.action("comment", action: .post, url: url, object: comment, options: options, success: success, failure: failure) } public func createCommentForEntry(siteID: String, entryID: String, comment: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.createCommentForObject("entries", siteID: siteID, objectID: entryID, comment: comment, options: options, success: success, failure: failure) } public func createCommentForPage(siteID: String, pageID: String, comment: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.createCommentForObject("pages", siteID: siteID, objectID: pageID, comment: comment, options: options, success: success, failure: failure) } fileprivate func createReplyCommentForObject(_ objectName: String, siteID: String, objectID: String, commentID: String, reply: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { //objectName:entries,pages let url = APIURL() + "/sites/\(siteID)/\(objectName)/\(objectID)/comments/\(commentID)/replies" self.action("comment", action: .post, url: url, object: reply, options: options, success: success, failure: failure) } public func createReplyCommentForEntry(siteID: String, entryID: String, commentID: String, reply: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.createReplyCommentForObject("entries", siteID: siteID, objectID: entryID, commentID: commentID, reply: reply, options: options, success: success, failure: failure) } public func createReplyCommentForPage(siteID: String, pageID: String, commentID: String, reply: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.createReplyCommentForObject("pages", siteID: siteID, objectID: pageID, commentID: commentID, reply: reply, options: options, success: success, failure: failure) } //MARK: - Trackback public func listTrackbacks(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/trackbacks" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func trackbackAction(_ action: HTTPMethod, siteID: String, trackbackID: String, trackback: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/trackbacks" if action != .post { url += "/" + trackbackID } else { failure(self.errorJSON()) return } self.action("comment", action: action, url: url, object: trackback, options: options, success: success, failure: failure) } public func getTrackback(siteID: String, trackbackID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.trackbackAction(.get, siteID: siteID, trackbackID: trackbackID, trackback: nil, options: options, success: success, failure: failure) } public func updateTrackback(siteID: String, trackbackID: String, trackback: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.trackbackAction(.put, siteID: siteID, trackbackID: trackbackID, trackback: trackback, options: options, success: success, failure: failure) } public func deleteTrackback(siteID: String, trackbackID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.trackbackAction(.delete, siteID: siteID, trackbackID: trackbackID, trackback: nil, options: options, success: success, failure: failure) } fileprivate func listTrackbackForObject(_ objectName: String, siteID: String, objectID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { //objectName:entries,pages let url = APIURL() + "/sites/\(siteID)/\(objectName)/\(objectID)/trackbacks" self.fetchList(url, params: options, success: success, failure: failure) } public func listTrackbackForEntry(siteID: String, entryID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listTrackbackForObject("entries", siteID: siteID, objectID: entryID, options: options, success: success, failure: failure) } public func listTrackbackForPage(siteID: String, pageID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listTrackbackForObject("pages", siteID: siteID, objectID: pageID, options: options, success: success, failure: failure) } //MARK: - Field public func listFields(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/fields" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func fieldAction(_ action: HTTPMethod, siteID: String, fieldID: String? = nil, field: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/fields" if action != .post { if let fieldID = fieldID { url += "/" + fieldID } } self.action("field", action: action, url: url, object: field, options: options, success: success, failure: failure) } public func createField(siteID: String, field: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.fieldAction(.post, siteID: siteID, fieldID: nil, field: field, options: options, success: success, failure: failure) } public func getField(siteID: String, fieldID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.fieldAction(.get, siteID: siteID, fieldID: fieldID, field: nil, options: options, success: success, failure: failure) } public func updateField(siteID: String, fieldID: String, field: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.fieldAction(.put, siteID: siteID, fieldID: fieldID, field: field, options: options, success: success, failure: failure) } public func deleteField(siteID: String, fieldID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.fieldAction(.delete, siteID: siteID, fieldID: fieldID, field: nil, options: options, success: success, failure: failure) } //MARK: - Template public func listTemplates(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/templates" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func templateAction(_ action: HTTPMethod, siteID: String, templateID: String? = nil, template: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/templates" if action != .post { if let id = templateID { url += "/" + id } } self.action("template", action: action, url: url, object: template, options: options, success: success, failure: failure) } public func createTemplate(siteID: String, template: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.templateAction(.post, siteID: siteID, templateID: nil, template: template, options: options, success: success, failure: failure) } public func getTemplate(siteID: String, templateID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.templateAction(.get, siteID: siteID, templateID: templateID, template: nil, options: options, success: success, failure: failure) } public func updateTemplate(siteID: String, templateID: String, template: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.templateAction(.put, siteID: siteID, templateID: templateID, template: template, options: options, success: success, failure: failure) } public func deleteTemplate(siteID: String, templateID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.templateAction(.delete, siteID: siteID, templateID: templateID, template: nil, options: options, success: success, failure: failure) } public func publishTemplate(siteID: String, templateID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/templates/\(templateID)/publish" self.post(url, params: options, success: success, failure: failure) } public func refreshTemplate(siteID: String, templateID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/templates/\(templateID)/refresh" self.post(url, params: options, success: success, failure: failure) } public func refreshTemplateForSite(_ siteID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/refresh_templates" self.post(url, params: options, success: success, failure: failure) } public func cloneTemplate(siteID: String, templateID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/templates/\(templateID)/clone" self.post(url, params: options, success: success, failure: failure) } //MARK: - TemplateMap public func listTemplateMaps(siteID: String, templateID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/templates/\(templateID)/templatemaps" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func templateMapAction(_ action: HTTPMethod, siteID: String, templateID: String, templateMapID: String? = nil, templateMap: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/templates/\(templateID)/templatemaps" if action != .post { if let id = templateMapID { url += "/" + id } } self.action("templatemap", action: action, url: url, object: templateMap, options: options, success: success, failure: failure) } public func createTemplateMap(siteID: String, templateID: String, templateMap: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.templateMapAction(.post, siteID: siteID, templateID: templateID, templateMapID: nil, templateMap: templateMap, options: options, success: success, failure: failure) } public func getTemplateMap(siteID: String, templateID: String, templateMapID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.templateMapAction(.get, siteID: siteID, templateID: templateID, templateMapID: templateMapID, templateMap: nil, options: options, success: success, failure: failure) } public func updateTemplateMap(siteID: String, templateID: String, templateMapID: String, templateMap: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.templateMapAction(.put, siteID: siteID, templateID: templateID, templateMapID: templateMapID, templateMap: templateMap, options: options, success: success, failure: failure) } public func deleteTemplateMap(siteID: String, templateID: String, templateMapID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.templateMapAction(.delete, siteID: siteID, templateID: templateID, templateMapID: templateMapID, templateMap: nil, options: options, success: success, failure: failure) } //MARK: - Widget public func listWidgets(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/widgets" self.fetchList(url, params: options, success: success, failure: failure) } public func listWidgetsForWidgetset(siteID: String, widgetsetID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/widgetsets/\(widgetsetID)/widgets" self.fetchList(url, params: options, success: success, failure: failure) } public func getWidgetForWidgetset(siteID: String, widgetSetID: String, widgetID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/widgetsets/\(widgetSetID)/widgets/\(widgetID)" self.action("widget", action: .get, url: url, options: options, success: success, failure: failure) } fileprivate func widgetAction(_ action: HTTPMethod, siteID: String, widgetID: String? = nil, widget: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/widgets" if action != .post { if let id = widgetID { url += "/" + id } } self.action("widget", action: action, url: url, object: widget, options: options, success: success, failure: failure) } public func createWidget(siteID: String, widget: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.widgetAction(.post, siteID: siteID, widgetID: nil, widget: widget, options: options, success: success, failure: failure) } public func getWidget(siteID: String, widgetID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.widgetAction(.get, siteID: siteID, widgetID: widgetID, widget: nil, options: options, success: success, failure: failure) } public func updateWidget(siteID: String, widgetID: String, widget: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.widgetAction(.put, siteID: siteID, widgetID: widgetID, widget: widget, options: options, success: success, failure: failure) } public func deleteWidget(siteID: String, widgetID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.widgetAction(.delete, siteID: siteID, widgetID: widgetID, widget: nil, options: options, success: success, failure: failure) } public func refreshWidget(siteID: String, widgetID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/widgets/\(widgetID)/refresh" self.post(url, params: options, success: success, failure: failure) } public func cloneWidget(siteID: String, widgetID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/widgets/\(widgetID)/clone" self.post(url, params: options, success: success, failure: failure) } //MARK: - WidgetSet public func listWidgetSets(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/widgetsets" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func widgetSetAction(_ action: HTTPMethod, siteID: String, widgetSetID: String? = nil, widgetSet: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/widgetsets" if action != .post { if let id = widgetSetID { url += "/" + id } } self.action("widgetset", action: action, url: url, object: widgetSet, options: options, success: success, failure: failure) } public func createWidgetSet(siteID: String, widgetSet: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.widgetSetAction(.post, siteID: siteID, widgetSetID: nil, widgetSet: widgetSet, options: options, success: success, failure: failure) } public func getWidgetSet(siteID: String, widgetSetID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.widgetSetAction(.get, siteID: siteID, widgetSetID: widgetSetID, widgetSet: nil, options: options, success: success, failure: failure) } public func updateWidgetSet(siteID: String, widgetSetID: String, widgetSet: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.widgetSetAction(.put, siteID: siteID, widgetSetID: widgetSetID, widgetSet: widgetSet, options: options, success: success, failure: failure) } public func deleteWidgetSet(siteID: String, widgetSetID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.widgetSetAction(.delete, siteID: siteID, widgetSetID: widgetSetID, widgetSet: nil, options: options, success: success, failure: failure) } //MARK: - Theme public func listThemes(_ options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/themes" self.fetchList(url, params: options, success: success, failure: failure) } public func getTheme(_ themeID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/themes/\(themeID)" self.get(url, params: options, success: success, failure: failure) } public func applyThemeToSite(siteID: String, themeID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/themes/\(themeID)/apply" self.post(url, params: options, success: success, failure: failure) } public func uninstallTheme(_ themeID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/themes/\(themeID)" self.delete(url, params: options, success: success, failure: failure) } public func exportSiteTheme(siteID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/export_theme" self.post(url, params: options, success: success, failure: failure) } //MARK: - Role public func listRoles(_ options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/roles" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func roleAction(_ action: HTTPMethod, roleID: String? = nil, role: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/roles" if action != .post { if let id = roleID { url += "/" + id } } self.action("role", action: action, url: url, object: role, options: options, success: success, failure: failure) } public func createRole(_ role: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.roleAction(.post, roleID: nil, role: role, options: options, success: success, failure: failure) } public func getRole(_ roleID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.roleAction(.get, roleID: roleID, role: nil, options: options, success: success, failure: failure) } public func updateRole(_ roleID: String, role: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.roleAction(.put, roleID: roleID, role: role, options: options, success: success, failure: failure) } public func deleteRole(_ roleID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.roleAction(.delete, roleID: roleID, role: nil, options: options, success: success, failure: failure) } //MARK: - Permission public func listPermissions(_ options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/permissions" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func listPermissionsForObject(_ objectName: String, objectID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { //objectName:users,sites,roles let url = APIURL() + "/\(objectName)/\(objectID)/permissions" self.fetchList(url, params: options, success: success, failure: failure) } public func listPermissionsForUser(_ userID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listPermissionsForObject("users", objectID: userID, options: options, success: success, failure: failure) } public func listPermissionsForSite(_ siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listPermissionsForObject("sites", objectID: siteID, options: options, success: success, failure: failure) } public func listPermissionsForRole(_ roleID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listPermissionsForObject("roles", objectID: roleID, options: options, success: success, failure: failure) } public func grantPermissionToSite(_ siteID: String, userID: String, roleID: String, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/permissions/grant" var params: Parameters = [:] params["user_id"] = userID params["role_id"] = roleID self.post(url, params: params as [String : AnyObject]?, success: success, failure: failure) } public func grantPermissionToUser(_ userID: String, siteID: String, roleID: String, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "//users/\(userID)/permissions/grant" var params: Parameters = [:] params["site_id"] = siteID params["role_id"] = roleID self.post(url, params: params as [String : AnyObject]?, success: success, failure: failure) } public func revokePermissionToSite(_ siteID: String, userID: String, roleID: String, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/permissions/revoke" var params: Parameters = [:] params["user_id"] = userID params["role_id"] = roleID self.post(url, params: params as [String : AnyObject]?, success: success, failure: failure) } public func revokePermissionToUser(_ userID: String, siteID: String, roleID: String, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/users/\(userID)/permissions/revoke" var params: Parameters = [:] params["site_id"] = siteID params["role_id"] = roleID self.post(url, params: params, success: success, failure: failure) } //MARK: - Log public func listLogs(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/logs" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func logAction(_ action: HTTPMethod, siteID: String, logID: String? = nil, log: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/logs" if action != .post { if let id = logID { url += "/" + id } } self.action("log", action: action, url: url, object: log, options: options, success: success, failure: failure) } public func createLog(siteID: String, log: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.logAction(.post, siteID: siteID, logID: nil, log: log, options: options, success: success, failure: failure) } public func getLog(siteID: String, logID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.logAction(.get, siteID: siteID, logID: logID, log: nil, options: options, success: success, failure: failure) } public func updateLog(siteID: String, logID: String, log: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.logAction(.put, siteID: siteID, logID: logID, log: log, options: options, success: success, failure: failure) } public func deleteLog(siteID: String, logID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.logAction(.delete, siteID: siteID, logID: logID, log: nil, options: options, success: success, failure: failure) } public func resetLogs(siteID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/logs" self.delete(url, params: options, success: success, failure: failure) } public func exportLogs(siteID: String, options: Parameters? = nil, success: ((String?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/logs/export" let request = makeRequest(.get, url: url, parameters: options) request.responseData{(response) -> Void in switch response.result { case .success(let data): //FIXME:ShiftJIS以外の場合もある? let result: String = NSString(data: data, encoding: String.Encoding.shiftJIS.rawValue)! as String if (result.hasPrefix("{\"error\":")) { let json = JSON(data:data) failure(json["error"]) return } success(result) case .failure(_): failure(self.errorJSON()) } } } //MARK: - FormattedText public func listFormattedTexts(siteID: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/formatted_texts" self.fetchList(url, params: options, success: success, failure: failure) } fileprivate func formattedTextAction(_ action: HTTPMethod, siteID: String, formattedTextID: String? = nil, formattedText: Parameters? = nil, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/sites/\(siteID)/formatted_texts" if action != .post { if let id = formattedTextID { url += "/" + id } } self.action("formatted_text", action: action, url: url, object: formattedText, options: options, success: success, failure: failure) } public func createFormattedText(siteID: String, formattedText: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.formattedTextAction(.post, siteID: siteID, formattedTextID: nil, formattedText: formattedText, options: options, success: success, failure: failure) } public func getFormattedText(siteID: String, formattedTextID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.formattedTextAction(.get, siteID: siteID, formattedTextID: formattedTextID, formattedText: nil, options: options, success: success, failure: failure) } public func updateFormattedText(siteID: String, formattedTextID: String, formattedText: Parameters, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.formattedTextAction(.put, siteID: siteID, formattedTextID: formattedTextID, formattedText: formattedText, options: options, success: success, failure: failure) } public func deleteFormattedText(siteID: String, formattedTextID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.formattedTextAction(.delete, siteID: siteID, formattedTextID: formattedTextID, formattedText: nil, options: options, success: success, failure: failure) } //MARK: - Stats public func getStatsProvider(siteID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/stats/provider" self.get(url, params: options, success: success, failure: failure) } fileprivate func listStatsForTarget(siteID: String, targetName: String, objectName: String, startDate: String, endDate: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/sites/\(siteID)/stats/\(targetName)/\(objectName)" var params: Parameters = [:] if let options = options { params = options } params["startDate"] = startDate as AnyObject? params["endDate"] = endDate as AnyObject? self.fetchList(url, params: params, success: success, failure: failure) } fileprivate func listStatsForPath(siteID: String, objectName: String, startDate: String, endDate: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { //objectName:pageviews, visits self.listStatsForTarget(siteID: siteID, targetName: "path", objectName: objectName, startDate: startDate, endDate: endDate, options: options, success: success, failure: failure) } public func pageviewsForPath(siteID: String, startDate: String, endDate: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listStatsForPath(siteID: siteID, objectName: "pageviews", startDate: startDate, endDate: endDate, options: options, success: success, failure: failure) } public func visitsForPath(siteID: String, startDate: String, endDate: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listStatsForPath(siteID: siteID, objectName: "visits", startDate: startDate, endDate: endDate, options: options, success: success, failure: failure) } fileprivate func listStatsForDate(siteID: String, objectName: String, startDate: String, endDate: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { //objectName:pageviews, visits self.listStatsForTarget(siteID: siteID, targetName: "date", objectName: objectName, startDate: startDate, endDate: endDate, options: options, success: success, failure: failure) } public func pageviewsForDate(siteID: String, startDate: String, endDate: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listStatsForDate(siteID: siteID, objectName: "pageviews", startDate: startDate, endDate: endDate, options: options, success: success, failure: failure) } public func visitsForDate(siteID: String, startDate: String, endDate: String, options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.listStatsForDate(siteID: siteID, objectName: "visits", startDate: startDate, endDate: endDate, options: options, success: success, failure: failure) } //MARK: - Plugin public func listPlugins(_ options: Parameters? = nil, success: ((_ items:[JSON]?, _ total:Int?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/plugins" self.fetchList(url, params: options, success: success, failure: failure) } public func getPlugin(_ pluginID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIURL() + "/plugins/\(pluginID)" self.get(url, params: options, success: success, failure: failure) } fileprivate func togglePlugin(_ pluginID: String, enable: Bool, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { var url = APIURL() + "/plugins" if pluginID != "*" { url += "/" + pluginID } if enable { url += "/enable" } else { url += "/disable" } self.post(url, params: options, success: success, failure: failure) } public func enablePlugin(_ pluginID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.togglePlugin(pluginID, enable: true, options: options, success: success, failure: failure) } public func disablePlugin(_ pluginID: String, options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.togglePlugin(pluginID, enable: false, options: options, success: success, failure: failure) } public func enableAllPlugin(_ options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.togglePlugin("*", enable: true, options: options, success: success, failure: failure) } public func disableAllPlugin(_ options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { self.togglePlugin("*", enable: false, options: options, success: success, failure: failure) } //MARK: - # V3 //MARK: - Version public func version(_ options: Parameters? = nil, success: ((JSON?) -> Void)!, failure: ((JSON?) -> Void)!)->Void { let url = APIBaseURL + "/version" self.get(url, success: {(result: JSON?)-> Void in if let result = result { self.endpointVersion = result["endpointVersion"].stringValue self.apiVersion = result["apiVersion"].stringValue } success(result) }, failure: failure ) } }
mit
ad25539d417e36d2d31f41ae8d6ecbaa
52.002468
252
0.61244
4.174781
false
false
false
false
swipe-org/swipe
sample/sample/SwipeVideoController.swift
3
11283
// // SwipeVideoController.swift // iheadunit // // Created by satoshi on 11/22/16. // Copyright © 2016 Satoshi Nakajima. All rights reserved. // import UIKit import AVFoundation class SwipeVideoController: UIViewController { static var playerItemContext = "playerItemContext" fileprivate var document = [String:Any]() fileprivate var pages = [[String:Any]]() fileprivate weak var delegate:SwipeDocumentViewerDelegate? fileprivate var url:URL? fileprivate let videoPlayer = AVPlayer() fileprivate var videoLayer:AVPlayerLayer! fileprivate let overlayLayer = CALayer() fileprivate var index = 0 fileprivate var observer:Any? fileprivate var layers = [String:CALayer]() fileprivate var dimension = CGSize(width:320, height:568) deinit { print("SVideoC deinit") } override func viewDidLoad() { super.viewDidLoad() videoLayer = AVPlayerLayer(player: self.videoPlayer) overlayLayer.masksToBounds = true view.layer.addSublayer(self.videoLayer) view.layer.addSublayer(self.overlayLayer) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let frame = CGRect(origin: .zero, size: dimension) self.videoLayer.frame = frame self.overlayLayer.frame = frame let viewSize = view.bounds.size let scale = min(viewSize.width / dimension.width, viewSize.height / dimension.height) var xf = CATransform3DMakeScale(scale, scale, 0) xf = CATransform3DTranslate(xf, (viewSize.width - dimension.width) / 2.0 / scale, (viewSize.height - dimension.height) / 2.0 / scale, 0.0) self.videoLayer.transform = xf self.overlayLayer.transform = xf } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension SwipeVideoController: SwipeDocumentViewer { func documentTitle() -> String? { return document["title"] as? String } func loadDocument(_ document:[String:Any], size:CGSize, url:URL?, state:[String:Any]?, callback:@escaping (Float, NSError?)->(Void)) throws { self.document = document self.url = url guard let filename = document["video"] as? String, let pages = document["pages"] as? [[String:Any]] else { throw SwipeError.invalidDocument } self.pages = pages if let dimension = document["dimension"] as? [CGFloat], dimension.count == 2 { self.dimension = CGSize(width: dimension[0], height: dimension[1]) } guard let videoURL = Bundle.main.url(forResource: filename, withExtension: nil) else { return } let playerItem = AVPlayerItem(url:videoURL) videoPlayer.replaceCurrentItem(with: playerItem) if let elements = document["elements"] as? [[String:Any]] { print("elements", elements) for element in elements { if let id = element["id"] as? String { var h = element["h"] as? CGFloat var w = element["w"] as? CGFloat let layer = CALayer() if let imageName = element["img"] as? String, let image = UIImage(named: imageName) { layer.contents = image.cgImage if let h = h { if w == nil { w = h / image.size.height * image.size.width } } else if let w = w { h = w / image.size.width * image.size.height } else { h = image.size.height w = image.size.width } } if let h = h, let w = w { layer.frame = CGRect(origin: .zero, size: CGSize(width: w, height: h)) layer.backgroundColor = UIColor.blue.cgColor layers[id] = layer } } } } //moveToPageAt(index: 0) playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: &SwipeVideoController.playerItemContext) callback(1.0, nil) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard context == &SwipeVideoController.playerItemContext else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } if keyPath == #keyPath(AVPlayerItem.status) { let status: AVPlayerItemStatus // Get the status change from the change dictionary if let statusNumber = change?[.newKey] as? NSNumber { status = AVPlayerItemStatus(rawValue: statusNumber.intValue)! } else { status = .unknown } // Switch over the status switch status { case .readyToPlay: print("ready") moveToPageAt(index: 0) if let playerItem = videoPlayer.currentItem { playerItem.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), context: &SwipeVideoController.playerItemContext) } default: break } } } func hideUI() -> Bool { return true } func landscape() -> Bool { return false // we might want to change it later } func setDelegate(_ delegate:SwipeDocumentViewerDelegate) { self.delegate = delegate } func becomeZombie() { // no op } func saveState() -> [String:Any]? { return nil } func languages() -> [[String:Any]]? { return nil } func reloadWithLanguageId(_ langId:String) { // no op } private func removeObserver() { if let observer = self.observer { videoPlayer.removeTimeObserver(observer) self.observer = nil print("SVideoC remove observer") } } func moveToPageAt(index:Int) { print("SVideoC moveToPageAt", index) if index < pages.count { self.index = index let page = pages[self.index] let start = page["start"] as? Double ?? 0.0 let duration = page["duration"] as? Double ?? 0.0 let videoPlayer = self.videoPlayer // local guard let playerItem = videoPlayer.currentItem else { return // something is wrong } removeObserver() let time = CMTime(seconds: start, preferredTimescale: 600) let tolerance = CMTimeMake(10, 600) // 1/60sec playerItem.seek(to: time, toleranceBefore: tolerance, toleranceAfter: tolerance) { (success) in //print("seek complete", success) if duration > 0 { videoPlayer.play() let end = CMTime(seconds: start + duration, preferredTimescale: 600) self.observer = videoPlayer.addBoundaryTimeObserver(forTimes: [end as NSValue], queue: nil) { [weak self] in print("SVideoC pausing", index) videoPlayer.pause() self?.removeObserver() } } else { videoPlayer.pause() } } CATransaction.begin() CATransaction.setDisableActions(true) if let sublayers = overlayLayer.sublayers { for layer in sublayers { layer.removeFromSuperlayer() } } if let elements = page["elements"] as? [[String:Any]] { for element in elements { if let id = element["id"] as? String, let layer = layers[id] { layer.removeAllAnimations() layer.transform = CATransform3DIdentity let x = element["x"] as? CGFloat ?? 0 let y = element["y"] as? CGFloat ?? 0 let frame = CGRect(origin: CGPoint(x:x, y:y), size: layer.frame.size) layer.frame = frame layer.opacity = element["opacity"] as? Float ?? 1.0 overlayLayer.addSublayer(layer) if let to = element["to"] as? [String:Any] { var beginTime:CFTimeInterval? if let start = to["start"] as? Double { beginTime = layer.convertTime(CACurrentMediaTime(), to: nil) + start } let aniDuration = to["duration"] as? Double ?? duration if let tx = to["translate"] as? [CGFloat], tx.count == 2 { let ani = CABasicAnimation(keyPath: "transform") let transform = CATransform3DMakeTranslation(tx[0], tx[1], 0.0) ani.fromValue = CATransform3DIdentity as NSValue ani.toValue = transform as NSValue // NSValue(caTransform3D : transform) ani.fillMode = kCAFillModeBoth if let beginTime = beginTime { ani.beginTime = beginTime } ani.duration = aniDuration layer.add(ani, forKey: "transform") layer.transform = transform } if let opacity = to["opacity"] as? Float { let ani = CABasicAnimation(keyPath: "opacity") ani.fromValue = layer.opacity as NSValue ani.toValue = opacity as NSValue ani.fillMode = kCAFillModeBoth if let beginTime = beginTime { ani.beginTime = beginTime } ani.duration = aniDuration layer.add(ani, forKey: "transform") layer.opacity = opacity } } } } } CATransaction.commit() } } func pageIndex() -> Int? { return index } func pageCount() -> Int? { return pages.count } }
mit
5cc1359224846ef153192a65ae3944e6
38.725352
152
0.500709
5.51687
false
false
false
false
lorentey/swift
benchmark/single-source/Walsh.swift
18
2478
//===--- Walsh.swift ------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils #if os(Linux) import Glibc #elseif os(Windows) import MSVCRT #else import Darwin #endif public let Walsh = BenchmarkInfo( name: "Walsh", runFunction: run_Walsh, tags: [.validation, .algorithm]) func IsPowerOfTwo(_ x: Int) -> Bool { return (x & (x - 1)) == 0 } // Fast Walsh Hadamard Transform func WalshTransform(_ data: inout [Double]) { assert(IsPowerOfTwo(data.count), "Not a power of two") var temp = [Double](repeating: 0, count: data.count) let ret = WalshImpl(&data, &temp, 0, data.count) for i in 0..<data.count { data[i] = ret[i] } } func Scale(_ data: inout [Double], _ scalar : Double) { for i in 0..<data.count { data[i] = data[i] * scalar } } func InverseWalshTransform(_ data: inout [Double]) { WalshTransform(&data) Scale(&data, Double(1)/Double(data.count)) } func WalshImpl(_ data: inout [Double], _ temp: inout [Double], _ start: Int, _ size: Int) -> [Double] { if (size == 1) { return data } let stride = size/2 for i in 0..<stride { temp[start + i] = data[start + i + stride] + data[start + i] temp[start + i + stride] = data[start + i] - data[start + i + stride] } _ = WalshImpl(&temp, &data, start, stride) return WalshImpl(&temp, &data, start + stride, stride) } func checkCorrectness() { let In : [Double] = [1,0,1,0,0,1,1,0] let Out : [Double] = [4,2,0,-2,0,2,0,2] var data : [Double] = In WalshTransform(&data) let mid = data InverseWalshTransform(&data) for i in 0..<In.count { // Check encode. CheckResults(abs(data[i] - In[i]) < 0.0001) // Check decode. CheckResults(abs(mid[i] - Out[i]) < 0.0001) } } @inline(never) public func run_Walsh(_ N: Int) { checkCorrectness() // Generate data. var data2 : [Double] = [] for i in 0..<1024 { data2.append(Double(sin(Float(i)))) } // Transform back and forth. for _ in 1...10*N { WalshTransform(&data2) InverseWalshTransform(&data2) } }
apache-2.0
f0375fe4dc780bd3b614942c1b1d5c7c
25.645161
103
0.59887
3.308411
false
false
false
false
migue1s/habitica-ios
HabitRPG/Interactors/Tasks/TaskRepeatablesSummaryInteractor.swift
2
10462
// // TaskRepeatablesSummaryInteractor.swift // Habitica // // Created by Phillip Thelen on 20/03/2017. // Copyright © 2017 Phillip Thelen. All rights reserved. // import Foundation import ReactiveSwift private enum RepeatType { case never case daily case weekly case monthly case yearly func string(_ everyX: Int) -> String { if self == .never { return NSLocalizedString("never", comment: "") } if everyX == 1 { return self.everyName() } else { return NSLocalizedString("every \(everyX) \(self.repeatName())", comment: "") } } private func everyName() -> String { switch self { case .daily: return NSLocalizedString("daily", comment: "As in 'repeats daily'") case .weekly: return NSLocalizedString("weekly", comment: "As in 'repeats weekly'") case .monthly: return NSLocalizedString("monthly", comment: "As in 'repeats monthly'") case .yearly: return NSLocalizedString("yearly", comment: "As in 'repeats yearly'") default: return "" } } private func repeatName() -> String { switch self { case .daily: return NSLocalizedString("days", comment: "") case .weekly: return NSLocalizedString("weeks", comment: "") case .monthly: return NSLocalizedString("months", comment: "") case .yearly: return NSLocalizedString("years", comment: "") default: return "" } } } struct RepeatableTask { var frequency: String? var everyX = 1 var monday = false var tuesday = false var wednesday = false var thursday = false var friday = false var saturday = false var sunday = false var startDate: Date? var daysOfMonth = Set<NSNumber>() var weeksOfMonth = Set<NSNumber>() init(task: Task) { self.frequency = task.frequency self.everyX = task.everyX?.intValue ?? 1 self.monday = task.monday?.boolValue ?? false self.tuesday = task.tuesday?.boolValue ?? false self.wednesday = task.wednesday?.boolValue ?? false self.thursday = task.thursday?.boolValue ?? false self.friday = task.friday?.boolValue ?? false self.saturday = task.saturday?.boolValue ?? false self.sunday = task.sunday?.boolValue ?? false self.startDate = task.startDate if let daysOfMonth = task.daysOfMonth { self.daysOfMonth = daysOfMonth } if let weeksOfMonth = task.weeksOfMonth { self.weeksOfMonth = weeksOfMonth } } //swiftlint:disable:next function_parameter_count init(frequency: String?, everyX: NSNumber?, monday: NSNumber?, tuesday: NSNumber?, wednesday: NSNumber?, thursday: NSNumber?, friday: NSNumber?, saturday: NSNumber?, sunday: NSNumber?, startDate: Date?, daysOfMonth: Set<NSNumber>?, weeksOfMonth: Set<NSNumber>?) { self.frequency = frequency self.everyX = everyX?.intValue ?? 1 self.monday = monday?.boolValue ?? false self.tuesday = tuesday?.boolValue ?? false self.wednesday = wednesday?.boolValue ?? false self.thursday = thursday?.boolValue ?? false self.friday = friday?.boolValue ?? false self.saturday = saturday?.boolValue ?? false self.sunday = sunday?.boolValue ?? false self.startDate = startDate if let daysOfMonth = daysOfMonth { self.daysOfMonth = daysOfMonth } if let weeksOfMonth = weeksOfMonth { self.weeksOfMonth = weeksOfMonth } } func allWeekdaysInactive() -> Bool { return !monday && !tuesday && !wednesday && !thursday && !friday && !saturday && !sunday } } class TaskRepeatablesSummaryInteractor: NSObject { let dateFormatter: DateFormatter let yearlyFormat: String let monthlyFormat: String override init() { let yearlyTemplate = "ddMMMM" if let yearlyFormat = DateFormatter.dateFormat(fromTemplate: yearlyTemplate, options: 0, locale: NSLocale.current) { self.yearlyFormat = yearlyFormat } else { self.yearlyFormat = "" } let monthlyTemplate = "FEEEE" if let monthlyFormat = DateFormatter.dateFormat(fromTemplate: monthlyTemplate, options: 0, locale: NSLocale.current) { self.monthlyFormat = monthlyFormat } else { self.monthlyFormat = "" } self.dateFormatter = DateFormatter() super.init() } //swiftlint:disable:next function_parameter_count func repeatablesSummary(frequency: String?, everyX: NSNumber?, monday: NSNumber?, tuesday: NSNumber?, wednesday: NSNumber?, thursday: NSNumber?, friday: NSNumber?, saturday: NSNumber?, sunday: NSNumber?, startDate: Date?, daysOfMonth: Set<NSNumber>?, weeksOfMonth: Set<NSNumber>?) -> String { let task = RepeatableTask(frequency: frequency, everyX: everyX, monday: monday, tuesday: tuesday, wednesday: wednesday, thursday: thursday, friday: friday, saturday: saturday, sunday: sunday, startDate: startDate, daysOfMonth: daysOfMonth, weeksOfMonth: weeksOfMonth) return self.repeatablesSummary(task) } func repeatablesSummary(_ task: Task) -> String { return self.repeatablesSummary(RepeatableTask(task: task)) } func repeatablesSummary(_ task: RepeatableTask) -> String { let everyX = task.everyX var repeatType = RepeatType.daily var repeatOnString: String? = nil switch task.frequency ?? "" { case "daily": repeatType = .daily case "weekly": if task.allWeekdaysInactive() { repeatType = .never } else { repeatType = .weekly } repeatOnString = weeklyRepeatOn(task) case "monthly": repeatType = .monthly repeatOnString = monthlyRepeatOn(task) case "yearly": repeatType = .yearly repeatOnString = yearlyRepeatOn(task) default: break } if task.everyX == 0 { repeatType = .never } if let repeatOnString = repeatOnString, repeatType != .never { return NSLocalizedString("Repeats \(repeatType.string(everyX)) on \(repeatOnString)", comment: "") } else { return NSLocalizedString("Repeats \(repeatType.string(everyX))", comment: "") } } private func weeklyRepeatOn(_ task: RepeatableTask) -> String? { if task.allWeekdaysInactive() { return nil } else if task.monday && task.tuesday && task.wednesday && task.thursday && task.friday && task.saturday && task.sunday { return NSLocalizedString("every day", comment: "") } else if task.monday && task.tuesday && task.wednesday && task.thursday && task.friday && !task.saturday && !task.sunday { return NSLocalizedString("weekdays", comment: "") } else if !task.monday && !task.tuesday && !task.wednesday && !task.thursday && !task.friday && task.saturday && task.sunday { return NSLocalizedString("weekends", comment: "") } else { return assembleActiveDaysString(task) } } private func assembleActiveDaysString(_ task: RepeatableTask) -> String { var repeatOnComponents = [String]() if task.monday { repeatOnComponents.append(NSLocalizedString("Monday", comment: "")) } if task.tuesday { repeatOnComponents.append(NSLocalizedString("Tuesday", comment: "")) } if task.wednesday { repeatOnComponents.append(NSLocalizedString("Wednesday", comment: "")) } if task.thursday { repeatOnComponents.append(NSLocalizedString("Thursday", comment: "")) } if task.friday { repeatOnComponents.append(NSLocalizedString("Friday", comment: "")) } if task.saturday { repeatOnComponents.append(NSLocalizedString("Saturday", comment: "")) } if task.sunday { repeatOnComponents.append(NSLocalizedString("Sunday", comment: "")) } return repeatOnComponents.joined(separator: ", ") } private func monthlyRepeatOn(_ task: RepeatableTask) -> String? { if task.daysOfMonth.count > 0 { var days = [String]() for day in task.daysOfMonth { days.append(day.stringValue) } return NSLocalizedString("the \(days.joined(separator: ", "))", comment: "") } if task.weeksOfMonth.count > 0 { if let startDate = task.startDate { self.dateFormatter.dateFormat = monthlyFormat return NSLocalizedString("the \(dateFormatter.string(from: startDate))", comment: "") } } return nil } private func yearlyRepeatOn(_ task: RepeatableTask) -> String? { if let startDate = task.startDate { self.dateFormatter.dateFormat = yearlyFormat return dateFormatter.string(from: startDate) } else { return nil } } }
gpl-3.0
6478ee9f013cc0674aa60d596a5ffe5a
33.524752
126
0.539432
5.212257
false
false
false
false
kaich/CKAlertView
CKAlertView/Classes/Extension/CKCircularProgressAlertView.swift
1
6952
// // CKAlertView+MajorAction.swift // Pods // // Created by mac on 16/10/12. // // import Foundation import DACircularProgress public class CKCircularProgressAlertView : CKAlertView { public var alertTitle = "" { didSet { if let componentMaker = self.componentMaker as? CKAlertViewComponentCircularProgressMaker { componentMaker.alertTitle = alertTitle } } } public var progress :Float = 0 { didSet { if let componentMaker = self.componentMaker as? CKAlertViewComponentCircularProgressMaker { componentMaker.progress = progress } } } public var progressMessage = "" { didSet { if let componentMaker = self.componentMaker as? CKAlertViewComponentCircularProgressMaker { componentMaker.progressMessage = progressMessage } } } public var alertMessage = "" { didSet { if let componentMaker = self.componentMaker as? CKAlertViewComponentCircularProgressMaker { componentMaker.alertMessage = alertMessage } } } public var alertDetailMessage = "" { didSet { if let componentMaker = self.componentMaker as? CKAlertViewComponentCircularProgressMaker { componentMaker.alertDetailMessage = alertDetailMessage } } } public var cancelButtonTitle = "" { didSet { if let componentMaker = self.componentMaker as? CKAlertViewComponentCircularProgressMaker { componentMaker.cancelButtonTitle = cancelButtonTitle } } } /// 显示圆形进度条的弹出框 /// /// - parameter alertTitle: 标题 /// - parameter progress: 进度 /// - parameter alertMessage: 内容 /// - parameter detailMessage: 详细内容 /// - parameter cancelButtonTitle: 取消按钮文字 /// - parameter completeBlock: 完成回调 public init(title alertTitle :String, progress :Float, progressMessage :String? , message alertMessage :String?, detailMessage :String?, cancelButtonTitle :String, completeBlock :(((Int) -> Void))? = nil) { super.init(nibName: nil, bundle: nil) dismissCompleteBlock = completeBlock let componentMaker = CKAlertViewComponentCircularProgressMaker() componentMaker.alertView = self componentMaker.alertTitle = alertTitle componentMaker.cancelButtonTitle = cancelButtonTitle componentMaker.otherButtonTitles = nil componentMaker.alertMessage = alertMessage componentMaker.alertDetailMessage = detailMessage componentMaker.progress = progress componentMaker.progressMessage = progressMessage installComponentMaker(maker: componentMaker) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func show() { super.show() } } class CKAlertViewCircularProgressBodyView : CKAlertViewBodyView { let progressView = DACircularProgressView() let lblMessage = UILabel() let lblDetailMessage = UILabel() let lblProgressMessage = UILabel() var progress :Float = 0.0 { didSet { progressView.setProgress(CGFloat(progress), animated: true) } } var progressMessage :String? { didSet { lblProgressMessage.text = progressMessage } } var alertMessage :String? { didSet { lblMessage.text = alertMessage } } var alertDetailMessage :String? { didSet { lblDetailMessage.text = alertDetailMessage } } override func makeLayout() { progressView.roundedCorners = 1 progressView.thicknessRatio = 0.1 progressView.trackTintColor = HexColor(0xe6e6e6, 1) progressView.progressTintColor = HexColor(0x39b54a, 1) addSubview(progressView) progressView.snp.makeConstraints { (make) in make.height.width.equalTo(100) make.top.equalTo(self).offset(10) make.centerX.equalTo(self) } lblProgressMessage.font = UIFont.systemFont(ofSize: 16) lblProgressMessage.textColor = UIColor.black addSubview(lblProgressMessage) lblProgressMessage.snp.makeConstraints { (make) in make.centerX.centerY.equalTo(progressView) } lblMessage.textColor = HexColor(0x333333, 1) lblMessage.textAlignment = .center lblMessage.font = UIFont.systemFont(ofSize: 13) addSubview(lblMessage) lblMessage.snp.makeConstraints { (make) in make.top.equalTo(progressView.snp.bottom).offset(25) make.left.equalTo(self).offset(20) make.right.equalTo(self).offset(-20) } lblDetailMessage.textColor = HexColor(0x999999, 1) lblDetailMessage.textAlignment = .center lblDetailMessage.font = UIFont.systemFont(ofSize: 11) addSubview(lblDetailMessage) lblDetailMessage.snp.makeConstraints { (make) in make.left.right.equalTo(lblMessage) make.top.equalTo(lblMessage.snp.bottom).offset(10) make.bottom.equalTo(self).offset(-30) } } } class CKAlertViewComponentCircularProgressMaker :CKAlertViewComponentMaker { var progress :Float = 0.0 { didSet { if let circularBodyView = bodyView as? CKAlertViewCircularProgressBodyView { circularBodyView.progress = progress } } } var progressMessage :String? { didSet { if let circularBodyView = bodyView as? CKAlertViewCircularProgressBodyView { circularBodyView.progressMessage = progressMessage } } } var alertMessage :String? { didSet { if let circularBodyView = bodyView as? CKAlertViewCircularProgressBodyView { circularBodyView.alertMessage = alertMessage } } } var alertDetailMessage :String? { didSet { if let circularBodyView = bodyView as? CKAlertViewCircularProgressBodyView { circularBodyView.alertDetailMessage = alertDetailMessage } } } override func makeHeader() -> CKAlertViewComponent? { let headerView = CKAlertViewXCloseHeaderView() headerView.alertTitle = alertTitle headerView.delegate = delegate return headerView } override func makeBody() -> CKAlertViewComponent? { let bodyView = CKAlertViewCircularProgressBodyView() return bodyView } }
mit
a8e6659e033059c8beace5bbd9ca9f14
30.318182
213
0.618287
5.176559
false
false
false
false
xedin/swift
stdlib/public/core/Hasher.swift
7
15028
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Defines the Hasher struct, representing Swift's standard hash function. // //===----------------------------------------------------------------------===// import SwiftShims @inline(__always) internal func _loadPartialUnalignedUInt64LE( _ p: UnsafeRawPointer, byteCount: Int ) -> UInt64 { var result: UInt64 = 0 switch byteCount { case 7: result |= UInt64(p.load(fromByteOffset: 6, as: UInt8.self)) &<< 48 fallthrough case 6: result |= UInt64(p.load(fromByteOffset: 5, as: UInt8.self)) &<< 40 fallthrough case 5: result |= UInt64(p.load(fromByteOffset: 4, as: UInt8.self)) &<< 32 fallthrough case 4: result |= UInt64(p.load(fromByteOffset: 3, as: UInt8.self)) &<< 24 fallthrough case 3: result |= UInt64(p.load(fromByteOffset: 2, as: UInt8.self)) &<< 16 fallthrough case 2: result |= UInt64(p.load(fromByteOffset: 1, as: UInt8.self)) &<< 8 fallthrough case 1: result |= UInt64(p.load(fromByteOffset: 0, as: UInt8.self)) fallthrough case 0: return result default: _internalInvariantFailure() } } extension Hasher { /// This is a buffer for segmenting arbitrary data into 8-byte chunks. Buffer /// storage is represented by a single 64-bit value in the format used by the /// finalization step of SipHash. (The least significant 56 bits hold the /// trailing bytes, while the most significant 8 bits hold the count of bytes /// appended so far, modulo 256. The count of bytes currently stored in the /// buffer is in the lower three bits of the byte count.) // FIXME: Remove @usableFromInline and @frozen once Hasher is resilient. // rdar://problem/38549901 @usableFromInline @frozen internal struct _TailBuffer { // msb lsb // +---------+-------+-------+-------+-------+-------+-------+-------+ // |byteCount| tail (<= 56 bits) | // +---------+-------+-------+-------+-------+-------+-------+-------+ internal var value: UInt64 @inline(__always) internal init() { self.value = 0 } @inline(__always) internal init(tail: UInt64, byteCount: UInt64) { // byteCount can be any value, but we only keep the lower 8 bits. (The // lower three bits specify the count of bytes stored in this buffer.) // FIXME: This should be a single expression, but it causes exponential // behavior in the expression type checker <rdar://problem/42672946>. let shiftedByteCount: UInt64 = ((byteCount & 7) << 3) let mask: UInt64 = (1 << shiftedByteCount - 1) _internalInvariant(tail & ~mask == 0) self.value = (byteCount &<< 56 | tail) } @inline(__always) internal init(tail: UInt64, byteCount: Int) { self.init(tail: tail, byteCount: UInt64(truncatingIfNeeded: byteCount)) } internal var tail: UInt64 { @inline(__always) get { return value & ~(0xFF &<< 56) } } internal var byteCount: UInt64 { @inline(__always) get { return value &>> 56 } } @inline(__always) internal mutating func append(_ bytes: UInt64) -> UInt64 { let c = byteCount & 7 if c == 0 { value = value &+ (8 &<< 56) return bytes } let shift = c &<< 3 let chunk = tail | (bytes &<< shift) value = (((value &>> 56) &+ 8) &<< 56) | (bytes &>> (64 - shift)) return chunk } @inline(__always) internal mutating func append(_ bytes: UInt64, count: UInt64) -> UInt64? { _internalInvariant(count >= 0 && count < 8) _internalInvariant(bytes & ~((1 &<< (count &<< 3)) &- 1) == 0) let c = byteCount & 7 let shift = c &<< 3 if c + count < 8 { value = (value | (bytes &<< shift)) &+ (count &<< 56) return nil } let chunk = tail | (bytes &<< shift) value = ((value &>> 56) &+ count) &<< 56 if c + count > 8 { value |= bytes &>> (64 - shift) } return chunk } } } extension Hasher { // FIXME: Remove @usableFromInline and @frozen once Hasher is resilient. // rdar://problem/38549901 @usableFromInline @frozen internal struct _Core { private var _buffer: _TailBuffer private var _state: Hasher._State @inline(__always) internal init(state: Hasher._State) { self._buffer = _TailBuffer() self._state = state } @inline(__always) internal init() { self.init(state: _State()) } @inline(__always) internal init(seed: Int) { self.init(state: _State(seed: seed)) } @inline(__always) internal mutating func combine(_ value: UInt) { #if arch(i386) || arch(arm) combine(UInt32(truncatingIfNeeded: value)) #else combine(UInt64(truncatingIfNeeded: value)) #endif } @inline(__always) internal mutating func combine(_ value: UInt64) { _state.compress(_buffer.append(value)) } @inline(__always) internal mutating func combine(_ value: UInt32) { let value = UInt64(truncatingIfNeeded: value) if let chunk = _buffer.append(value, count: 4) { _state.compress(chunk) } } @inline(__always) internal mutating func combine(_ value: UInt16) { let value = UInt64(truncatingIfNeeded: value) if let chunk = _buffer.append(value, count: 2) { _state.compress(chunk) } } @inline(__always) internal mutating func combine(_ value: UInt8) { let value = UInt64(truncatingIfNeeded: value) if let chunk = _buffer.append(value, count: 1) { _state.compress(chunk) } } @inline(__always) internal mutating func combine(bytes: UInt64, count: Int) { _internalInvariant(count >= 0 && count < 8) let count = UInt64(truncatingIfNeeded: count) if let chunk = _buffer.append(bytes, count: count) { _state.compress(chunk) } } @inline(__always) internal mutating func combine(bytes: UnsafeRawBufferPointer) { var remaining = bytes.count guard remaining > 0 else { return } var data = bytes.baseAddress! // Load first unaligned partial word of data do { let start = UInt(bitPattern: data) let end = _roundUp(start, toAlignment: MemoryLayout<UInt64>.alignment) let c = min(remaining, Int(end - start)) if c > 0 { let chunk = _loadPartialUnalignedUInt64LE(data, byteCount: c) combine(bytes: chunk, count: c) data += c remaining -= c } } _internalInvariant( remaining == 0 || Int(bitPattern: data) & (MemoryLayout<UInt64>.alignment - 1) == 0) // Load as many aligned words as there are in the input buffer while remaining >= MemoryLayout<UInt64>.size { combine(UInt64(littleEndian: data.load(as: UInt64.self))) data += MemoryLayout<UInt64>.size remaining -= MemoryLayout<UInt64>.size } // Load last partial word of data _internalInvariant(remaining >= 0 && remaining < 8) if remaining > 0 { let chunk = _loadPartialUnalignedUInt64LE(data, byteCount: remaining) combine(bytes: chunk, count: remaining) } } @inline(__always) internal mutating func finalize() -> UInt64 { return _state.finalize(tailAndByteCount: _buffer.value) } } } /// The universal hash function used by `Set` and `Dictionary`. /// /// `Hasher` can be used to map an arbitrary sequence of bytes to an integer /// hash value. You can feed data to the hasher using a series of calls to /// mutating `combine` methods. When you've finished feeding the hasher, the /// hash value can be retrieved by calling `finalize()`: /// /// var hasher = Hasher() /// hasher.combine(23) /// hasher.combine("Hello") /// let hashValue = hasher.finalize() /// /// Within the execution of a Swift program, `Hasher` guarantees that finalizing /// it will always produce the same hash value as long as it is fed the exact /// same sequence of bytes. However, the underlying hash algorithm is designed /// to exhibit avalanche effects: slight changes to the seed or the input byte /// sequence will typically produce drastic changes in the generated hash value. /// /// - Note: Do not save or otherwise reuse hash values across executions of your /// program. `Hasher` is usually randomly seeded, which means it will return /// different values on every new execution of your program. The hash /// algorithm implemented by `Hasher` may itself change between any two /// versions of the standard library. @frozen // FIXME: Should be resilient (rdar://problem/38549901) public struct Hasher { internal var _core: _Core /// Creates a new hasher. /// /// The hasher uses a per-execution seed value that is set during process /// startup, usually from a high-quality random source. @_effects(releasenone) public init() { self._core = _Core() } /// Initialize a new hasher using the specified seed value. /// The provided seed is mixed in with the global execution seed. @usableFromInline @_effects(releasenone) internal init(_seed: Int) { self._core = _Core(seed: _seed) } /// Initialize a new hasher using the specified seed value. @usableFromInline // @testable @_effects(releasenone) internal init(_rawSeed: (UInt64, UInt64)) { self._core = _Core(state: _State(rawSeed: _rawSeed)) } /// Indicates whether we're running in an environment where hashing needs to /// be deterministic. If this is true, the hash seed is not random, and hash /// tables do not apply per-instance perturbation that is not repeatable. /// This is not recommended for production use, but it is useful in certain /// test environments where randomization may lead to unwanted nondeterminism /// of test results. @inlinable internal static var _isDeterministic: Bool { @inline(__always) get { return _swift_stdlib_Hashing_parameters.deterministic } } /// The 128-bit hash seed used to initialize the hasher state. Initialized /// once during process startup. @inlinable // @testable internal static var _executionSeed: (UInt64, UInt64) { @inline(__always) get { // The seed itself is defined in C++ code so that it is initialized during // static construction. Almost every Swift program uses hash tables, so // initializing the seed during the startup seems to be the right // trade-off. return ( _swift_stdlib_Hashing_parameters.seed0, _swift_stdlib_Hashing_parameters.seed1) } } /// Adds the given value to this hasher, mixing its essential parts into the /// hasher state. /// /// - Parameter value: A value to add to the hasher. @inlinable @inline(__always) public mutating func combine<H: Hashable>(_ value: H) { value.hash(into: &self) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt64) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt32) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt16) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt8) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(bytes value: UInt64, count: Int) { _core.combine(bytes: value, count: count) } /// Adds the contents of the given buffer to this hasher, mixing it into the /// hasher state. /// /// - Parameter bytes: A raw memory buffer. @_effects(releasenone) public mutating func combine(bytes: UnsafeRawBufferPointer) { _core.combine(bytes: bytes) } /// Finalize the hasher state and return the hash value. /// Finalizing invalidates the hasher; additional bits cannot be combined /// into it, and it cannot be finalized again. @_effects(releasenone) @usableFromInline internal mutating func _finalize() -> Int { return Int(truncatingIfNeeded: _core.finalize()) } /// Finalizes the hasher state and returns the hash value. /// /// Finalizing consumes the hasher: it is illegal to finalize a hasher you /// don't own, or to perform operations on a finalized hasher. (These may /// become compile-time errors in the future.) /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. /// /// - Returns: The hash value calculated by the hasher. @_effects(releasenone) public __consuming func finalize() -> Int { var core = _core return Int(truncatingIfNeeded: core.finalize()) } @_effects(readnone) @usableFromInline internal static func _hash(seed: Int, _ value: UInt64) -> Int { var state = _State(seed: seed) state.compress(value) let tbc = _TailBuffer(tail: 0, byteCount: 8) return Int(truncatingIfNeeded: state.finalize(tailAndByteCount: tbc.value)) } @_effects(readnone) @usableFromInline internal static func _hash(seed: Int, _ value: UInt) -> Int { var state = _State(seed: seed) #if arch(i386) || arch(arm) _internalInvariant(UInt.bitWidth < UInt64.bitWidth) let tbc = _TailBuffer( tail: UInt64(truncatingIfNeeded: value), byteCount: UInt.bitWidth &>> 3) #else _internalInvariant(UInt.bitWidth == UInt64.bitWidth) state.compress(UInt64(truncatingIfNeeded: value)) let tbc = _TailBuffer(tail: 0, byteCount: 8) #endif return Int(truncatingIfNeeded: state.finalize(tailAndByteCount: tbc.value)) } @_effects(readnone) @usableFromInline internal static func _hash( seed: Int, bytes value: UInt64, count: Int) -> Int { _internalInvariant(count >= 0 && count < 8) var state = _State(seed: seed) let tbc = _TailBuffer(tail: value, byteCount: count) return Int(truncatingIfNeeded: state.finalize(tailAndByteCount: tbc.value)) } @_effects(readnone) @usableFromInline internal static func _hash( seed: Int, bytes: UnsafeRawBufferPointer) -> Int { var core = _Core(seed: seed) core.combine(bytes: bytes) return Int(truncatingIfNeeded: core.finalize()) } }
apache-2.0
5dd23abf1842973a35456a269f6584b5
31.669565
80
0.63222
4.152528
false
false
false
false
andr3a88/TryNetworkLayer
TryNetworkLayer/Controllers/Users/UsersCoordinator.swift
1
1101
// // UsersCoordinator.swift // TryNetworkLayer // // Created by Andrea Stevanato on 13/03/2020. // Copyright © 2020 Andrea Stevanato. All rights reserved. // import UIKit final class UsersCoordinator: Coordinator { var window: UIWindow var navigationController: UINavigationController! var userDetailCoordinator: UserDetailCoordinator? init(window: UIWindow) { self.window = window } func start() { let usersViewController = Storyboard.main.instantiate(UsersViewController.self) usersViewController.viewModel = UsersViewModel() usersViewController.viewModel.coordinatorDelegate = self self.navigationController = UINavigationController(rootViewController: usersViewController) self.window.rootViewController = navigationController } } extension UsersCoordinator: UsersViewModelCoordinatorDelegate { func usersViewModelPresent(user: GHUser) { userDetailCoordinator = UserDetailCoordinator(navigationController: navigationController, user: user) userDetailCoordinator?.start() } }
mit
e07e18b44832933b9fa156deef29d75b
28.72973
109
0.741818
5.5
false
false
false
false
LouZhuang/Test
hard/hard/AppDelegate.swift
1
4581
// // AppDelegate.swift // hard // // Created by huanglch on 2017/3/9. // Copyright © 2017年 huanglch. 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: "hard") 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
8f3554962e77dafa8c37a225a42a68bc
48.225806
285
0.685234
5.831847
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/chance_btc_wallet/viewcontrollers/public/RootNavigationController.swift
1
1621
// // RootNavigationController.swift // Chance_wallet // // Created by Chance on 15/11/16. // Copyright © 2015年 Chance. All rights reserved. // import UIKit class RootNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() self.setupNavigationBar() } /// 配置导航栏背景 func setupNavigationBar() { let bgImg = UIImage(named: "navbar_bg")?.resizableImage( withCapInsets: UIEdgeInsets.zero, resizingMode: UIImageResizingMode.stretch) self.navigationBar.setBackgroundImage(bgImg, for: UIBarMetrics.default) self.navigationBar.isTranslucent = false //文字颜色 self.navigationBar.tintColor = UIColor.white self.navigationBar.titleTextAttributes = [ NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont(name: "Menlo-Bold", size: 17)! ] UINavigationBar.appearance().tintColor = UIColor.white self.navigationBar.shadowImage = UIImage() self.navigationBar.backgroundColor = UIColor.clear } //MARK: ios7状态栏修改 override var preferredStatusBarStyle : UIStatusBarStyle { return UIStatusBarStyle.lightContent } override var prefersStatusBarHidden : Bool { return false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
cb7a7ac9dc8830af82b83a02e1fcd7ec
27.321429
77
0.634931
5.60424
false
false
false
false
aiqiuqiu/Tuan
Tuan/Deal/HMRegionsViewController.swift
2
3550
// // HMRegionsViewController.swift // Tuan // // Created by nero on 15/5/16. // Copyright (c) 2015年 nero. All rights reserved. // import UIKit class HMRegionsViewController: UIViewController { lazy var menu:HMDropdownMenu = { // 顶部的view var topView = self.view.subviews.first! // 创建菜单 var menu = HMDropdownMenu() menu.delegate = self self.view.addSubview(menu) // menu的ALEdgeTop == topView的ALEdgeBottom menu.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Bottom, ofView: topView) // 除开顶部,其他方向距离父控件的间距都为0 menu.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: ALEdge.Top) return menu }() @IBAction func changeCity() { // changeCityClosuer?() let cityesVC = HMCitiesViewController() cityesVC.view = NSBundle.mainBundle().loadNibNamed("HMCitiesViewController", owner: cityesVC, options: nil).last as! UIView cityesVC.modalPresentationStyle = UIModalPresentationStyle.FormSheet presentViewController(cityesVC, animated: true) { () -> Void in } } var changeCityClosuer:(Void ->Void)? override func viewDidLoad() { super.viewDidLoad() self.preferredContentSize = CGSizeMake(400, 480); } var regions:Array<HMRegion>! { willSet { menu.items = newValue } } /** 当前选中的区域 */ var selectedRegion:HMRegion! { willSet { if newValue == nil {return } let itsmNSArray = NSArray(array: menu.items) menu.selectMain(Int32(itsmNSArray.indexOfObject(newValue))) } } /** 当前选中的子区域名称 */ var selectedSubRegionName:NSString! { willSet { if newValue == nil {return } let itsmNSArray = NSArray(array: menu.items) // 这个200 我瞎写的 为了屏蔽找不到索引越界的情况 if itsmNSArray.indexOfObject(newValue) <= 200 { menu.selectSub(Int32(itsmNSArray.indexOfObject(newValue))) } } } } extension HMRegionsViewController: HMDropdownMenuDelegate { func dropdownMenu(dropdownMenu: HMDropdownMenu!, didSelectSub subRow: Int32, ofMain mainRow: Int32) { // 发出通知,选中了某个分类 var userinfo = [String:AnyObject]() let region = dropdownMenu.items[Int(mainRow)] as! HMRegion userinfo[HMRegionNotification.HMSelectedRegion] = region userinfo[HMRegionNotification.HMSelectedSubRegionName] = region.subregions[Int(subRow)] HMNotificationCenter.postNotificationName(HMRegionNotification.HMRegionDidSelectNotification, object: nil, userInfo: userinfo) } func dropdownMenu(dropdownMenu: HMDropdownMenu!, didSelectMain mainRow: Int32) { let region = dropdownMenu.items[Int(mainRow)] as! HMRegion if region.subregions != nil { if selectedRegion == regions { // 选中右边的子区域 let temp = selectedSubRegionName if temp == nil { return } selectedSubRegionName = temp } }else{ HMNotificationCenter.postNotificationName(HMRegionNotification.HMRegionDidSelectNotification, object: nil, userInfo: [HMRegionNotification.HMSelectedRegion:region]) } } }
mit
c5f5692df51c3448db2964b2d2537936
32.455446
180
0.622854
4.504
false
false
false
false
natecook1000/swift
test/SILGen/reabstract_lvalue.swift
3
2893
// RUN: %target-swift-emit-silgen -module-name reabstract_lvalue -enable-sil-ownership %s | %FileCheck %s struct MyMetatypeIsThin {} // CHECK-LABEL: sil hidden @$S17reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T> (@inout T) -> () func consumeGenericInOut<T>(_ x: inout T) {} // CHECK-LABEL: sil hidden @$S17reabstract_lvalue9transformySdSiF : $@convention(thin) (Int) -> Double func transform(_ i: Int) -> Double { return Double(i) } // CHECK-LABEL: sil hidden @$S17reabstract_lvalue0A13FunctionInOutyyF : $@convention(thin) () -> () func reabstractFunctionInOut() { // CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_guaranteed (Int) -> Double } // CHECK: [[PB:%.*]] = project_box [[BOX]] // CHECK: [[ARG:%.*]] = function_ref @$S17reabstract_lvalue9transformySdSiF // CHECK: [[THICK_ARG:%.*]] = thin_to_thick_function [[ARG]] // CHECK: store [[THICK_ARG:%.*]] to [init] [[PB]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*@callee_guaranteed (Int) -> Double // CHECK: [[ABSTRACTED_BOX:%.*]] = alloc_stack $@callee_guaranteed (@in_guaranteed Int) -> @out Double // CHECK: [[THICK_ARG:%.*]] = load [copy] [[WRITE]] // CHECK: [[THUNK1:%.*]] = function_ref @$SSiSdIegyd_SiSdIegnr_TR // CHECK: [[ABSTRACTED_ARG:%.*]] = partial_apply [callee_guaranteed] [[THUNK1]]([[THICK_ARG]]) // CHECK: store [[ABSTRACTED_ARG]] to [init] [[ABSTRACTED_BOX]] // CHECK: [[FUNC:%.*]] = function_ref @$S17reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F // CHECK: apply [[FUNC]]<(Int) -> Double>([[ABSTRACTED_BOX]]) // CHECK: [[NEW_ABSTRACTED_ARG:%.*]] = load [take] [[ABSTRACTED_BOX]] // CHECK: [[THUNK2:%.*]] = function_ref @$SSiSdIegnr_SiSdIegyd_TR // CHECK: [[NEW_ARG:%.*]] = partial_apply [callee_guaranteed] [[THUNK2]]([[NEW_ABSTRACTED_ARG]]) var minimallyAbstracted = transform consumeGenericInOut(&minimallyAbstracted) } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SSiSdIegyd_SiSdIegnr_TR : $@convention(thin) (@in_guaranteed Int, @guaranteed @callee_guaranteed (Int) -> Double) -> @out Double // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SSiSdIegnr_SiSdIegyd_TR : $@convention(thin) (Int, @guaranteed @callee_guaranteed (@in_guaranteed Int) -> @out Double) -> Double // CHECK-LABEL: sil hidden @$S17reabstract_lvalue0A13MetatypeInOutyyF : $@convention(thin) () -> () func reabstractMetatypeInOut() { var thinMetatype = MyMetatypeIsThin.self // CHECK: [[BOX:%.*]] = alloc_stack $@thick MyMetatypeIsThin.Type // CHECK: [[THICK:%.*]] = metatype $@thick MyMetatypeIsThin.Type // CHECK: store [[THICK]] to [trivial] [[BOX]] // CHECK: [[FUNC:%.*]] = function_ref @$S17reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F // CHECK: apply [[FUNC]]<MyMetatypeIsThin.Type>([[BOX]]) consumeGenericInOut(&thinMetatype) }
apache-2.0
205642e7526212b4780c36f5e0efc63b
59.270833
208
0.66298
3.379673
false
false
false
false
kstaring/swift
stdlib/public/SDK/Foundation/DateComponents.swift
4
16295
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module /** `DateComponents` encapsulates the components of a date in an extendable, structured manner. It is used to specify a date by providing the temporal components that make up a date and time in a particular calendar: hour, minutes, seconds, day, month, year, and so on. It can also be used to specify a duration of time, for example, 5 hours and 16 minutes. A `DateComponents` is not required to define all the component fields. When a new instance of `DateComponents` is created, the date components are set to `nil`. */ public struct DateComponents : ReferenceConvertible, Hashable, Equatable, _MutableBoxing { public typealias ReferenceType = NSDateComponents internal var _handle: _MutableHandle<NSDateComponents> /// Initialize a `DateComponents`, optionally specifying values for its fields. public init(calendar: Calendar? = nil, timeZone: TimeZone? = nil, era: Int? = nil, year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil, nanosecond: Int? = nil, weekday: Int? = nil, weekdayOrdinal: Int? = nil, quarter: Int? = nil, weekOfMonth: Int? = nil, weekOfYear: Int? = nil, yearForWeekOfYear: Int? = nil) { _handle = _MutableHandle(adoptingReference: NSDateComponents()) if let _calendar = calendar { self.calendar = _calendar } if let _timeZone = timeZone { self.timeZone = _timeZone } if let _era = era { self.era = _era } if let _year = year { self.year = _year } if let _month = month { self.month = _month } if let _day = day { self.day = _day } if let _hour = hour { self.hour = _hour } if let _minute = minute { self.minute = _minute } if let _second = second { self.second = _second } if let _nanosecond = nanosecond { self.nanosecond = _nanosecond } if let _weekday = weekday { self.weekday = _weekday } if let _weekdayOrdinal = weekdayOrdinal { self.weekdayOrdinal = _weekdayOrdinal } if let _quarter = quarter { self.quarter = _quarter } if let _weekOfMonth = weekOfMonth { self.weekOfMonth = _weekOfMonth } if let _weekOfYear = weekOfYear { self.weekOfYear = _weekOfYear } if let _yearForWeekOfYear = yearForWeekOfYear { self.yearForWeekOfYear = _yearForWeekOfYear } } // MARK: - Properties /// Translate from the NSDateComponentUndefined value into a proper Swift optional private func _getter(_ x : Int) -> Int? { return x == NSDateComponentUndefined ? nil : x } /// Translate from the proper Swift optional value into an NSDateComponentUndefined private func _setter(_ x : Int?) -> Int { if let xx = x { return xx } else { return NSDateComponentUndefined } } /// The `Calendar` used to interpret the other values in this structure. /// /// - note: API which uses `DateComponents` may have different behavior if this value is `nil`. For example, assuming the current calendar or ignoring certain values. public var calendar: Calendar? { get { return _handle.map { $0.calendar } } set { _applyMutation { $0.calendar = newValue } } } /// A time zone. /// - note: This value is interpreted in the context of the calendar in which it is used. public var timeZone: TimeZone? { get { return _handle.map { $0.timeZone } } set { _applyMutation { $0.timeZone = newValue } } } /// An era or count of eras. /// - note: This value is interpreted in the context of the calendar in which it is used. public var era: Int? { get { return _handle.map { _getter($0.era) } } set { _applyMutation { $0.era = _setter(newValue) } } } /// A year or count of years. /// - note: This value is interpreted in the context of the calendar in which it is used. public var year: Int? { get { return _handle.map { _getter($0.year) } } set { _applyMutation { $0.year = _setter(newValue) } } } /// A month or count of months. /// - note: This value is interpreted in the context of the calendar in which it is used. public var month: Int? { get { return _handle.map { _getter($0.month) } } set { _applyMutation { $0.month = _setter(newValue) } } } /// A day or count of days. /// - note: This value is interpreted in the context of the calendar in which it is used. public var day: Int? { get { return _handle.map { _getter($0.day) } } set { _applyMutation { $0.day = _setter(newValue) } } } /// An hour or count of hours. /// - note: This value is interpreted in the context of the calendar in which it is used. public var hour: Int? { get { return _handle.map { _getter($0.hour) } } set { _applyMutation { $0.hour = _setter(newValue) } } } /// A minute or count of minutes. /// - note: This value is interpreted in the context of the calendar in which it is used. public var minute: Int? { get { return _handle.map { _getter($0.minute) } } set { _applyMutation { $0.minute = _setter(newValue) } } } /// A second or count of seconds. /// - note: This value is interpreted in the context of the calendar in which it is used. public var second: Int? { get { return _handle.map { _getter($0.second) } } set { _applyMutation { $0.second = _setter(newValue) } } } /// A nanosecond or count of nanoseconds. /// - note: This value is interpreted in the context of the calendar in which it is used. public var nanosecond: Int? { get { return _handle.map { _getter($0.nanosecond) } } set { _applyMutation { $0.nanosecond = _setter(newValue) } } } /// A weekday or count of weekdays. /// - note: This value is interpreted in the context of the calendar in which it is used. public var weekday: Int? { get { return _handle.map { _getter($0.weekday) } } set { _applyMutation { $0.weekday = _setter(newValue) } } } /// A weekday ordinal or count of weekday ordinals. /// Weekday ordinal units represent the position of the weekday within the next larger calendar unit, such as the month. For example, 2 is the weekday ordinal unit for the second Friday of the month./// /// - note: This value is interpreted in the context of the calendar in which it is used. public var weekdayOrdinal: Int? { get { return _handle.map { _getter($0.weekdayOrdinal) } } set { _applyMutation { $0.weekdayOrdinal = _setter(newValue) } } } /// A quarter or count of quarters. /// - note: This value is interpreted in the context of the calendar in which it is used. public var quarter: Int? { get { return _handle.map { _getter($0.quarter) } } set { _applyMutation { $0.quarter = _setter(newValue) } } } /// A week of the month or a count of weeks of the month. /// - note: This value is interpreted in the context of the calendar in which it is used. public var weekOfMonth: Int? { get { return _handle.map { _getter($0.weekOfMonth) } } set { _applyMutation { $0.weekOfMonth = _setter(newValue) } } } /// A week of the year or count of the weeks of the year. /// - note: This value is interpreted in the context of the calendar in which it is used. public var weekOfYear: Int? { get { return _handle.map { _getter($0.weekOfYear) } } set { _applyMutation { $0.weekOfYear = _setter(newValue) } } } /// The ISO 8601 week-numbering year of the receiver. /// /// The Gregorian calendar defines a week to have 7 days, and a year to have 356 days, or 366 in a leap year. However, neither 356 or 366 divide evenly into a 7 day week, so it is often the case that the last week of a year ends on a day in the next year, and the first week of a year begins in the preceding year. To reconcile this, ISO 8601 defines a week-numbering year, consisting of either 52 or 53 full weeks (364 or 371 days), such that the first week of a year is designated to be the week containing the first Thursday of the year. /// /// You can use the yearForWeekOfYear property with the weekOfYear and weekday properties to get the date corresponding to a particular weekday of a given week of a year. For example, the 6th day of the 53rd week of the year 2005 (ISO 2005-W53-6) corresponds to Sat 1 January 2005 on the Gregorian calendar. /// - note: This value is interpreted in the context of the calendar in which it is used. public var yearForWeekOfYear: Int? { get { return _handle.map { _getter($0.yearForWeekOfYear) } } set { _applyMutation { $0.yearForWeekOfYear = _setter(newValue) } } } /// Set to true if these components represent a leap month. public var isLeapMonth: Bool? { get { return _handle.map { $0.isLeapMonth } } set { _applyMutation { // Technically, the underlying class does not support setting isLeapMonth to nil, but it could - so we leave the API consistent. if let b = newValue { $0.isLeapMonth = b } else { $0.isLeapMonth = false } } } } /// Returns a `Date` calculated from the current components using the `calendar` property. public var date: Date? { if let d = _handle.map({$0.date}) { return d as Date } else { return nil } } // MARK: - Generic Setter/Getters /// Set the value of one of the properties, using an enumeration value instead of a property name. /// /// The calendar and timeZone and isLeapMonth properties cannot be set by this method. @available(OSX 10.9, iOS 8.0, *) public mutating func setValue(_ value: Int?, for component: Calendar.Component) { _applyMutation { $0.setValue(_setter(value), forComponent: Calendar._toCalendarUnit([component])) } } /// Returns the value of one of the properties, using an enumeration value instead of a property name. /// /// The calendar and timeZone and isLeapMonth property values cannot be retrieved by this method. @available(OSX 10.9, iOS 8.0, *) public func value(for component: Calendar.Component) -> Int? { return _handle.map { $0.value(forComponent: Calendar._toCalendarUnit([component])) } } // MARK: - /// Returns true if the combination of properties which have been set in the receiver is a date which exists in the `calendar` property. /// /// This method is not appropriate for use on `DateComponents` values which are specifying relative quantities of calendar components. /// /// Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap. /// /// If the time zone property is set in the `DateComponents`, it is used. /// /// The calendar property must be set, or the result is always `false`. @available(OSX 10.9, iOS 8.0, *) public var isValidDate: Bool { return _handle.map { $0.isValidDate } } /// Returns true if the combination of properties which have been set in the receiver is a date which exists in the specified `Calendar`. /// /// This method is not appropriate for use on `DateComponents` values which are specifying relative quantities of calendar components. /// /// Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap. /// /// If the time zone property is set in the `DateComponents`, it is used. @available(OSX 10.9, iOS 8.0, *) public func isValidDate(in calendar: Calendar) -> Bool { return _handle.map { $0.isValidDate(in: calendar) } } // MARK: - public var hashValue : Int { return _handle.map { $0.hash } } // MARK: - Bridging Helpers fileprivate init(reference: NSDateComponents) { _handle = _MutableHandle(reference: reference) } public static func ==(lhs : DateComponents, rhs: DateComponents) -> Bool { // Don't copy references here; no one should be storing anything return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference()) } } extension DateComponents : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { public var description: String { return self.customMirror.children.reduce("") { $0.appending("\($1.label ?? ""): \($1.value) ") } } public var debugDescription: String { return self.description } public var customMirror: Mirror { var c: [(label: String?, value: Any)] = [] if let r = calendar { c.append((label: "calendar", value: r)) } if let r = timeZone { c.append((label: "timeZone", value: r)) } if let r = era { c.append((label: "era", value: r)) } if let r = year { c.append((label: "year", value: r)) } if let r = month { c.append((label: "month", value: r)) } if let r = day { c.append((label: "day", value: r)) } if let r = hour { c.append((label: "hour", value: r)) } if let r = minute { c.append((label: "minute", value: r)) } if let r = second { c.append((label: "second", value: r)) } if let r = nanosecond { c.append((label: "nanosecond", value: r)) } if let r = weekday { c.append((label: "weekday", value: r)) } if let r = weekdayOrdinal { c.append((label: "weekdayOrdinal", value: r)) } if let r = quarter { c.append((label: "quarter", value: r)) } if let r = weekOfMonth { c.append((label: "weekOfMonth", value: r)) } if let r = weekOfYear { c.append((label: "weekOfYear", value: r)) } if let r = yearForWeekOfYear { c.append((label: "yearForWeekOfYear", value: r)) } if let r = isLeapMonth { c.append((label: "isLeapMonth", value: r)) } return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct) } } // MARK: - Bridging extension DateComponents : _ObjectiveCBridgeable { public static func _getObjectiveCType() -> Any.Type { return NSDateComponents.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSDateComponents { return _handle._copiedReference() } public static func _forceBridgeFromObjectiveC(_ dateComponents: NSDateComponents, result: inout DateComponents?) { if !_conditionallyBridgeFromObjectiveC(dateComponents, result: &result) { fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ dateComponents: NSDateComponents, result: inout DateComponents?) -> Bool { result = DateComponents(reference: dateComponents) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDateComponents?) -> DateComponents { var result: DateComponents? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension NSDateComponents : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as DateComponents) } }
apache-2.0
69eba34dc452cfe8dd3894a5c1b12245
44.901408
544
0.625713
4.399298
false
false
false
false
Polidea/RxBluetoothKit
ExampleApp/ExampleApp/Screens/PeripheralRead/PeripheralReadView.swift
2
1769
import UIKit class PeripheralReadView: UIView { init() { super.init(frame: .zero) backgroundColor = .systemBackground setupLayout() } required init?(coder: NSCoder) { nil } // MARK: - Subviews let serviceUuidTextField: UITextField = { let textField = UITextField() textField.placeholder = Labels.serviceUuidPlaceholder return textField }() let characteristicUuidTextField: UITextField = { let textField = UITextField() textField.placeholder = Labels.characteristicUuidPlaceholder return textField }() let valueTextField: UITextField = { let textField = UITextField() textField.placeholder = "Value (String)" return textField }() let advertiseButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Advertise", for: .normal) button.setImage(UIImage(systemName: "wave.3.right"), for: .normal) return button }() let stackView: UIStackView = { let stackView = UIStackView() stackView.axis = .vertical stackView.spacing = 20.0 return stackView }() // MARK: - Private private func setupLayout() { stackView.translatesAutoresizingMaskIntoConstraints = false addSubview(stackView) [serviceUuidTextField, characteristicUuidTextField, valueTextField, advertiseButton].forEach(stackView.addArrangedSubview) NSLayoutConstraint.activate([ stackView.centerXAnchor.constraint(equalTo: centerXAnchor), stackView.centerYAnchor.constraint(equalTo: centerYAnchor), stackView.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, constant: -32) ]) } }
apache-2.0
5e350d90bf013dbf6c164087d470625c
28
130
0.654042
5.443077
false
false
false
false
Google-IO-Extended-Grand-Rapids/conference_ios
ConferenceApp/ConferenceApp/SessionDetailViewController.swift
1
2264
// // SessionDetailViewController.swift // ConferenceApp // // Created by Dan McCracken on 4/2/15. // Copyright (c) 2015 GR OpenSource. All rights reserved. // import UIKit class SessionDetailViewController: UITableViewController { var conferencesDao: ConferencesDao! var detailItem: Session? { didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. // if let detail: Conference = self.detailItem { // if let label = self.eventNameLabel { // self.eventNameLabel.text = detail.name // self.eventDateLabel.text = "put the date here" // } // } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate conferencesDao = appDelegate.conferencesDao! /* * So, depending on what changes we make to the API, we have to do calls here. * * - Possibly for Room? which there is no API for right now. * + Possibly for Presenter? where there IS an API for, which is nice. */ //conferencesDao.getAllConferences(receivedConferences) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("SessionDetailCell", forIndexPath: indexPath) as! UITableViewCell let object = detailItem as Session? cell.textLabel!.text = object?.name return cell } }
apache-2.0
0c7642bc67b9401125fa35b1d0d6cdc3
30.887324
128
0.611307
5.16895
false
false
false
false
Geor9eLau/WorkHelper
Carthage/Checkouts/SwiftCharts/SwiftCharts/ChartLineModel.swift
1
1413
// // ChartLineModel.swift // swift_charts // // Created by ischuetz on 11/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit /// Models a line to be drawn in a chart based on an array of chart points. public struct ChartLineModel<T: ChartPoint> { /// The array of chart points that the line should be drawn with. In a simple case this would be drawn as straight line segments connecting each point. let chartPoints: [T] /// The color that the line is drawn with let lineColor: UIColor /// The width of the line in points let lineWidth: CGFloat /// The duration in seconds of the animation that is run when the line appears let animDuration: Float /// The delay in seconds before the animation runs let animDelay: Float /// The dash pattern for the line let dashPattern: [Double]? public init(chartPoints: [T], lineColor: UIColor, lineWidth: CGFloat = 1, animDuration: Float, animDelay: Float, dashPattern: [Double]? = nil) { self.chartPoints = chartPoints self.lineColor = lineColor self.lineWidth = lineWidth self.animDuration = animDuration self.animDelay = animDelay self.dashPattern = dashPattern } /// The number of chart points in the model var chartPointsCount: Int { return self.chartPoints.count } }
mit
f2b0de4ce53b724a6b6c3989c2222f1a
29.717391
155
0.665251
4.71
false
false
false
false
dcunited001/Spectra
Pod/Classes/EncodableData.swift
1
7188
// // InputGroup.swift // Spectra // // Created by David Conner on 9/30/15. // Copyright © 2015 Spectra. All rights reserved. // import Metal import simd public struct InputParams { public var index:Int public var offset:Int = 0 } public typealias SceneEncodableDataMap = [String: EncodableData] //static let baseBufferDefaultOptions = ["default": BufferOptions(index: 0, offset: 0) as! AnyObject] public protocol EncodableData { // the advantage of this interface is that buffers, inputs & groups are all accessable under the same interface // - all input params can be passed in as hash under inputParams // - the actual data (buffers/inputs) can be passed in to *optional* inputData, using the same keys as params // - the buffers should be passed in by reference, so buffers can be grabbed off the pool and passed in // - then the actual subclass implementation knows how to piece everything together // - a default implementation can just map up keys from inputParams & inputData // but how to write to buffers using StorageModeShared and StorageModeManaged (with pointers?) // - i guess just pass in the pointer and, again, the subclass implementation knows how to deal with it // - the memory would have to be allocated elsewhere //TODO: add options: [String: AnyObject] ? //TODO: add variation that accepts a block? func writeCompute(encoder: MTLComputeCommandEncoder, inputParams: [String:InputParams], inputData: [String:EncodableData]) func writeVertex(encoder: MTLRenderCommandEncoder, inputParams: [String:InputParams], inputData: [String:EncodableData]) func writeFragment(encoder: MTLRenderCommandEncoder, inputParams: [String:InputParams], inputData: [String:EncodableData]) } public protocol EncodableBuffer: EncodableData { var buffer: MTLBuffer? { get set } var bytecount: Int? { get set } var resourceOptions: MTLResourceOptions? { get set } func prepareBuffer(device: MTLDevice, options: MTLResourceOptions) } public protocol EncodableInput: EncodableData { typealias InputType var data: InputType? { get set } } public class BaseEncodableInput<T>: EncodableInput { public typealias InputType = T public var data: InputType? public func writeCompute(encoder: MTLComputeCommandEncoder, inputParams: [String:InputParams], inputData: [String:EncodableData] = [:]) { encoder.setBytes(&data!, length: sizeof(T), atIndex: inputParams.values.first!.index) } public func writeVertex(encoder: MTLRenderCommandEncoder, inputParams: [String:InputParams], inputData: [String:EncodableData] = [:]) { encoder.setVertexBytes(&data!, length: sizeof(T), atIndex: inputParams.values.first!.index) } public func writeFragment(encoder: MTLRenderCommandEncoder, inputParams: [String:InputParams], inputData: [String:EncodableData] = [:]) { encoder.setFragmentBytes(&data!, length: sizeof(T), atIndex: inputParams.values.first!.index) } } public class BaseEncodableBuffer: EncodableBuffer { // hmm or no EncodableBuffer protocol and just pass in buffers from inputData? public var buffer: MTLBuffer? public var bytecount: Int? public var resourceOptions: MTLResourceOptions? public func prepareBuffer(device: MTLDevice, options: MTLResourceOptions) { buffer = device.newBufferWithLength(bytecount!, options: options) } public func writeCompute(encoder: MTLComputeCommandEncoder, inputParams: [String:InputParams], inputData: [String:EncodableData] = [:]) { let defaultInputParams = inputParams.values.first! encoder.setBuffer(buffer!, offset: defaultInputParams.offset, atIndex: defaultInputParams.index) } public func writeVertex(encoder: MTLRenderCommandEncoder, inputParams: [String:InputParams], inputData: [String:EncodableData] = [:]) { let defaultInputParams = inputParams.values.first! encoder.setVertexBuffer(buffer!, offset: defaultInputParams.offset, atIndex: defaultInputParams.index) } public func writeFragment(encoder: MTLRenderCommandEncoder, inputParams: [String:InputParams], inputData: [String:EncodableData] = [:]) { let defaultInputParams = inputParams.values.first! encoder.setFragmentBuffer(buffer!, offset: defaultInputParams.offset, atIndex: defaultInputParams.index) } } // iterates through the input data/params keys & runs write() on all of them, // and defaults to passing all data down through the tree public class BaseEncodableGroup: EncodableData { public func writeCompute(encoder: MTLComputeCommandEncoder, inputParams: [String:InputParams], inputData: [String:EncodableData]) { for (k,v) in inputData { v.writeCompute(encoder, inputParams: inputParams, inputData: inputData) } } public func writeVertex(encoder: MTLRenderCommandEncoder, inputParams: [String:InputParams], inputData: [String:EncodableData]) { for (k,v) in inputData { v.writeVertex(encoder, inputParams: inputParams, inputData: inputData) } } public func writeFragment(encoder: MTLRenderCommandEncoder, inputParams: [String:InputParams], inputData: [String:EncodableData]) { for (k,v) in inputData { v.writeFragment(encoder, inputParams: inputParams, inputData: inputData) } } } //class CircularBuffer: EncodableBuffer { // //} // manages writing texture data //class TextureBuffer: SpectraBaseBuffer { // //} // highly performant buffer (requires iOS and CPU/GPU integrated architecture) // TODO: decide if generic is required? //@available(iOS 9.0, *) //class NoCopyBuffer<T>: EncodableBuffer { // var stride:Int? // var elementSize:Int = sizeof(T) // private var bufferPtr: UnsafeMutablePointer<Void>? // private var bufferVoidPtr: COpaquePointer? // private var bufferDataPtr: UnsafeMutablePointer<T>? // var bufferAlignment: Int = 0x1000 // for NoCopy buffers, memory needs needs to be mutliples of 4096 // // func prepareMemory(bytecount: Int) { // self.bytecount = bytecount // bufferPtr = UnsafeMutablePointer<Void>.alloc(bytecount) // posix_memalign(&bufferPtr!, bufferAlignment, bytecount) // bufferVoidPtr = COpaquePointer(bufferPtr!) // bufferDataPtr = UnsafeMutablePointer<T>(bufferVoidPtr!) // } // // override func prepareBuffer(device: MTLDevice, options: MTLResourceOptions) { // //TODO: common deallocator? // buffer = device.newBufferWithBytesNoCopy(bufferPtr!, length: bytecount!, options: .StorageModeShared, deallocator: nil) // } // // //TODO: decide on how to use similar data access patterns when buffer is specific to a texture // // override func initTexture(device: MTLDevice, textureDescriptor: MTLTextureDescriptor) { // // // texture = texBuffer!.newTextureWithDescriptor(textureDescriptor, offset: 0, bytesPerRow: calcBytesPerRow()) // // } // // //mechanism for writing specific bytes // func writeBuffer(data: [T]) { // memcpy(bufferDataPtr!, data, bytecount!) // } //}
mit
5b0010751cb0ef982889d2fe2377a9f3
43.91875
141
0.715737
4.390348
false
false
false
false
taqun/TodoEver
TodoEver/Classes/Model/Managed/TDEMNote.swift
1
2417
// // TDEMNote.swift // TodoEver // // Created by taqun on 2015/06/01. // Copyright (c) 2015年 envoixapp. All rights reserved. // import UIKit import CoreData import SWXMLHash @objc(TDEMNote) class TDEMNote: NSManagedObject { @NSManaged var title: String @NSManaged var guid: String @NSManaged var content: String @NSManaged var usn: NSNumber @NSManaged var needsToSync: Bool @NSManaged var remoteUsn: NSNumber @NSManaged var tasks: NSMutableSet /* * Public Method */ func parseMetaData(metaData: EDAMNoteMetadata) { self.title = metaData.title self.guid = metaData.guid self.usn = metaData.updateSequenceNum } func appendTasks(tasks: [TDEMTask]) { let taskSet = NSMutableSet(array: tasks) self.tasks = taskSet } func addTask(task: TDEMTask) { self.tasks.addObject(task) } func removeTask(index: Int) { var tasks = self.orderedTasks tasks.removeAtIndex(index) let taskSet = NSMutableSet(array: tasks) self.tasks = taskSet } func generateEDAMNote() -> (EDAMNote) { var edamNote = EDAMNote() edamNote.title = self.title edamNote.guid = self.guid edamNote.content = self.generateContent() return edamNote } /* * Private Method */ func generateContent() -> (String) { var content = "" content += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" content += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" content += "<en-note>" for task in self.orderedTasks { content += task.htmlString } content += "</en-note>" return content } /* * Getter, Setter */ var orderedTasks: [TDEMTask] { get { if var array = self.tasks.allObjects as? [TDEMTask] { array.sort({ $0.index < $1.index }) return array } else { return [] } } } var isChanged: Bool { get { if self.content != self.generateContent() { return true } else { return false } } } }
mit
e22683024943c5239d7eef01fa37c0f4
21.361111
90
0.522567
4.375
false
false
false
false
lintaoSuper/Kingfisher
Kingfisher/KingfisherOptions.swift
25
3914
// // KingfisherOptions.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2015 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** * Options to control Kingfisher behaviors. */ public struct KingfisherOptions : RawOptionSetType { typealias RawValue = UInt private var value: UInt = 0 init(_ value: UInt) { self.value = value } /** Init an option :param: value Raw value of the option. :returns: An option represets input value. */ public init(rawValue value: UInt) { self.value = value } /** Init a None option :param: nilLiteral Void. :returns: An option represents None. */ public init(nilLiteral: ()) { self.value = 0 } /// An option represents None. public static var allZeros: KingfisherOptions { return self(0) } /// Raw value of the option. public var rawValue: UInt { return self.value } static func fromMask(raw: UInt) -> KingfisherOptions { return self(raw) } /// None options. Kingfisher will keep its default behavior. public static var None: KingfisherOptions { return self(0) } /// Download in a low priority. public static var LowPriority: KingfisherOptions { return KingfisherOptions(1 << 0) } /// Try to send request to server first. If response code is 304 (Not Modified), use the cached image. Otherwise, download the image and cache it again. public static var ForceRefresh: KingfisherOptions { return KingfisherOptions(1 << 1) } /// Only cache downloaded image to memory, not cache in disk. public static var CacheMemoryOnly: KingfisherOptions { return KingfisherOptions(1 << 2) } /// Decode the image in background thread before using. public static var BackgroundDecode: KingfisherOptions { return KingfisherOptions(1 << 3) } /// Cache the downloaded image to Apple Watch app. By default the downloaded image will not be cached in the watch. By containing this in options could improve performance when setting the same URL later. However, the cache size in the Watch is limited. So you will want to cache often used images only. public static var CacheInWatch: KingfisherOptions { return KingfisherOptions(1 << 4) } /// If set it will dispatch callbacks asynchronously to the global queue DISPATCH_QUEUE_PRIORITY_DEFAULT. Otherwise it will use the queue defined at KingfisherManager.DefaultOptions.queue public static var BackgroundCallback: KingfisherOptions { return KingfisherOptions(1 << 5) } /// Decode the image using the same scale as the main screen. Otherwise it will use the same scale as defined on the KingfisherManager.DefaultOptions.scale. public static var ScreenScale: KingfisherOptions { return KingfisherOptions(1 << 6) } }
mit
7143836e60fb59ec23324a359541ba5c
44.511628
307
0.718191
4.698679
false
false
false
false
Dimillian/HackerSwifter
Hacker Swifter/Hacker Swifter/HTTP/Cache.swift
1
5270
// // Cache.swift // HackerSwifter // // Created by Thomas Ricouard on 16/07/14. // Copyright (c) 2014 Thomas Ricouard. All rights reserved. // import Foundation private let _Cache = Cache() private let _MemoryCache = MemoryCache() private let _DiskCache = DiskCache() public typealias cacheCompletion = (AnyObject!) -> Void public class Cache { public class var sharedCache: Cache { return _Cache } init() { } public class func generateCacheKey(path: String) -> String { if (path == "") { return "root" } return path.stringByReplacingOccurrencesOfString("/", withString: "#", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) } public func setObject(object: AnyObject, key: String) { if (object.conformsToProtocol(NSCoding)) { MemoryCache.sharedMemoryCache.setObject(object, key: key) DiskCache.sharedDiskCache.setObject(object, key: key) } } public func objectForKey(key: String, completion: cacheCompletion) { MemoryCache.sharedMemoryCache.objectForKey(key, completion: {(object: AnyObject!) in if let realObject: AnyObject = object { completion(realObject) } else { DiskCache.sharedDiskCache.objectForKey(key, completion: {(object: AnyObject!) in completion(object) }) } }) } public func objectForKeySync(key: String) -> AnyObject! { let ramObject: AnyObject! = MemoryCache.sharedMemoryCache.objectForKeySync(key) return (ramObject != nil) ? ramObject : DiskCache.sharedDiskCache.objectForKeySync(key) } public func removeObject(key: String) { MemoryCache.sharedMemoryCache.removeObject(key) DiskCache.sharedDiskCache.removeObject(key) } public func removeAllObject() { MemoryCache.sharedMemoryCache.removeAllObject() DiskCache.sharedDiskCache.removeAllObject() } } public class DiskCache: Cache { private struct files { static var filepath: String { let manager = NSFileManager.defaultManager() var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true) let cachePath = paths[0] + "/modelCache/" if (!manager.fileExistsAtPath(cachePath)) { do { try manager.createDirectoryAtPath(cachePath, withIntermediateDirectories: true, attributes: nil) } catch _ { } } return cachePath } } private let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT public class var sharedDiskCache: Cache { return _DiskCache } override init() { } public func fullPath(key: String) -> String { return files.filepath + key } public func objectExist(key: String) -> Bool { return NSFileManager.defaultManager().fileExistsAtPath(fullPath(key)) } public override func objectForKey(key: String, completion: cacheCompletion) { if (self.objectExist(key)) { dispatch_async(dispatch_get_global_queue(self.priority, UInt(0)), { ()->() in let object: AnyObject! = NSKeyedUnarchiver.unarchiveObjectWithFile(self.fullPath(key)) dispatch_async(dispatch_get_main_queue(), { ()->() in completion(object) }) }) } else { completion(nil) } } public override func objectForKeySync(key: String) -> AnyObject! { if (self.objectExist(key)) { return NSKeyedUnarchiver.unarchiveObjectWithFile(self.fullPath(key)) } return nil } public override func setObject(object: AnyObject, key: String) { NSKeyedArchiver.archiveRootObject(object, toFile: self.fullPath(key)) } public override func removeObject(key: String) { if (self.objectExist(key)) { do { try NSFileManager.defaultManager().removeItemAtPath(self.fullPath(key)) } catch _ { } } } public override func removeAllObject() { } } public class MemoryCache: Cache { private var memoryCache = NSCache() public class var sharedMemoryCache: Cache { return _MemoryCache } override init() { } public override func objectForKeySync(key: String) -> AnyObject! { return self.memoryCache.objectForKey(key) } public override func objectForKey(key: String, completion: cacheCompletion) { completion(self.memoryCache.objectForKey(key)) } public override func setObject(object: AnyObject, key: String) { self.memoryCache.setObject(object, forKey: key) } public override func removeObject(key: String) { self.memoryCache.removeObjectForKey(key) } public override func removeAllObject() { self.memoryCache.removeAllObjects() } }
mit
6652a989d9f461c55dc0f7d7fb57baad
28.606742
120
0.605123
5.171737
false
false
false
false
NickAger/NADocumentPicker
Example/Pods/BrightFutures/Sources/BrightFutures/SequenceType+BrightFutures.swift
1
6322
// The MIT License (MIT) // // Copyright (c) 2014 Thomas Visser // // 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 extension Sequence { /// Turns a sequence of T's into an array of `Future<U>`'s by calling the given closure for each element in the sequence. /// If no context is provided, the given closure is executed on `Queue.global` public func traverse<U, E, A: AsyncType>(_ context: @escaping ExecutionContext = DispatchQueue.global().context, f: (Iterator.Element) -> A) -> Future<[U], E> where A.Value: ResultProtocol, A.Value.Value == U, A.Value.Error == E { return map(f).fold(context, zero: [U]()) { (list: [U], elem: U) -> [U] in return list + [elem] } } } extension Sequence where Iterator.Element: AsyncType { /// Returns a future that returns with the first future from the given sequence that completes /// (regardless of whether that future succeeds or fails) public func firstCompleted() -> Iterator.Element { let res = Async<Iterator.Element.Value>() for fut in self { fut.onComplete(DispatchQueue.global().context) { res.tryComplete($0) } } return Iterator.Element(other: res) } } extension Sequence where Iterator.Element: AsyncType, Iterator.Element.Value: ResultProtocol { //// The free functions in this file operate on sequences of Futures /// Performs the fold operation over a sequence of futures. The folding is performed /// on `Queue.global`. /// (The Swift compiler does not allow a context parameter with a default value /// so we define some functions twice) public func fold<R>(_ zero: R, f: @escaping (R, Iterator.Element.Value.Value) -> R) -> Future<R, Iterator.Element.Value.Error> { return fold(DispatchQueue.global().context, zero: zero, f: f) } /// Performs the fold operation over a sequence of futures. The folding is performed /// in the given context. public func fold<R>(_ context: @escaping ExecutionContext, zero: R, f: @escaping (R, Iterator.Element.Value.Value) -> R) -> Future<R, Iterator.Element.Value.Error> { return reduce(Future<R, Iterator.Element.Value.Error>(value: zero)) { zero, elem in return zero.flatMap(MaxStackDepthExecutionContext) { zeroVal in elem.map(context) { elemVal in return f(zeroVal, elemVal) } } } } /// Turns a sequence of `Future<T>`'s into a future with an array of T's (Future<[T]>) /// If one of the futures in the given sequence fails, the returned future will fail /// with the error of the first future that comes first in the list. public func sequence() -> Future<[Iterator.Element.Value.Value], Iterator.Element.Value.Error> { return traverse(ImmediateExecutionContext) { return $0 } } /// See `find<S: SequenceType, T where S.Iterator.Element == Future<T>>(seq: S, context c: ExecutionContext, p: T -> Bool) -> Future<T>` public func find(_ p: @escaping (Iterator.Element.Value.Value) -> Bool) -> Future<Iterator.Element.Value.Value, BrightFuturesError<Iterator.Element.Value.Error>> { return find(DispatchQueue.global().context, p: p) } /// Returns a future that succeeds with the value from the first future in the given /// sequence that passes the test `p`. /// If any of the futures in the given sequence fail, the returned future fails with the /// error of the first failed future in the sequence. /// If no futures in the sequence pass the test, a future with an error with NoSuchElement is returned. public func find(_ context: @escaping ExecutionContext, p: @escaping (Iterator.Element.Value.Value) -> Bool) -> Future<Iterator.Element.Value.Value, BrightFuturesError<Iterator.Element.Value.Error>> { return sequence().mapError(ImmediateExecutionContext) { error in return BrightFuturesError(external: error) }.flatMap(context) { val -> Result<Iterator.Element.Value.Value, BrightFuturesError<Iterator.Element.Value.Error>> in for elem in val { if (p(elem)) { return .success(elem) } } return .failure(.noSuchElement) } } } extension Sequence where Iterator.Element: ResultProtocol { /// Turns a sequence of `Result<T>`'s into a Result with an array of T's (`Result<[T]>`) /// If one of the results in the given sequence is a .failure, the returned result is a .failure with the /// error from the first failed result from the sequence. public func sequence() -> Result<[Iterator.Element.Value], Iterator.Element.Error> { return reduce(.success([])) { (res, elem) -> Result<[Iterator.Element.Value], Iterator.Element.Error> in switch res { case .success(let resultSequence): return elem.analysis(ifSuccess: { let newSeq = resultSequence + [$0] return .success(newSeq) }, ifFailure: { return .failure($0) }) case .failure(_): return res } } } }
mit
ff7f69a976d9746a4717b7f90d69463f
49.576
234
0.655805
4.439607
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/ConnectRequests/IncomingConnectionView.swift
1
6804
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireSyncEngine import WireCommonComponents final class IncomingConnectionView: UIView { private let usernameLabel = UILabel() private let userDetailView = UserNameDetailView() private let securityLevelView = SecurityLevelView() private let userImageView = UserImageView() private let incomingConnectionFooter = UIView() private let acceptButton = Button(style: .accentColorTextButtonStyle, cornerRadius: 16, fontSpec: .smallSemiboldFont) private let ignoreButton = Button(style: .secondaryTextButtonStyle, cornerRadius: 16, fontSpec: .smallSemiboldFont) private let classificationProvider: ClassificationProviding? var user: UserType { didSet { setupLabelText() userImageView.user = user } } typealias UserAction = (UserType) -> Void var onAccept: UserAction? var onIgnore: UserAction? init(user: UserType, classificationProvider: ClassificationProviding? = ZMUserSession.shared()) { self.user = user self.classificationProvider = classificationProvider super.init(frame: .zero) userImageView.userSession = ZMUserSession.shared() userImageView.initialsFont = UIFont.systemFont(ofSize: 55, weight: .semibold).monospaced() setup() createConstraints() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { acceptButton.accessibilityLabel = "accept" acceptButton.setTitle("inbox.connection_request.connect_button_title".localized(uppercased: true), for: .normal) acceptButton.addTarget(self, action: #selector(onAcceptButton), for: .touchUpInside) ignoreButton.accessibilityLabel = "ignore" ignoreButton.setTitle("inbox.connection_request.ignore_button_title".localized(uppercased: true), for: .normal) ignoreButton.addTarget(self, action: #selector(onIgnoreButton), for: .touchUpInside) userImageView.accessibilityLabel = "user image" userImageView.shouldDesaturate = false userImageView.size = .big userImageView.user = user incomingConnectionFooter.addSubview(acceptButton) incomingConnectionFooter.addSubview(ignoreButton) [usernameLabel, userDetailView, securityLevelView, userImageView, incomingConnectionFooter].forEach(addSubview) setupLabelText() } private func setupLabelText() { let viewModel = UserNameDetailViewModel( user: user, fallbackName: "", addressBookName: (user as? ZMUser)?.addressBookEntry?.cachedName ) usernameLabel.attributedText = viewModel.title usernameLabel.accessibilityIdentifier = "name" userDetailView.configure(with: viewModel) securityLevelView.configure(with: [user], provider: classificationProvider) } private func createConstraints() { [incomingConnectionFooter, acceptButton, ignoreButton, usernameLabel, userDetailView, securityLevelView, userImageView].prepareForLayout() NSLayoutConstraint.activate([ ignoreButton.leftAnchor.constraint(equalTo: incomingConnectionFooter.leftAnchor, constant: 16), ignoreButton.topAnchor.constraint(equalTo: incomingConnectionFooter.topAnchor, constant: 12), ignoreButton.bottomAnchor.constraint(equalTo: incomingConnectionFooter.bottomAnchor, constant: -16), ignoreButton.heightAnchor.constraint(equalToConstant: 40), ignoreButton.rightAnchor.constraint(equalTo: incomingConnectionFooter.centerXAnchor, constant: -8), acceptButton.rightAnchor.constraint(equalTo: incomingConnectionFooter.rightAnchor, constant: -16), acceptButton.leftAnchor.constraint(equalTo: incomingConnectionFooter.centerXAnchor, constant: 8), acceptButton.centerYAnchor.constraint(equalTo: ignoreButton.centerYAnchor), acceptButton.heightAnchor.constraint(equalTo: ignoreButton.heightAnchor), usernameLabel.topAnchor.constraint(equalTo: topAnchor, constant: 18), usernameLabel.centerXAnchor.constraint(equalTo: centerXAnchor), usernameLabel.leftAnchor.constraint(greaterThanOrEqualTo: leftAnchor), userDetailView.centerXAnchor.constraint(equalTo: centerXAnchor), userDetailView.topAnchor.constraint(equalTo: usernameLabel.bottomAnchor, constant: 4), userDetailView.leftAnchor.constraint(greaterThanOrEqualTo: leftAnchor), securityLevelView.topAnchor.constraint(equalTo: userDetailView.bottomAnchor, constant: 4), securityLevelView.centerXAnchor.constraint(equalTo: centerXAnchor), securityLevelView.leadingAnchor.constraint(equalTo: leadingAnchor), securityLevelView.trailingAnchor.constraint(equalTo: trailingAnchor), securityLevelView.bottomAnchor.constraint(lessThanOrEqualTo: userImageView.topAnchor), userImageView.centerXAnchor.constraint(equalTo: centerXAnchor), userImageView.centerYAnchor.constraint(equalTo: centerYAnchor), userImageView.leftAnchor.constraint(greaterThanOrEqualTo: leftAnchor, constant: 54), userImageView.widthAnchor.constraint(equalTo: userImageView.heightAnchor), userImageView.heightAnchor.constraint(lessThanOrEqualToConstant: 264), incomingConnectionFooter.topAnchor.constraint(greaterThanOrEqualTo: userImageView.bottomAnchor), incomingConnectionFooter.leftAnchor.constraint(equalTo: leftAnchor), incomingConnectionFooter.bottomAnchor.constraint(equalTo: bottomAnchor), incomingConnectionFooter.rightAnchor.constraint(equalTo: rightAnchor) ]) } // MARK: - Actions @objc private func onAcceptButton(sender: AnyObject!) { onAccept?(user) } @objc private func onIgnoreButton(sender: AnyObject!) { onIgnore?(user) } }
gpl-3.0
0ce445ebe10896c0698a4684d8c9a356
42.615385
121
0.721046
5.408585
false
false
false
false
mattgallagher/CwlSignal
Sources/CwlSignal/CwlSignalReactive.swift
1
154005
// // CwlSignalReactive.swift // CwlSignal // // Created by Matt Gallagher on 2016/09/08. // Copyright © 2016 Matt Gallagher ( https://www.cocoawithlove.com ). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // import CwlUtils import Foundation #if swift(>=4) #else public typealias Numeric = IntegerArithmetic & ExpressibleByIntegerLiteral public typealias BinaryInteger = IntegerArithmetic & ExpressibleByIntegerLiteral #endif /// Errors used by the Reactive extensions on Signal. /// - timeout: used to close the stream when the Signal.timeout function reaches its limit. public enum SignalReactiveError: Error { case timeout } extension SignalInterface { /// - Note: the [Reactive X operator "Create"](http://reactivex.io/documentation/operators/create.html) is considered unnecessary, given the `CwlSignal.Signal.generate` and `CwlSignal.Signal.create` methods. /// - Note: the [Reactive X operator "Defer"](http://reactivex.io/documentation/operators/defer.html) is considered not applicable, given the different semantics of "activation" with `CwlSignal.Signal`. If `Defer`-like behavior is desired, either a method that constructs and returns a new `Signal` graph should be used (if a truly distinct graph is desired) or `CwlSignal.Signal.generate` should be used (if wait-until-activated behavior is desired). } extension Signal { /// Implementation of [Reactive X operator "From"](http://reactivex.io/documentation/operators/from.html) in the context of the Swift `Sequence` /// /// See also: `preclosed(:)`, which is a shareable activation sequence /// See also: `just(:)`, which offers the same functionality but accepts a variable argument list instead of a sequence /// /// NOTE: it is possible to specify a `nil` error to have the signal remain open at the end of the sequence. /// /// - parameter values: A Swift `Sequence` that generates the signal values. /// - parameter end: The error with which to close the sequence. Can be `nil` to leave the sequence open (default: `SignalEnd.complete`) /// - parameter context: the `Exec` where the `SequenceType` will be enumerated (default: .direct). /// - returns: a signal that emits `values` and then closes public static func from<S: Sequence>(_ sequence: S, end: SignalEnd? = .complete, context: Exec = .direct) -> Signal<OutputValue> where S.Iterator.Element == OutputValue { if let e = end { return generate(context: context) { input in guard let i = input else { return } for v in sequence { if let _ = i.send(result: .success(v)) { break } } i.send(end: e) } } else { return retainedGenerate(context: context) { input in guard let i = input else { return } for v in sequence { if let _ = i.send(result: .success(v)) { break } } } } } /// Implementation of [Reactive X operator "Never"](http://reactivex.io/documentation/operators/empty-never-throw.html) /// /// Implemented as `.from([], end: nil)` /// /// - returns: a non-sending, non-closing signal of the desired type public static func never() -> Signal<OutputValue> { return .from([], end: nil) } /// - Implementation of [Reactive X operator "Just"](http://reactivex.io/documentation/operators/just.html) /// /// See also: `from(:)`, which sends a sequence of values (optionally on a specific context) /// See also: `preclosed(:)`, which is a shareable activation sequence /// /// - Parameters: /// - value: the value to send /// - end: if non-nil, sent after value to close the stream /// - Returns: a signal that will emit `value` and (optionally) close public static func just(_ values: OutputValue..., end: SignalEnd? = .complete) -> Signal<OutputValue> { return .from(values, end: end) } /// - Implementation of [Reactive X operator "Throw"](http://reactivex.io/documentation/operators/empty-never-throw.html) /// /// See also: `from(:)`, which sends a sequence of values (optionally on a specific context) /// See also: `preclosed(:)`, which is a shareable activation sequence /// /// - Parameters: /// - value: the value to send /// - end: if non-nil, sent after value to close the stream /// - Returns: a signal that will emit `value` and (optionally) close public static func error(_ error: Error) -> Signal<OutputValue> { return Signal<OutputValue>.from([], end: .other(error)) } /// - Implementation of [Reactive X operator "Empty"](http://reactivex.io/documentation/operators/empty-never-throw.html) /// /// See also: `from(:)`, which sends a sequence of values (optionally on a specific context) /// /// - Returns: a signal that will emit no values and then close public static func empty() -> Signal<OutputValue> { return Signal<OutputValue>.from([]) } } extension SignalInterface { /// Implementation of [Reactive X operator "To"](http://reactivex.io/documentation/operators/to.html) in the context of the Swift `Sequence` /// /// WARNING: Because it blocks the receiving thread, and because it undermines the principle of *reactive* programming, this function should only be used in specific circumstances. /// /// `SignalSequence` subscribes to `self` and blocks. This means that if any earlier signals in the graph force processing on the same context where `SignalSequence` is iterated, a deadlock may occur between the iteration and the signal processing. /// This function is safe only when you can guarantee all parts of the signal graph are independent of the blocking context. public func toSequence() -> SignalSequence<OutputValue> { return SignalSequence<OutputValue>(signal) } } /// Represents a Signal<OutputValue> converted to a synchronously iterated sequence. Values can be obtained using typical SequenceType actions. The error that ends the sequence is available through the `error` property. public class SignalSequence<OutputValue>: Sequence, IteratorProtocol { typealias GeneratorType = SignalSequence<OutputValue> typealias ElementType = OutputValue let semaphore = DispatchSemaphore(value: 0) let context = Exec.syncQueue() var output: SignalOutput<OutputValue>? = nil var queued: Array<OutputValue> = [] /// Error type property is `nil` before the end of the signal is reached and contains the error used to close the signal in other cases public var end: SignalEnd? // Only intended to be constructed by `Signal.toSequence` // // - Parameter signal: the signal whose values will be iterated by this sequence init(_ signal: Signal<OutputValue>) { output = signal.subscribe(context: context) { [weak self] (r: Result<OutputValue, SignalEnd>) in guard let s = self else { return } switch r { case .success(let v): s.queued.append(v) s.semaphore.signal() case .failure(let e): s.end = e s.semaphore.signal() } } } /// Stops listening to the signal and set the error value to SignalComplete.cancelled public func cancel() { context.invokeSync { self.end = .cancelled self.output?.cancel() self.semaphore.signal() } } /// Implementation of GeneratorType method. public func next() -> OutputValue? { _ = semaphore.wait(timeout: DispatchTime.distantFuture) return context.invokeSync { [weak self] () -> OutputValue? in guard let s = self else { return nil } if !s.queued.isEmpty { return s.queued.removeFirst() } else { // Signal the sempahore so that `nil` can be fetched again. s.semaphore.signal() return nil } } } deinit { if end == nil { semaphore.signal() } } } extension SignalInterface where OutputValue == Int { /// Implementation of [Reactive X operator "Interval"](http://reactivex.io/documentation/operators/interval.html) /// /// - Parameters: /// - interval: duration between values /// - initialInterval: duration until first value /// - context: execution context where the timer will run /// - Returns: the interval signal public static func interval(_ interval: DispatchTimeInterval = .seconds(1), initial initialInterval: DispatchTimeInterval? = nil, context: Exec = .global) -> Signal<Int> { // We need to protect the `count` variable and make sure that out-of-date timers don't update it so we use a `serialized` context for the `generate` and the timers, since the combination of the two will ensure that these requirements are met. let serialContext = context.serialized() var timer: Lifetime? = nil var count = 0 return Signal<Int>.generate(context: serialContext) { input in guard let i = input else { timer?.cancel() count = 0 return } let repeater = { timer = serialContext.periodicTimer(interval: interval) { i.send(value: count) count += 1 } } if let initial = initialInterval { if initial == .seconds(0) { i.send(value: count) count += 1 repeater() } else { timer = serialContext.singleTimer(interval: initial) { i.send(value: count) count += 1 repeater() } } } else { repeater() } } } } extension SignalInterface { /// - Note: the [Reactive X operator `Range`](http://reactivex.io/documentation/operators/range.html) is considered unnecessary, given that ranges are already handled by `from(:)`. } extension Signal { /// Implementation of [Reactive X operator "Repeat"](http://reactivex.io/documentation/operators/repeat.html) for a Swift `CollectionType` /// /// - Parameters: /// - values: A Swift `CollectionType` that generates the signal values. /// - count: the number of times that `values` will be repeated. /// - context: the `Exec` where the `SequenceType` will be enumerated. /// - Returns: a signal that emits `values` a `count` number of times and then closes public static func repeatCollection<C: Collection>(_ values: C, count: Int, context: Exec = .direct) -> Signal<OutputValue> where C.Iterator.Element == OutputValue { return generate(context: context) { input in guard let i = input else { return } for _ in 0..<count { for v in values { if i.send(result: .success(v)) != nil { break } } } i.complete() } } /// Implementation of [Reactive X operator "Start"](http://reactivex.io/documentation/operators/start.html) /// /// - Parameters: /// - context: the `Exec` where `f` will be evaluated (default: .direct). /// - f: a function that is run to generate the value. /// - Returns: a signal that emits a single value emitted from a function public static func start(context: Exec = .direct, f: @escaping () -> OutputValue) -> Signal<OutputValue> { return Signal.generate(context: context) { input in guard let i = input else { return } i.send(value: f()) i.complete() } } /// Implementation of [Reactive X operator "Timer"](http://reactivex.io/documentation/operators/timer.html) /// /// - Parameters: /// - interval: the time until the value is sent. /// - value: the value that will be sent before closing the signal (if `nil` then the signal will simply be closed at the end of the timer) /// - context: execution context where the timer will be run /// - Returns: the timer signal public static func timer(interval: DispatchTimeInterval, value: OutputValue? = nil, context: Exec = .global) -> Signal<OutputValue> { var timer: Lifetime? = nil return Signal<OutputValue>.generate(context: context) { input in if let i = input { timer = context.singleTimer(interval: interval) { if let v = value { i.send(value: v) } i.complete() } } else { timer?.cancel() } } } } extension SignalInterface { /// A shared function for emitting a boundary signal usable by the timed, non-overlapping buffer/window functions buffer(timeshift:count:continuous:behavior:) or window(timeshift:count:continuous:behavior:) /// /// - Parameters: /// - interval: maximum duration between boundaries /// - count: maximum number of signal values between boundaries /// - continuous: timer is paused immediately after a boundary until the next value is received /// - context: execution context where the timer will be run /// - Returns: the boundary signal private func timedCountedBoundary(interval: DispatchTimeInterval, count: Int, continuous: Bool, context: Exec) -> Signal<Void> { // An interval signal let intSig = Signal.interval(interval, context: context) if count == Int.max { // If number of values per boundary is infinite, then all we need is the timer signal return intSig.map { v in () } } // The interval signal may need to be disconnectable so create a junction let intervalJunction = intSig.junction() let (initialInput, sig) = Signal<Int>.create() // Continuous signals don't really need the junction. Just connect it immediately and ignore it. if continuous { // Both `intervalJunction` and `initialInput` are newly created so this can't be an error try! intervalJunction.bind(to: initialInput) } return combine(sig, initialState: (0, nil)) { (state: inout (count: Int, timerInput: SignalInput<Int>?), cr: EitherResult2<OutputValue, Int>) -> Signal<Void>.Next in var send = false switch cr { case .result1(.success): // Count the values received per window state.count += 1 // If we hit `count` values, trigger the boundary signal if state.count == count { send = true } else if !continuous, let i = state.timerInput { // If we're not continuous, make sure the timer is connected do { try intervalJunction.bind(to: i) } catch { return .end(.other(error)) } } case .result1(.failure(let e)): // If there's an error on the `self` signal, forward it on. return .end(e) case .result2(.success): // When the timer fires, trigger the boundary signal send = true case .result2(.failure(let e)): // If there's a timer error, close return .end(e) } if send { // Reset the count and – if not continuous – disconnect the timer until we receive a signal from `self` state.count = 0 if !continuous { state.timerInput = intervalJunction.disconnect() } // Send the boundary signal return .value(()) } else { return .none } } } /// Implementation of [Reactive X operator "Buffer"](http://reactivex.io/documentation/operators/buffer.html) for non-overlapping/no-gap buffers. /// /// - Parameter boundaries: when this `Signal` sends a value, the buffer is emitted and cleared /// - Returns: a signal where the values are arrays of values from `self`, accumulated according to `boundaries` public func buffer<Interface: SignalInterface>(boundaries: Interface) -> Signal<[OutputValue]> { return combine(boundaries, initialState: [OutputValue]()) { (buffer: inout [OutputValue], cr: EitherResult2<OutputValue, Interface.OutputValue>) -> Signal<[OutputValue]>.Next in switch cr { case .result1(.success(let v)): buffer.append(v) return .none case .result1(.failure(let e)): let b = buffer buffer.removeAll() return .value(b, end: e) case .result2(.success): let b = buffer buffer.removeAll() return .value(b) case .result2(.failure(let e)): let b = buffer buffer.removeAll() return .value(b, end: e) } } } /// Implementation of [Reactive X operator "Buffer"](http://reactivex.io/documentation/operators/buffer.html) for buffers with overlap or gaps between. /// /// - Parameter windows: a "windows" signal (one that describes a series of times and durations). Each value `Signal` in the stream starts a new buffer and when the value `Signal` closes, the buffer is emitted. /// - Returns: a signal where the values are arrays of values from `self`, accumulated according to `windows` public func buffer<Interface: SignalInterface>(windows: Interface) -> Signal<[OutputValue]> where Interface.OutputValue: SignalInterface { return combine(windows.valueDurations { s in s }, initialState: [Int: [OutputValue]]()) { (buffers: inout [Int: [OutputValue]], cr: EitherResult2<OutputValue, (Int, Interface.OutputValue?)>) -> Signal<[OutputValue]>.Next in switch cr { case .result1(.success(let v)): for index in buffers.keys { buffers[index]?.append(v) } return .none case .result1(.failure(let e)): let values = buffers.map { $0.1 } buffers.removeAll() return .values(sequence: values, end: e) case .result2(.success((let index, .some))): buffers[index] = [] return .none case .result2(.success((let index, .none))): if let b = buffers[index] { buffers.removeValue(forKey: index) return .value(b) } return .none case .result2(.failure(let e)): let values = buffers.map { $0.1 } buffers.removeAll() return .values(sequence: values, end: e) } } } /// Implementation of [Reactive X operator "Buffer"](http://reactivex.io/documentation/operators/buffer.html) for buffers of fixed length and a fixed number of values separating starts. /// /// - Parameters: /// - count: the number of separate values to accumulate before emitting an array of values /// - skip: the stride between the start of each new buffer (can be smaller than `count`, resulting in overlapping buffers) /// - Returns: a signal where the values are arrays of length `count` of values from `self`, with start values separated by `skip` public func buffer(count: UInt, skip: UInt) -> Signal<[OutputValue]> { if count == 0 { return Signal<[OutputValue]>.preclosed() } let multi = multicast() // Create the two listeners to the "multi" signal carefully so that the window signal is *first* (so it reaches the buffer before the value signal) let windowSignal = multi.stride(count: Int(skip)).map { _ in // `count - 1` is the index of the count-th element but since `valuesSignal` will resolve before this, we need to fire 1 element sooner, hence `count - 2` multi.elementAt(count - 2).ignoreElements(outputType: OutputValue.self) } return multi.buffer(windows: windowSignal) } /// Implementation of [Reactive X operator "Buffer"](http://reactivex.io/documentation/operators/buffer.html) for non-overlapping, periodic buffer start times and possibly limited buffer sizes. /// /// - Parameters: /// - interval: number of seconds between the start of each buffer /// - count: the number of separate values to accumulate before emitting an array of values /// - continuous: if `true` (default), the `timeshift` periodic timer runs continuously (empty buffers may be emitted if a timeshift elapses without any source signals). If `false`, the periodic timer does start until the first value is received from the source and the periodic timer is paused when a buffer is emitted. /// - context: context where the timer will be run /// - Returns: a signal where the values are arrays of values from `self`, accumulated according to `windows public func buffer(interval: DispatchTimeInterval, count: Int = Int.max, continuous: Bool = true, context: Exec = .direct) -> Signal<[OutputValue]> { let multi = multicast() // Create the two listeners to the "multi" signal carefully so that the raw signal is *first* (so it reaches the buffer before the boundary signal) let valuesSignal = multi.map { v in v } let boundarySignal = multi.timedCountedBoundary(interval: interval, count: count, continuous: continuous, context: context) return valuesSignal.buffer(boundaries: boundarySignal) } /// Implementation of [Reactive X operator "Buffer"](http://reactivex.io/documentation/operators/buffer.html) for non-overlapping buffers of fixed length. /// /// - Note: this is just a convenience wrapper around `buffer(count:skip:)` where `skip` equals `count`. /// /// - Parameter count: the number of separate values to accumulate before emitting an array of values /// - Returns: a signal where the values are arrays of values from `self`, accumulated according to `count` public func buffer(count: UInt) -> Signal<[OutputValue]> { return buffer(count: count, skip: count) } /// Implementation of [Reactive X operator "Buffer"](http://reactivex.io/documentation/operators/buffer.html) for periodic buffer start times and fixed duration buffers. /// /// - Note: this is just a convenience wrapper around `buffer(windows:behaviors)` where the `windows` signal contains `timerSignal` signals contained in a `Signal.interval` signal. /// /// - Parameters: /// - interval: the duration of each buffer, in seconds. /// - timeshift: the number of seconds between the start of each buffer (if smaller than `interval`, buffers will overlap). /// - context: context where the timer will be run /// - Returns: a signal where the values are arrays of values from `self`, accumulated according to `windows` public func buffer(interval: DispatchTimeInterval, timeshift: DispatchTimeInterval, context: Exec = .direct) -> Signal<[OutputValue]> { return buffer(windows: Signal.interval(timeshift, initial: .seconds(0), context: context).map { v in Signal<Void>.timer(interval: interval, context: context) }) } /// Implementation of map and filter. Essentially a flatMap but instead of flattening over child `Signal`s like the standard Reactive implementation, this flattens over child `Optional`s. /// /// - Parameters: /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: for each value emitted by `self`, outputs a new `Signal` /// - Returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream public func compact<U>() -> Signal<U> where OutputValue == Optional<U> { return transform() { (r: Result<Optional<U>, SignalEnd>) -> Signal<U>.Next in switch r { case .success(.some(let v)): return .value(v) case .success: return .none case .failure(let e): return .end(e) } } } /// Implementation of map and filter. Essentially a flatMap but instead of flattening over child `Signal`s like the standard Reactive implementation, this flattens over child `Optional`s. /// /// - Parameters: /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: for each value emitted by `self`, outputs a new `Signal` /// - Returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream public func compactMap<U>(context: Exec = .direct, _ processor: @escaping (OutputValue) throws -> U?) -> Signal<U> { return transform(context: context) { (r: Result<OutputValue, SignalEnd>) -> Signal<U>.Next in switch r { case .success(let v): do { if let u = try processor(v) { return .value(u) } return .none } catch { return .end(.other(error)) } case .failure(let e): return .end(e) } } } /// Implementation of map and filter. Essentially a flatMap but instead of flattening over child `Signal`s like the standard Reactive implementation, this flattens over child `Optional`s. /// /// - Parameters: /// - initialState: an initial value for a state parameter that will be passed to the processor on each iteration. /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: for each value emitted by `self`, outputs a new `Signal` /// - Returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream public func compactMap<S, U>(initialState: S, context: Exec = .direct, _ processor: @escaping (inout S, OutputValue) throws -> U?) -> Signal<U> { return transform(initialState: initialState, context: context) { (s: inout S, r: Result<OutputValue, SignalEnd>) -> Signal<U>.Next in switch r { case .success(let v): do { if let u = try processor(&s, v) { return .value(u) } return .none } catch { return .end(.other(error)) } case .failure(let e): return .end(e) } } } /// An implementation of compactMap that allows the "activation" values of the sequence to be mapped using a different function. /// /// - Parameters: /// - select: chooses which parts of the activation sequence (first value, last value or all values) should be passed through the `activation` function (NOTE: if `.last` is used, all but the most recent value is discarded). Default: `.all` /// - context: the `Exec` where `activation` will be evaluated (default: .direct). /// - activation: processing closure for activation values /// - remainder: processing closure for all `normal` values (and activation values after the first, if `.first` is passed as the `select` argument) /// - Returns: a `Signal` where all the activation values have been transformed by `activation` and all other values have been transformed by `remained`. Any error is emitted in the output without change. public func compactMapActivation<U>(select: SignalActivationSelection = .all, context: Exec = .direct, activation: @escaping (OutputValue) throws -> U?, remainder: @escaping (OutputValue) throws -> U?) -> Signal<U> { let preceeding: Signal<OutputValue> if case .all = select { preceeding = self.signal } else { preceeding = self.capture().resume(resend: select) } return preceeding.transformActivation( context: context, activation: { result in switch result { case .success(let v): do { if let u = try activation(v) { return .value(u) } return .none } catch { return .end(.other(error)) } case .failure(let e): return .end(e) } } ) { result in switch result { case .success(let v): do { if let u = try remainder(v) { return .value(u) } return .none } catch { return .end(.other(error)) } case .failure(let e): return .end(e) } } } /// A specialized implementation of `compactMapActivation` that processes only activation values (remaining values are simply passed through). A consequence is that input and output values must have the same type (unlike the unspecialized version which can map onto a different type). /// /// - Parameters: /// - select: chooses which parts of the activation sequence (first value, last value or all values) should be passed through the `activation` function (NOTE: if `.last` is used, all but the most recent value is discarded). Default: `.all`. /// - context: the `Exec` where `activation` will be evaluated (default: .direct). /// - activation: processing closure for activation values /// - Returns: a `Signal` where all the activation values have been transformed by `activation` and all other values have been transformed by `remained`. Any error is emitted in the output without change. public func compactMapActivation(select: SignalActivationSelection = .all, context: Exec = .direct, activation: @escaping (OutputValue) throws -> OutputValue?) -> Signal<OutputValue> { return compactMapActivation(select: select, context: context, activation: activation, remainder: { value in value }) } /// Implementation of [Reactive X operator "FlatMap"](http://reactivex.io/documentation/operators/flatmap.html) /// /// - Parameters: /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: for each value emitted by `self`, outputs a new `Signal` /// - Returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream public func flatten<Interface: SignalInterface>() -> Signal<Interface.OutputValue> where OutputValue == Interface { return transformFlatten(closePropagation: .errors) { (v: OutputValue, mergedInput: SignalMergedInput<Interface.OutputValue>) in mergedInput.add(v, closePropagation: .errors, removeOnDeactivate: true) } } /// Implementation of [Reactive X operator "FlatMap"](http://reactivex.io/documentation/operators/flatmap.html) /// /// - Parameters: /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: for each value emitted by `self`, outputs a new `Signal` /// - Returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream public func flatMap<Interface: SignalInterface>(context: Exec = .direct, _ processor: @escaping (OutputValue) throws -> Interface) -> Signal<Interface.OutputValue> { return transformFlatten(closePropagation: .errors, context: context) { (v: OutputValue, mergedInput: SignalMergedInput<Interface.OutputValue>) in mergedInput.add(try processor(v), closePropagation: .errors, removeOnDeactivate: true) } } /// Implementation of [Reactive X operator "FlatMapFirst"](http://reactivex.io/documentation/operators/flatmap.html) /// /// - Parameters: /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: for each value emitted by `self`, outputs a new `Signal` /// - Returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream public func flatMapFirst<Interface: SignalInterface>(context: Exec = .direct, _ processor: @escaping (OutputValue) throws -> Interface) -> Signal<Interface.OutputValue> { return transformFlatten(initialState: false, closePropagation: .errors, context: context) { (s: inout Bool, v: OutputValue, mergedInput: SignalMergedInput<Interface.OutputValue>) in if !s { mergedInput.add(try processor(v), closePropagation: .errors, removeOnDeactivate: true) s = true } } } /// Implementation of [Reactive X operator "FlatMapLatest"](http://reactivex.io/documentation/operators/flatmap.html) /// /// See also `switchLatest` /// /// - Parameters: /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: for each value emitted by `self`, outputs a new `Signal` /// - Returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream public func flatMapLatest<Interface: SignalInterface>(context: Exec = .direct, _ processor: @escaping (OutputValue) throws -> Interface) -> Signal<Interface.OutputValue> { return transformFlatten(initialState: nil, closePropagation: .errors, context: context) { (s: inout Signal<Interface.OutputValue>?, v: OutputValue, mergedInput: SignalMergedInput<Interface.OutputValue>) in if let existing = s { mergedInput.remove(existing) } let next = try processor(v).signal mergedInput.add(next, closePropagation: .errors, removeOnDeactivate: true) s = next } } /// Implementation of [Reactive X operator "FlatMap"](http://reactivex.io/documentation/operators/flatmap.html) /// /// - Parameters: /// - initialState: an initial value for a state parameter that will be passed to the processor on each iteration. /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: for each value emitted by `self`, outputs a new `Signal` /// - Returns: a signal where every value from every `Signal` output by `processor` is merged into a single stream public func flatMap<Interface: SignalInterface, V>(initialState: V, context: Exec = .direct, _ processor: @escaping (inout V, OutputValue) throws -> Interface) -> Signal<Interface.OutputValue> { return transformFlatten(initialState: initialState, closePropagation: .errors, context: context) { (s: inout V, v: OutputValue, mergedInput: SignalMergedInput<Interface.OutputValue>) in mergedInput.add(try processor(&s, v), closePropagation: .errors, removeOnDeactivate: true) } } /// Implementation of [Reactive X operator "ConcatMap"](http://reactivex.io/documentation/operators/flatmap.html) /// /// - Parameters: /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: for each value emitted by `self`, outputs a new `Signal` /// - Returns: a signal where every value from every `Signal` output by `processor` is serially concatenated into a single stream public func concatMap<Interface: SignalInterface>(context: Exec = .direct, _ processor: @escaping (OutputValue) throws -> Interface) -> Signal<Interface.OutputValue> { return transformFlatten(initialState: 0, closePropagation: .errors, context: context) { (index: inout Int, v: OutputValue, mergedInput: SignalMergedInput<(Int, Result<Interface.OutputValue, SignalEnd>)>) in mergedInput.add(try processor(v).transform { (r: Result<Interface.OutputValue, SignalEnd>) -> Signal<Result<Interface.OutputValue, SignalEnd>>.Next in switch r { case .success: return .value(r) case .failure(let e): return .value(r, end: e) } }.map { [index] (r: Result<Interface.OutputValue, SignalEnd>) -> (Int, Result<Interface.OutputValue, SignalEnd>) in (index, r) }, closePropagation: .errors, removeOnDeactivate: true) index += 1 }.transform(initialState: (0, Array<Array<Result<Interface.OutputValue, SignalEnd>>>())) { (state: inout (completed: Int, buffers: Array<Array<Result<Interface.OutputValue, SignalEnd>>>), result: Result<(Int, Result<Interface.OutputValue, SignalEnd>), SignalEnd>) -> Signal<Interface.OutputValue>.Next in switch result { case .success((let index, .success(let v))): // We can send results for the first incomplete signal without buffering if index == state.completed { return .value(v) } else { // Make sure we have enough buffers while index >= state.buffers.count { state.buffers.append([]) } // Buffer the result state.buffers[index].append(Result<Interface.OutputValue, SignalEnd>.success(v)) return .none } case .success((let index, .failure(let e))): // If its an error, try to send some more buffers if index == state.completed { state.completed += 1 var results = [Signal<Interface.OutputValue>.Result]() for i in state.completed..<state.buffers.count { for j in state.buffers[i] where !j.isFailure { results.append(j) } let incomplete = state.buffers[i].last?.isFailure != true state.buffers[i].removeAll() if incomplete { break } state.completed += 1 } return .array(results) } else { // If we're not up to that buffer, just record the error state.buffers[index].append(Result<Interface.OutputValue, SignalEnd>.failure(e)) return .none } case .failure(let error): return .end(error) } } } /// Implementation of [Reactive X operator "GroupBy"](http://reactivex.io/documentation/operators/groupby.html) /// /// - Parameters: /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: for each value emitted by `self`, outputs the "key" for the output `Signal` /// - Returns: a parent `Signal` where values are tuples of a "key" and a child `Signal` that will contain all values from `self` associated with that "key". public func groupBy<U: Hashable>(context: Exec = .direct, _ processor: @escaping (OutputValue) throws -> U) -> Signal<(U, Signal<OutputValue>)> { return self.transform(initialState: Dictionary<U, SignalInput<OutputValue>>(), context: context) { (outputs: inout Dictionary<U, SignalInput<OutputValue>>, r: Result<OutputValue, SignalEnd>) -> Signal<(U, Signal<OutputValue>)>.Next in switch r { case .success(let v): do { let u = try processor(v) if let o = outputs[u] { o.send(value: v) return .none } else { let (input, preCachedSignal) = Signal<OutputValue>.create() let s = preCachedSignal.cacheUntilActive() input.send(value: v) outputs[u] = input return .value((u, s)) } } catch { return .error(error) } case .failure(let e): outputs.forEach { tuple in tuple.value.send(end: e) } return .end(e) } } } /// Implementation of [Reactive X operator "Map"](http://reactivex.io/documentation/operators/map.html) /// /// - Parameters: /// - keyPath: selects a child value to emit /// - Returns: a `Signal` where all the values have been transformed by the key path. public func keyPath<U>(_ keyPath: KeyPath<OutputValue, U>) -> Signal<U> { return transform { (r: Result<OutputValue, SignalEnd>) -> Signal<U>.Next in switch r { case .success(let v): return .value(v[keyPath: keyPath]) case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "Map"](http://reactivex.io/documentation/operators/map.html) /// /// - Parameters: /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: for each value emitted by `self`, outputs a value for the output `Signal` /// - Returns: a `Signal` where all the values have been transformed by the `processor`. Any error is emitted in the output without change. public func map<U>(context: Exec = .direct, _ processor: @escaping (OutputValue) throws -> U) -> Signal<U> { return transform(context: context) { (r: Result<OutputValue, SignalEnd>) -> Signal<U>.Next in switch r { case .success(let v): return .single(Result<U, Error> { try processor(v) }.mapError(SignalEnd.other)) case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "Map"](http://reactivex.io/documentation/operators/map.html) /// /// - Parameters: /// - initialState: an initial value for a state parameter that will be passed to the processor on each iteration. /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: for each value emitted by `self`, outputs a value for the output `Signal` /// - Returns: a `Signal` where all the values have been transformed by the `processor`. Any error is emitted in the output without change. public func map<U, V>(initialState: V, context: Exec = .direct, _ processor: @escaping (inout V, OutputValue) throws -> U) -> Signal<U> { return transform(initialState: initialState, context: context) { (s: inout V, r: Result<OutputValue, SignalEnd>) -> Signal<U>.Next in switch r { case .success(let v): return .single(Result<U, Error> { try processor(&s, v) }.mapError(SignalEnd.other)) case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "Map"](http://reactivex.io/documentation/operators/map.html) that offers a separate transformation for "activation" values. /// /// - Parameters: /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - activation: processing closure for activation values /// - remainder: processing closure for all normal (non-activation) values /// - Returns: a `Signal` where all the activation values have been transformed by `activation` and all other values have been transformed by `remained`. Any error is emitted in the output without change. public func mapActivation<U>(select: SignalActivationSelection, context: Exec = .direct, activation: @escaping (OutputValue) throws -> U, remainder: @escaping (OutputValue) throws -> U) -> Signal<U> { return compactMapActivation(select: select, context: context, activation: activation, remainder: remainder) } /// Implementation of [Reactive X operator "Map"](http://reactivex.io/documentation/operators/map.html) /// /// - Parameters: /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: used to transform the closing error /// - Returns: when an error is emitted from `self`, emits the result returned from passing that error into `processor`. All values emitted normally. public func mapErrors(context: Exec = .direct, _ processor: @escaping (SignalEnd) -> SignalEnd) -> Signal<OutputValue> { return transform(context: context) { (r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(let v): return .value(v) case .failure(let e): return .end(processor(e)) } } } /// Implementation of [Reactive X operator "Scan"](http://reactivex.io/documentation/operators/scan.html) /// /// See also: `Signal.reduce` which returns a `SignalMulti` and whose processor has the signature `(inout U, OutputValue) -> Void` to make in-place transformations easier. /// See also: `aggregate` which performs the equivalent of scan over the entire sequence before emitting a single value. /// /// - Parameters: /// - initialState: an initial value for a state parameter that will be passed to the processor on each iteration. /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: takes the most recently emitted value and the most recent value from `self` and returns the next emitted value /// - Returns: a `Signal` where the result from each invocation of `processor` are emitted public func scan<U>(initialState: U, context: Exec = .direct, _ processor: @escaping (U, OutputValue) throws -> U) -> Signal<U> { return transform(initialState: initialState, context: context) { (accumulated: inout U, r: Result<OutputValue, SignalEnd>) -> Signal<U>.Next in switch r { case .success(let v): do { accumulated = try processor(accumulated, v) return .value(accumulated) } catch { return .error(error) } case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "Window"](http://reactivex.io/documentation/operators/window.html) for non-overlapping/no-gap buffers. /// /// - Note: equivalent to "buffer" method with same parameters /// /// - Parameter boundaries: when this `Signal` sends a value, the buffer is emitted and cleared /// - Returns: a signal where the values are arrays of values from `self`, accumulated according to `boundaries` public func window<Interface: SignalInterface>(boundaries: Interface) -> Signal<Signal<OutputValue>> { return combine(boundaries, initialState: nil) { (current: inout SignalInput<OutputValue>?, cr: EitherResult2<OutputValue, Interface.OutputValue>) -> Signal<Signal<OutputValue>>.Next in switch cr { case .result1(.success(let v)): if let c = current { c.send(value: v) return .none } else { let (i, s) = Signal<OutputValue>.create() current = i return .value(s.cacheUntilActive(precached: [v])) } case .result1(.failure(let e)): return .end(e) case .result2(.success): _ = current?.complete() current = nil return .none case .result2(.failure(let e)): return .end(e) } } } /// Implementation of [Reactive X operator "Window"](http://reactivex.io/documentation/operators/window.html) for buffers with overlap or gaps between. /// /// - Note: equivalent to "buffer" method with same parameters /// /// - Parameter windows: a "windows" signal (one that describes a series of times and durations). Each value `Signal` in the stream starts a new buffer and when the value `Signal` closes, the buffer is emitted. /// - Returns: a signal where the values are arrays of values from `self`, accumulated according to `windows` public func window<Interface: SignalInterface>(windows: Interface) -> Signal<Signal<OutputValue>> where Interface.OutputValue: SignalInterface { return combine(windows.valueDurations { s in s }, initialState: [Int: SignalInput<OutputValue>]()) { (children: inout [Int: SignalInput<OutputValue>], cr: EitherResult2<OutputValue, (Int, Interface.OutputValue?)>) -> Signal<Signal<OutputValue>>.Next in switch cr { case .result1(.success(let v)): for index in children.keys { if let c = children[index] { c.send(value: v) } } return .none case .result1(.failure(let e)): return .end(e) case .result2(.success((let index, .some))): let (i, s) = Signal<OutputValue>.create() children[index] = i return .value(s) case .result2(.success((let index, .none))): if let c = children[index] { c.complete() children.removeValue(forKey: index) } return .none case .result2(.failure(let e)): return .end(e) } } } /// Implementation of [Reactive X operator "Window"](http://reactivex.io/documentation/operators/window.html) for buffers of fixed length and a fixed number of values separating starts. /// /// - Note: equivalent to "buffer" method with same parameters /// /// - Parameters: /// - count: the number of separate values to accumulate before emitting an array of values /// - skip: the stride between the start of each new buffer (can be smaller than `count`, resulting in overlapping buffers) /// - Returns: a signal where the values are arrays of length `count` of values from `self`, with start values separated by `skip` public func window(count: UInt, skip: UInt) -> Signal<Signal<OutputValue>> { let multi = multicast() // Create the two listeners to the "multi" signal carefully so that the window signal is *first* (so it reaches the buffer before the value signal) let windowSignal = multi.stride(count: Int(skip)).map { v in // `count - 1` is the index of the count-th element but since `valuesSignal` will resolve before this, we need to fire 1 element sooner, hence `count - 2` multi.elementAt(count - 2).ignoreElements(outputType: OutputValue.self) } return multi.window(windows: windowSignal) } /// Implementation of [Reactive X operator "Window"](http://reactivex.io/documentation/operators/window.html) for non-overlapping, periodic buffer start times and possibly limited buffer sizes. /// /// - Note: equivalent to "buffer" method with same parameters /// /// - Parameters: /// - interval: the number of seconds between the start of each buffer /// - count: the number of separate values to accumulate before emitting an array of values /// - continuous: if `true` (default), the `timeshift` periodic timer runs continuously (empty buffers may be emitted if a timeshift elapses without any source signals). If `false`, the periodic timer does start until the first value is received from the source and the periodic timer is paused when a buffer is emitted. /// - context: context where the timer will run /// - Returns: a signal where the values are arrays of values from `self`, accumulated according to `windows` public func window(interval: DispatchTimeInterval, count: Int = Int.max, continuous: Bool = true, context: Exec = .direct) -> Signal<Signal<OutputValue>> { let multi = multicast() // Create the two listeners to the "multi" signal carefully so that the raw signal is *first* (so it reaches the buffer before the boundary signal) let valuesSignal = multi.map { v in v } let boundarySignal = multi.timedCountedBoundary(interval: interval, count: count, continuous: continuous, context: context) return valuesSignal.window(boundaries: boundarySignal) } /// Implementation of [Reactive X operator "Window"](http://reactivex.io/documentation/operators/window.html) for non-overlapping buffers of fixed length. /// /// - Note: this is just a convenience wrapper around `buffer(count:skip:behavior)` where `skip` equals `count`. /// - Note: equivalent to "buffer" method with same parameters /// /// - Parameter count: the number of separate values to accumulate before emitting an array of values /// - Returns: a signal where the values are arrays of values from `self`, accumulated according to `count` public func window(count: UInt) -> Signal<Signal<OutputValue>> { return window(count: count, skip: count) } /// Implementation of [Reactive X operator "Window"](http://reactivex.io/documentation/operators/window.html) for periodic buffer start times and fixed duration buffers. /// /// - Note: this is just a convenience wrapper around `buffer(windows:behaviors)` where the `windows` signal contains `timerSignal` signals contained in a `Signal.interval` signal. /// - Note: equivalent to "buffer" method with same parameters /// /// - Parameters: /// - interval: the duration of each buffer, in seconds /// - timeshift: the number of seconds between the start of each buffer (if smaller than `interval`, buffers will overlap). /// - context: context where the timer will run /// - Returns: a signal where the values are arrays of values from `self`, accumulated according to `windows` public func window(interval: DispatchTimeInterval, timeshift: DispatchTimeInterval, context: Exec = .direct) -> Signal<Signal<OutputValue>> { return window(windows: Signal.interval(timeshift, initial: .seconds(0), context: context).map { v in Signal<Void>.timer(interval: interval, context: context) }) } /// Implementation of [Reactive X operator "Debounce"](http://reactivex.io/documentation/operators/debounce.html) /// /// - Parameters: /// - interval: the duration over which to drop values. /// - flushOnClose: if true, then any buffered value is sent before closing, if false (default) then the buffered value is discarded when a close occurs /// - context: context where the timer will run /// - Returns: a signal where values are emitted after a `interval` but only if no another value occurs during that `interval`. public func debounce(interval: DispatchTimeInterval, flushOnClose: Bool = false, context: Exec = .direct) -> Signal<OutputValue> { let serialContext = context.serialized() let (mergedInput, signal) = Signal<OutputValue>.createMergedInput() let intermediate = transform(initialState: nil, context: serialContext) { (timer: inout Signal<OutputValue>?, result: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch result { case .success(let v): if let oldTimer = timer { mergedInput.remove(oldTimer) } let newTimer = Signal<OutputValue>.timer(interval: interval, value: v, context: serialContext) mergedInput.add(newTimer, closePropagation: .none, removeOnDeactivate: true) timer = newTimer return .none case .failure(let e): return .end(e) } } mergedInput.add(intermediate, closePropagation: .all, removeOnDeactivate: false) return signal } /// Implementation of [Reactive X operator "throttleFirst"](http://reactivex.io/documentation/operators/sample.html) /// /// - Note: this is largely the reverse of `debounce`. /// /// - Parameters: /// - interval: the duration over which to drop values. /// - context: context where the timer will run /// - Returns: a signal where a timer is started when a value is received and emitted and further values received within that `interval` will be dropped. public func throttleFirst(interval: DispatchTimeInterval, context: Exec = .direct) -> Signal<OutputValue> { let timerQueue = context.serialized() var timer: Lifetime? = nil return transform(initialState: nil, context: timerQueue) { (cleanup: inout OnDelete?, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in cleanup = cleanup ?? OnDelete { timer = nil } switch r { case .failure(let e): return .end(e) case .success(let v) where timer == nil: timer = timerQueue.singleTimer(interval: interval) { timer = nil } return .value(v) case .success: return .none } } } } extension SignalInterface where OutputValue: Hashable { /// Implementation of [Reactive X operator "distinct"](http://reactivex.io/documentation/operators/distinct.html) /// /// - Returns: a signal where all values received are remembered and only values not previously received are emitted. public func distinct() -> Signal<OutputValue> { return transform(initialState: Set<OutputValue>()) { (previous: inout Set<OutputValue>, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(let v): if !previous.contains(v) { previous.insert(v) return .value(v) } return .none case .failure(let e): return .end(e) } } } } extension SignalInterface where OutputValue: Equatable { /// Implementation of [Reactive X operator "distinct"](http://reactivex.io/documentation/operators/distinct.html) /// /// - Returns: a signal that emits the first value but then emits subsequent values only when they are different to the previous value. public func distinctUntilChanged() -> Signal<OutputValue> { return transform(initialState: nil) { (previous: inout OutputValue?, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(let v): if previous != v { previous = v return .value(v) } return .none case .failure(let e): return .end(e) } } } } extension SignalInterface { /// Implementation of [Reactive X operator "distinct"](http://reactivex.io/documentation/operators/distinct.html) /// /// - Parameters: /// - context: the `Exec` where `comparator` will be evaluated (default: .direct). /// - comparator: a function taking two parameters (the previous and current value in the signal) which should return `false` to indicate the current value should be emitted. /// - Returns: a signal that emits the first value but then emits subsequent values only if the function `comparator` returns `false` when passed the previous and current values. public func distinctUntilChanged(context: Exec = .direct, compare: @escaping (OutputValue, OutputValue) throws -> Bool) -> Signal<OutputValue> { return transform(initialState: nil) { (previous: inout OutputValue?, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(let v): do { if let p = previous, try compare(p, v) { previous = v return .none } else { previous = v return .value(v) } } catch { return .error(error) } case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "elementAt"](http://reactivex.io/documentation/operators/elementat.html) /// /// - Parameter index: identifies the element to be emitted. /// - Returns: a signal that emits the zero-indexed element identified by `index` and then closes. public func elementAt(_ index: UInt) -> Signal<OutputValue> { return transform(initialState: 0, context: .direct) { (curr: inout UInt, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(let v) where curr == index: return .value(v, end: .complete) case .success: curr += 1 return .none case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "filter"](http://reactivex.io/documentation/operators/filter.html) /// /// - Parameters: /// - context: the `Exec` where `matching` will be evaluated (default: .direct). /// - matching: a function which is passed the current value and should return `true` to indicate the value should be emitted. /// - Returns: a signal that emits received values only if the function `matching` returns `true` when passed the value. public func filter(context: Exec = .direct, matching: @escaping (OutputValue) throws -> Bool) -> Signal<OutputValue> { return transform(context: context) { (r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in do { switch r { case .success(let v) where try matching(v): return .value(v) case .success: return .none case .failure(let e): return .end(e) } } catch { return .error(error) } } } /// Implementation of [Reactive X operator "ofType"](http://reactivex.io/documentation/operators/filter.html) /// /// - Parameters: /// - type: values will be filtered to this type (NOTE: only the *static* type of this parameter is considered – if the runtime type is more specific, that will be ignored). /// - Returns: a signal that emits received values only if the value can be dynamically cast to the type `U`, specified statically by `type`. public func ofType<U>(_ type: U.Type) -> Signal<U> { return self.transform(initialState: 0) { (curr: inout Int, r: Result<OutputValue, SignalEnd>) -> Signal<U>.Next in switch r { case .success(let v as U): return .value(v) case .success: return .none case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "first"](http://reactivex.io/documentation/operators/first.html) /// /// - Parameters: /// - context: the `Exec` where `matching` will be evaluated (default: .direct). /// - matching: run for each value until it returns `true` /// - Returns: a signal that, when an error is received, emits the first value (if any) in the signal where `matching` returns `true` when invoked with the value, followed by the error. public func first(context: Exec = .direct, matching: @escaping (OutputValue) throws -> Bool = { _ in true }) -> Signal<OutputValue> { return transform(context: context) { (r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in do { switch r { case .success(let v) where try matching(v): return .value(v, end: .complete) case .success: return .none case .failure(let e): return .end(e) } } catch { return .error(error) } } } /// Implementation of [Reactive X operator "single"](http://reactivex.io/documentation/operators/first.html) /// /// - Parameters: /// - context: the `Exec` where `matching` will be evaluated (default: .direct). /// - matching: run for each value /// - Returns: a signal that, if a single value in the sequence, when passed to `matching` returns `true`, then that value will be returned, followed by a SignalEnd.complete when the input signal closes (otherwise a SignalEnd.complete will be emitted without emitting any prior values). public func single(context: Exec = .direct, matching: @escaping (OutputValue) throws -> Bool = { _ in true }) -> Signal<OutputValue> { return transform(initialState: nil, context: context) { (state: inout (firstMatch: OutputValue, unique: Bool)?, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in do { switch r { case .success(let v) where try matching(v): if let s = state { state = (firstMatch: s.firstMatch, unique: false) } else { state = (firstMatch: v, unique: true) } return .none case .success: return .none case .failure(let e): if let s = state, s.unique == true { return .value(s.firstMatch, end: e) } else { return .end(e) } } } catch { return .error(error) } } } /// Implementation of [Reactive X operator "ignoreElements"](http://reactivex.io/documentation/operators/ignoreelements.html) /// /// - Returns: a signal that emits the input error, when received, otherwise ignores all values. public func ignoreElements<U>(outputType: U.Type = U.self) -> Signal<U> { return transform { (r: Result<OutputValue, SignalEnd>) -> Signal<U>.Next in if case .failure(let e) = r { return .end(e) } else { return .none } } } /// Implementation of [Reactive X operator "last"](http://reactivex.io/documentation/operators/last.html) /// /// - Parameters: /// - context: the `Exec` where `matching` will be evaluated (default: .direct). /// - matching: run for each value /// - Returns: a signal that, when an error is received, emits the last value (if any) in the signal where `matching` returns `true` when invoked with the value, followed by the error. public func last(context: Exec = .direct, matching: @escaping (OutputValue) throws -> Bool = { _ in true }) -> Signal<OutputValue> { return transform(initialState: nil, context: context) { (last: inout OutputValue?, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in do { switch r { case .success(let v) where try matching(v): last = v return .none case .success: return .none case .failure(let e): if let l = last { return .value(l, end: e) } else { return .end(e) } } } catch { return .error(error) } } } /// Implementation of [Reactive X operator "sample"](http://reactivex.io/documentation/operators/sample.html) /// /// See also: `debounce` is the equivalent where the sampling interval is time based /// See also: `withLatestFrom` always emits, even when the sampled signal hasn't emitted another value during the interval /// /// - Parameter trigger: instructs the result to emit the last value from `self` /// - Returns: a signal that, when a value is received from `trigger`, emits the last value (if any) received from `self`. public func sample<Interface: SignalInterface>(_ trigger: Interface) -> Signal<OutputValue> { return combine(trigger, initialState: nil, context: .direct) { (last: inout OutputValue?, c: EitherResult2<OutputValue, Interface.OutputValue>) -> Signal<OutputValue>.Next in switch (c, last) { case (.result1(.success(let v)), _): last = v return .none case (.result1(.failure(let e)), _): return .end(e) case (.result2(.success), .some(let l)): last = nil return .value(l) case (.result2(.success), _): return .none case (.result2(.failure(let e)), _): return .end(e) } } } /// Implementation of [Reactive X operator "sample"](http://reactivex.io/documentation/operators/sample.html) /// /// - Parameter trigger: instructs the result to emit the last value from `self` /// - Returns: a signal that, when a value is received from `trigger`, emits the last value (if any) received from `self`. public func throttleFirst<Interface: SignalInterface>(_ trigger: Interface) -> Signal<OutputValue> { return combine(trigger, initialState: nil, context: .direct) { (last: inout OutputValue?, c: EitherResult2<OutputValue, Interface.OutputValue>) -> Signal<OutputValue>.Next in switch (c, last) { case (.result1(.success(let v)), nil): last = v return .none case (.result1(.success), _): return .none case (.result1(.failure(let e)), _): return .end(e) case (.result2(.success), .some(let l)): last = nil return .value(l) case (.result2(.success), _): return .none case (.result2(.failure(let e)), _): return .end(e) } } } /// Implementation of [Reactive X operator "skip"](http://reactivex.io/documentation/operators/skip.html) /// /// - Parameter count: the number of values from the start of `self` to drop /// - Returns: a signal that drops `count` values from `self` then mirrors `self`. public func skip(_ count: Int) -> Signal<OutputValue> { return transform(initialState: 0) { (progressCount: inout Int, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(let v) where progressCount >= count: return .value(v) case .success: progressCount = progressCount + 1 return .none case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "skipLast"](http://reactivex.io/documentation/operators/skiplast.html) /// /// - Parameter count: the number of values from the end of `self` to drop /// - Returns: a signal that buffers `count` values from `self` then for each new value received from `self`, emits the oldest value in the buffer. When `self` closes, all remaining values in the buffer are discarded. public func skipLast(_ count: Int) -> Signal<OutputValue> { return transform(initialState: Array<OutputValue>()) { (buffer: inout Array<OutputValue>, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(let v): buffer.append(v) if buffer.count > count { return .value(buffer.removeFirst()) } else { return .none } case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "skip"](http://reactivex.io/documentation/operators/skip.html) /// /// - Parameter count: the number of values from the start of `self` to emit /// - Returns: a signal that emits `count` values from `self` then closes. public func take(_ count: Int) -> Signal<OutputValue> { return transform(initialState: 0) { (progressCount: inout Int, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in progressCount = progressCount + 1 switch r { case .success(let v) where progressCount >= count: return .value(v, end: .complete) case .success(let v): return .value(v) case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "skipLast"](http://reactivex.io/documentation/operators/skiplast.html) /// /// - Parameter count: the number of values from the end of `self` to emit /// - Returns: a signal that buffers `count` values from `self` then for each new value received from `self`, drops the oldest value in the buffer. When `self` closes, all values in the buffer are emitted, followed by the close. public func takeLast(_ count: Int) -> Signal<OutputValue> { return transform(initialState: Array<OutputValue>()) { (buffer: inout Array<OutputValue>, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(let v): buffer.append(v) if buffer.count > count { buffer.removeFirst() } return .none case .failure(let e): return .values(sequence: buffer, end: e) } } } } extension SignalInterface { /// - Note: the [Reactive X operators "And", "Then" and "When"](http://reactivex.io/documentation/operators/and-then-when.html) are considered unnecessary, given the slightly different implementation of `CwlSignal.Signal.zip` which produces tuples (rather than producing a non-structural type) and is hence equivalent to `and`+`then`. } extension SignalInterface { /// Implementation similar to [Reactive X operator "sample"](http://reactivex.io/documentation/operators/sample.html) except that the output is sent every time self emits, not just when sample has changed since self last emitted. /// /// See also: `combineLatest`, `sample` and `throttleFirst` which have similar but slightly different emitting scenarios. /// /// - Parameter sample: the latest value from this signal will be emitted whenever `self` emits /// - Returns: a signal that emits the latest value from `sample` each time `self` emits public func withLatestFrom<Interface: SignalInterface>(_ sample: Interface) -> Signal<Interface.OutputValue> { return combine(sample, initialState: nil, context: .direct) { (last: inout Interface.OutputValue?, c: EitherResult2<OutputValue, Interface.OutputValue>) -> Signal<Interface.OutputValue>.Next in switch (c, last) { case (.result1(.success), .some(let l)): return .value(l) case (.result1(.success), _): return .none case (.result1(.failure(let e)), _): return .end(e) case (.result2(.success(let v)), _): last = v return .none case (.result2(.failure(let e)), _): return .end(e) } } } /// Implementation similar to [Reactive X operator "sample"](http://reactivex.io/documentation/operators/sample.html) except that a function is run to generate the emitted value each time self emits. The function is passed the value emitted from `self` and the last emitted value from the `sample` signal parameter. /// /// See also: `combineLatest`, `sample` and `throttleFirst` which have similar but slightly different emitting scenarios. /// /// - Parameter sample: a signal whose latest value will be used each time `self` emits /// - Parameter processor: produces the outputs values /// - Returns: a signal that, when a value is received from `trigger`, emits the result or performing `processor`. public func withLatestFrom<Interface: SignalInterface, R>(_ sample: Interface, context: Exec = .direct, _ processor: @escaping (OutputValue, Interface.OutputValue) throws -> R) -> Signal<R> { return combine(sample, initialState: nil, context: context) { (last: inout Interface.OutputValue?, c: EitherResult2<OutputValue, Interface.OutputValue>) -> Signal<R>.Next in switch (c, last) { case (.result1(.success(let left)), .some(let right)): do { return .value(try processor(left, right)) } catch { return .error(error) } case (.result1(.success), _): return .none case (.result1(.failure(let e)), _): return .end(e) case (.result2(.success(let v)), _): last = v return .none case (.result2(.failure(let e)), _): return .end(e) } } } /// Implementation of [Reactive X operator "combineLatest"](http://reactivex.io/documentation/operators/combinelatest.html) for two observed signals. /// /// - Parameters: /// - second: an observed signal. /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: invoked with the most recent values of the observed signals (or nil if a signal has not yet emitted a value) when any of the observed signals emits a value /// - Returns: a signal that emits the values from the processor and closes when any of the observed signals closes public func combineLatestWith<U: SignalInterface, V>(_ second: U, context: Exec = .direct, _ processor: @escaping (OutputValue, U.OutputValue) throws -> V) -> Signal<V> { return combine(second, initialState: (nil, nil), context: context) { (state: inout (OutputValue?, U.OutputValue?), r: EitherResult2<OutputValue, U.OutputValue>) -> Signal<V>.Next in switch r { case .result1(.success(let v)): state = (v, state.1) case .result2(.success(let v)): state = (state.0, v) case .result1(.failure(let e)): return .end(e) case .result2(.failure(let e)): return .end(e) } if let v0 = state.0, let v1 = state.1 { do { return .value(try processor(v0, v1)) } catch { return .error(error) } } else { return .none } } } @available(*, deprecated, message:"Renamed to combineLatestWith. Alternately, use static combineLatest function.") public func combineLatest<U: SignalInterface, V>(_ second: U, context: Exec = .direct, _ processor: @escaping (OutputValue, U.OutputValue) throws -> V) -> Signal<V> { return combineLatestWith(second, context: context, processor) } public static func combineLatest<U: SignalInterface, V>(_ first: Self, _ second: U, context: Exec = .direct, _ processor: @escaping (OutputValue, U.OutputValue) throws -> V) -> Signal<V> { return first.combineLatestWith(second, context: context, processor) } /// Implementation of [Reactive X operator "combineLatest"](http://reactivex.io/documentation/operators/combinelatest.html) for three observed signals. /// /// - Parameters: /// - second: an observed signal. /// - third: an observed signal. /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: invoked with the most recent values of the observed signals (or nil if a signal has not yet emitted a value) when any of the observed signals emits a value /// - Returns: a signal that emits the values from the processor and closes when any of the observed signals closes public func combineLatestWith<U: SignalInterface, V: SignalInterface, W>(_ second: U, _ third: V, context: Exec = .direct, _ processor: @escaping (OutputValue, U.OutputValue, V.OutputValue) throws -> W) -> Signal<W> { return combine(second, third, initialState: (nil, nil, nil), context: context) { (state: inout (OutputValue?, U.OutputValue?, V.OutputValue?), r: EitherResult3<OutputValue, U.OutputValue, V.OutputValue>) -> Signal<W>.Next in switch r { case .result1(.success(let v)): state = (v, state.1, state.2) case .result2(.success(let v)): state = (state.0, v, state.2) case .result3(.success(let v)): state = (state.0, state.1, v) case .result1(.failure(let e)): return .end(e) case .result2(.failure(let e)): return .end(e) case .result3(.failure(let e)): return .end(e) } if let v0 = state.0, let v1 = state.1, let v2 = state.2 { do { return .value(try processor(v0, v1, v2)) } catch { return .error(error) } } else { return .none } } } @available(*, deprecated, message:"Renamed to combineLatestWith. Alternately, use static combineLatest function.") public func combineLatest<U: SignalInterface, V: SignalInterface, W>(_ second: U, _ third: V, context: Exec = .direct, _ processor: @escaping (OutputValue, U.OutputValue, V.OutputValue) throws -> W) -> Signal<W> { return combineLatestWith(second, third, context: context, processor) } public static func combineLatest<U: SignalInterface, V: SignalInterface, W>(_ first: Self, _ second: U, _ third: V, context: Exec = .direct, _ processor: @escaping (OutputValue, U.OutputValue, V.OutputValue) throws -> W) -> Signal<W> { return first.combineLatestWith(second, third, context: context, processor) } /// Implementation of [Reactive X operator "combineLatest"](http://reactivex.io/documentation/operators/combinelatest.html) for four observed signals. /// /// - Note: support for multiple listeners and reactivation is determined by the specified `behavior`. /// /// - Parameters: /// - second: an observed signal. /// - third: an observed signal. /// - fourth: an observed signal. /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: invoked with the most recent values of the observed signals (or nil if a signal has not yet emitted a value) when any of the observed signals emits a value /// - Returns: a signal that emits the values from the processor and closes when any of the observed signals closes public func combineLatestWith<U: SignalInterface, V: SignalInterface, W: SignalInterface, X>(_ second: U, _ third: V, _ fourth: W, context: Exec = .direct, _ processor: @escaping (OutputValue, U.OutputValue, V.OutputValue, W.OutputValue) throws -> X) -> Signal<X> { return combine(second, third, fourth, initialState: (nil, nil, nil, nil), context: context) { (state: inout (OutputValue?, U.OutputValue?, V.OutputValue?, W.OutputValue?), r: EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>) -> Signal<X>.Next in switch r { case .result1(.success(let v)): state = (v, state.1, state.2, state.3) case .result2(.success(let v)): state = (state.0, v, state.2, state.3) case .result3(.success(let v)): state = (state.0, state.1, v, state.3) case .result4(.success(let v)): state = (state.0, state.1, state.2, v) case .result1(.failure(let e)): return .end(e) case .result2(.failure(let e)): return .end(e) case .result3(.failure(let e)): return .end(e) case .result4(.failure(let e)): return .end(e) } if let v0 = state.0, let v1 = state.1, let v2 = state.2, let v3 = state.3 { do { return .value(try processor(v0, v1, v2, v3)) } catch { return .error(error) } } else { return .none } } } @available(*, deprecated, message:"Renamed to combineLatestWith. Alternately, use static combineLatest function.") public func combineLatest<U: SignalInterface, V: SignalInterface, W: SignalInterface, X>(_ second: U, _ third: V, _ fourth: W, context: Exec = .direct, _ processor: @escaping (OutputValue, U.OutputValue, V.OutputValue, W.OutputValue) throws -> X) -> Signal<X> { return combineLatestWith(second, third, fourth, context: context, processor) } public static func combineLatest<U: SignalInterface, V: SignalInterface, W: SignalInterface, X>(_ first: Self, _ second: U, _ third: V, _ fourth: W, context: Exec = .direct, _ processor: @escaping (OutputValue, U.OutputValue, V.OutputValue, W.OutputValue) throws -> X) -> Signal<X> { return first.combineLatestWith(second, third, fourth, context: context, processor) } /// Implementation of [Reactive X operator "combineLatest"](http://reactivex.io/documentation/operators/combinelatest.html) for five observed signals. /// /// - Note: support for multiple listeners and reactivation is determined by the specified `behavior`. /// /// - Parameters: /// - second: an observed signal. /// - third: an observed signal. /// - fourth: an observed signal. /// - fifth: an observed signal. /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: invoked with the most recent values of the observed signals (or nil if a signal has not yet emitted a value) when any of the observed signals emits a value /// - Returns: a signal that emits the values from the processor and closes when any of the observed signals closes public func combineLatestWith<U: SignalInterface, V: SignalInterface, W: SignalInterface, X: SignalInterface, Y>(_ second: U, _ third: V, _ fourth: W, _ fifth: X, context: Exec = .direct, _ processor: @escaping (OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue) throws -> Y) -> Signal<Y> { return combine(second, third, fourth, fifth, initialState: (nil, nil, nil, nil, nil), context: context) { (state: inout (OutputValue?, U.OutputValue?, V.OutputValue?, W.OutputValue?, X.OutputValue?), r: EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>) -> Signal<Y>.Next in switch r { case .result1(.success(let v)): state = (v, state.1, state.2, state.3, state.4) case .result2(.success(let v)): state = (state.0, v, state.2, state.3, state.4) case .result3(.success(let v)): state = (state.0, state.1, v, state.3, state.4) case .result4(.success(let v)): state = (state.0, state.1, state.2, v, state.4) case .result5(.success(let v)): state = (state.0, state.1, state.2, state.3, v) case .result1(.failure(let e)): return .end(e) case .result2(.failure(let e)): return .end(e) case .result3(.failure(let e)): return .end(e) case .result4(.failure(let e)): return .end(e) case .result5(.failure(let e)): return .end(e) } if let v0 = state.0, let v1 = state.1, let v2 = state.2, let v3 = state.3, let v4 = state.4 { do { return .value(try processor(v0, v1, v2, v3, v4)) } catch { return .error(error) } } else { return .none } } } @available(*, deprecated, message:"Renamed to combineLatestWith. Alternately, use static combineLatest function.") public func combineLatest<U: SignalInterface, V: SignalInterface, W: SignalInterface, X: SignalInterface, Y>(_ second: U, _ third: V, _ fourth: W, _ fifth: X, context: Exec = .direct, _ processor: @escaping (OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue) throws -> Y) -> Signal<Y> { return combineLatestWith(second, third, fourth, fifth, context: context, processor) } public static func combineLatest<U: SignalInterface, V: SignalInterface, W: SignalInterface, X: SignalInterface, Y>(_ first: Self, _ second: U, _ third: V, _ fourth: W, _ fifth: X, context: Exec = .direct, _ processor: @escaping (OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue) throws -> Y) -> Signal<Y> { return first.combineLatestWith(second, third, fourth, fifth, context: context, processor) } public static func combineLatest<S: Sequence>(sequence: S) -> Signal<[OutputValue]> where S.Element: SignalInterface, OutputValue == S.Element.OutputValue { let array = Array(sequence) let count = array.count let indexed = Signal<OutputValue>.indexed(array) return indexed.transform(initialState: Array<OutputValue?>(repeating: nil, count: count)) { buffer, result in switch result { case .success((let offset, let element)): buffer[offset] = element let compacted = buffer.compactMap { $0 } guard compacted.count == count else { return .none } return .value(compacted) case .failure(let e): return .end(e) } } } public static func combineLatest<S: SignalInterface>(_ signals: S...) -> Signal<[OutputValue]> where OutputValue == S.OutputValue { return combineLatest(sequence: signals) } /// Implementation of [Reactive X operator "join"](http://reactivex.io/documentation/operators/join.html) /// /// - Parameters: /// - withRight: an observed signal /// - leftEnd: function invoked when a value is received from `self`. The resulting signal is observed and the time until signal close is treated as a duration "window" that started with the received `self` value. /// - rightEnd: function invoked when a value is received from `right`. The resulting signal is observed and the time until signal close is treated as a duration "window" that started with the received `right` value. /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: invoked with the corresponding `left` and `right` values when a `left` value is emitted during a `right`->`rightEnd` window or a `right` value is received during a `left`->`leftEnd` window /// - Returns: a signal that emits the values from the processor and closes when any of the last of the observed windows closes. public func intersect<U: SignalInterface, V: SignalInterface, W: SignalInterface, X>(withRight: U, leftEnd: @escaping (OutputValue) -> V, rightEnd: @escaping (U.OutputValue) -> W, context: Exec = .direct, _ processor: @escaping ((OutputValue, U.OutputValue)) -> X) -> Signal<X> { let leftDurations = valueDurations({ t in leftEnd(t).takeWhile { _ in false } }) let rightDurations = withRight.valueDurations({ u in rightEnd(u).takeWhile { _ in false } }) let a = leftDurations.combine(rightDurations, initialState: ([Int: OutputValue](), [Int: U.OutputValue]())) { (state: inout (activeLeft: [Int: OutputValue], activeRight: [Int: U.OutputValue]), cr: EitherResult2<(Int, OutputValue?), (Int, U.OutputValue?)>) -> Signal<(OutputValue, U.OutputValue)>.Next in switch cr { case .result1(.success((let leftIndex, .some(let leftValue)))): state.activeLeft[leftIndex] = leftValue return .array(state.activeRight.sorted { $0.0 < $1.0 }.map { tuple in .success((leftValue, tuple.value)) }) case .result2(.success((let rightIndex, .some(let rightValue)))): state.activeRight[rightIndex] = rightValue return .array(state.activeLeft.sorted { $0.0 < $1.0 }.map { tuple in .success((tuple.value, rightValue)) }) case .result1(.success((let leftIndex, .none))): state.activeLeft.removeValue(forKey: leftIndex) return .none case .result2(.success((let rightIndex, .none))): state.activeRight.removeValue(forKey: rightIndex) return .none default: return .complete() } } return a.map(context: context, processor) } /// Implementation of [Reactive X operator "groupJoin"](http://reactivex.io/documentation/operators/join.html) /// /// - Parameters: /// - withRight: an observed signal. /// - leftEnd: function invoked when a value is received from `self`. The resulting signal is observed and the time until signal close is treated as a duration "window" that started with the received `self` value. /// - rightEnd: function invoked when a value is received from `right`. The resulting signal is observed and the time until signal close is treated as a duration "window" that started with the received `right` value. /// - context: the `Exec` where `processor` will be evaluated (default: .direct). /// - processor: when a `left` value is received, this function is invoked with the `left` value and a `Signal` that will emit all the `right` values encountered until the `left`->`leftEnd` window closes. The value returned by this function will be emitted as part of the `Signal` returned from `groupIntersect`. /// - Returns: a signal that emits the values from the processor and closes when any of the last of the observed windows closes. public func groupIntersect<U: SignalInterface, V: SignalInterface, W: SignalInterface, X>(withRight: U, leftEnd: @escaping (OutputValue) -> V, rightEnd: @escaping (U.OutputValue) -> W, context: Exec = .direct, _ processor: @escaping ((OutputValue, Signal<U.OutputValue>)) -> X) -> Signal<X> { let leftDurations = valueDurations({ u in leftEnd(u).takeWhile { _ in false } }) let rightDurations = withRight.valueDurations({ u in rightEnd(u).takeWhile { _ in false } }) return leftDurations.combine(rightDurations, initialState: ([Int: SignalInput<U.OutputValue>](), [Int: U.OutputValue]())) { (state: inout (activeLeft: [Int: SignalInput<U.OutputValue>], activeRight: [Int: U.OutputValue]), cr: EitherResult2<(Int, OutputValue?), (Int, U.OutputValue?)>) -> Signal<(OutputValue, Signal<U.OutputValue>)>.Next in switch cr { case .result1(.success((let leftIndex, .some(let leftValue)))): let (li, ls) = Signal<U.OutputValue>.create() state.activeLeft[leftIndex] = li return .value((leftValue, ls.cacheUntilActive(precached: state.activeRight.sorted { $0.0 < $1.0 }.map { $0.value }))) case .result2(.success((let rightIndex, .some(let rightValue)))): state.activeRight[rightIndex] = rightValue state.activeLeft.sorted { $0.0 < $1.0 }.forEach { tuple in tuple.value.send(value: rightValue) } return .none case .result1(.success((let leftIndex, .none))): _ = state.activeLeft[leftIndex]?.complete() state.activeLeft.removeValue(forKey: leftIndex) return .none case .result2(.success((let rightIndex, .none))): state.activeRight.removeValue(forKey: rightIndex) return .none default: return .complete() } }.map(context: context, processor) } } extension Signal { /// Implementation of [Reactive X operator "merge"](http://reactivex.io/documentation/operators/merge.html) where the output closes only when the last source closes. /// /// - Parameter sources: a variable parameter list of `Signal<OutputValue>` instances that are merged with `self` to form the result. /// - Returns: a signal that emits every value from every `sources` input `signal`. public func merge<S: Sequence>(sequence: S) -> Signal<OutputValue> where S.Iterator.Element == Signal<OutputValue> { let (mergedInput, sig) = Signal<OutputValue>.createMergedInput(onLastInputClosed: .complete) mergedInput.add(signal, closePropagation: .errors) for s in sequence { mergedInput.add(s, closePropagation: .errors) } return sig } /// Implementation of [Reactive X operator "merge"](http://reactivex.io/documentation/operators/merge.html) where the output closes only when the last source closes. /// /// NOTE: the signal closes as `SignalComplete.cancelled` when the last output closes. For other closing semantics, use `Signal.mergSetAndSignal` instead. /// /// - Parameter sources: an `Array` where `signal` is merged into the result. /// - Returns: a signal that emits every value from every `sources` input `signal`. public static func merge<S: Sequence>(sequence: S) -> Signal<OutputValue> where S.Iterator.Element == Signal<OutputValue> { let (mergedInput, sig) = Signal<OutputValue>.createMergedInput(onLastInputClosed: .complete) var sequenceEmpty = true for s in sequence { mergedInput.add(s, closePropagation: .errors) sequenceEmpty = false } if sequenceEmpty { return Signal<OutputValue>.preclosed() } return sig } /// Implementation of [Reactive X operator "merge"](http://reactivex.io/documentation/operators/merge.html) where the output closes only when the last source closes. /// /// - Parameter sources: an `Array` where `signal` is merged into the result. /// - Returns: a signal that emits every value from every `sources` input `signal`. public static func merge(_ sources: Signal<OutputValue>...) -> Signal<OutputValue> { return merge(sequence: sources) } } extension SignalInterface { /// Implementation of [Reactive X operator "merge"](http://reactivex.io/documentation/operators/merge.html) where the output closes only when the last source closes. /// /// - Parameter sources: a variable parameter list of `Signal<OutputValue>` instances that are merged with `self` to form the result. /// - Returns: a signal that emits every value from every `sources` input `signal`. public func merge(_ sources: Signal<OutputValue>...) -> Signal<OutputValue> { let (mergedInput, sig) = Signal<OutputValue>.createMergedInput(onLastInputClosed: .complete) mergedInput.add(signal, closePropagation: .errors) for s in sources { mergedInput.add(s, closePropagation: .errors) } return sig } /// Implementation of [Reactive X operator "startWith"](http://reactivex.io/documentation/operators/startwith.html) /// /// - Parameter sequence: a sequence of values. /// - Returns: a signal that emits every value from `sequence` immediately before it starts mirroring `self`. public func startWith<S: Sequence>(sequence: S) -> Signal<OutputValue> where S.Iterator.Element == OutputValue { return Signal.from(sequence).combine(signal, initialState: false) { (alreadySent: inout Bool, r: EitherResult2<OutputValue, OutputValue>) -> Signal<OutputValue>.Next in switch r { case .result1(.success(let v)): if !alreadySent { return .value(v) } else { return .none } case .result1(.failure): alreadySent = true return .none case .result2(.success(let v)): if !alreadySent { alreadySent = true return .values(sequence: Array(sequence).appending(v)) } else { return .value(v) } case .result2(.failure(let e)): if !alreadySent { alreadySent = true return .values(sequence: sequence, end: e) } else { return .end(e) } } } } /// Implementation of [Reactive X operator "startWith"](http://reactivex.io/documentation/operators/startwith.html) /// /// - Parameter value: a value. /// - Returns: a signal that emits the value immediately before it starts mirroring `self`. public func startWith(_ values: OutputValue...) -> Signal<OutputValue> { return startWith(sequence: values) } /// Implementation of [Reactive X operator "endWith"](http://reactivex.io/documentation/operators/endwith.html) /// /// - Returns: a signal that emits every value from `sequence` on activation and then mirrors `self`. public func endWith<U: Sequence>(sequence: U, conditional: @escaping (SignalEnd) -> SignalEnd? = { e in e }) -> Signal<OutputValue> where U.Iterator.Element == OutputValue { return transform() { (r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(let v): return .value(v) case .failure(let e): if let newEnd = conditional(e) { return .values(sequence: sequence, end: newEnd) } else { return .end(e) } } } } /// Implementation of [Reactive X operator "endWith"](http://reactivex.io/documentation/operators/endwith.html) /// /// - Returns: a signal that emits every value from `sequence` on activation and then mirrors `self`. public func endWith(_ values: OutputValue..., conditional: @escaping (Error) -> Error? = { e in e }) -> Signal<OutputValue> { return endWith(sequence: values) } /// Implementation of [Reactive X operator "switch"](http://reactivex.io/documentation/operators/switch.html) /// /// See also: `flatMapLatest` (emits values from the latest `Signal` to start emitting) /// /// - Parameter signal: each of the inner signals emitted by this outer signal is observed, with the most recent signal emitted from the result /// - Returns: a signal that emits the values from the latest `Signal` emitted by `signal` public func switchLatest<U>() -> Signal<U> where OutputValue: SignalInterface, OutputValue.OutputValue == U { return transformFlatten(initialState: nil, closePropagation: .errors) { (latest: inout Signal<U>?, next: OutputValue, mergedInput: SignalMergedInput<U>) in if let l = latest { mergedInput.remove(l) } let s = next.signal mergedInput.add(s, closePropagation: .errors, removeOnDeactivate: true) latest = s } } @available(*, deprecated, message:"Renamed to zipWith. Alternately, use static zip function.") public func zip<U: SignalInterface>(_ second: U) -> Signal<(OutputValue, U.OutputValue)> { return zipWith(second) } /// Implementation of [Reactive X operator "zip"](http://reactivex.io/documentation/operators/zip.html) /// /// - Parameter second: another `Signal` /// - Returns: a signal that emits the values from `self`, paired with corresponding value from `with`. public static func zip<U: SignalInterface>(_ first: Self, _ second: U) -> Signal<(Self.OutputValue, U.OutputValue)> { return first.zipWith(second) } /// Implementation of [Reactive X operator "zip"](http://reactivex.io/documentation/operators/zip.html) /// /// - Parameter second: another `Signal` /// - Returns: a signal that emits the values from `self`, paired with corresponding value from `with`. public func zipWith<U: SignalInterface>(_ second: U) -> Signal<(OutputValue, U.OutputValue)> { return combine(second, initialState: (Array<OutputValue>(), Array<U.OutputValue>(), false, false)) { (queues: inout (first: Array<OutputValue>, second: Array<U.OutputValue>, firstClosed: Bool, secondClosed: Bool), r: EitherResult2<OutputValue, U.OutputValue>) -> Signal<(OutputValue, U.OutputValue)>.Next in switch (r, queues.first.first, queues.second.first) { case (.result1(.success(let first)), _, .some(let second)): queues.second.removeFirst() if (queues.second.isEmpty && queues.secondClosed) { return .value((first, second), end: .complete) } else { return .value((first, second)) } case (.result1(.success(let first)), _, _): queues.first.append(first) return .none case (.result1(.failure(let e)), _, _): if queues.first.isEmpty || (queues.second.isEmpty && queues.secondClosed) { return .end(e) } else { queues.firstClosed = true } return .none case (.result2(.success(let second)), .some(let first), _): queues.first.removeFirst() if (queues.first.isEmpty && queues.firstClosed) { return .value((first, second), end: .complete) } else { return .value((first, second)) } case (.result2(.success(let second)), _, _): queues.second.append(second) return .none case (.result2(.failure(let e)), _, _): if queues.second.isEmpty || (queues.first.isEmpty && queues.firstClosed) { return .end(e) } else { queues.secondClosed = true return .none } } } } @available(*, deprecated, message:"Renamed to zipWith. Alternately, use static zip function.") public func zip<U: SignalInterface, V: SignalInterface>(_ second: U, _ third: V) -> Signal<(OutputValue, U.OutputValue, V.OutputValue)> { return zipWith(second, third) } /// Implementation of [Reactive X operator "zip"](http://reactivex.io/documentation/operators/zip.html) /// /// - Parameters: /// - second: another `Signal` /// - third: another `Signal` /// - Returns: a signal that emits the values from `self`, paired with corresponding value from `second` and `third`. public static func zip<U: SignalInterface, V: SignalInterface>(_ first: Self, _ second: U, _ third: V) -> Signal<(Self.OutputValue, U.OutputValue, V.OutputValue)> { return first.zipWith(second, third) } /// Implementation of [Reactive X operator "zip"](http://reactivex.io/documentation/operators/zip.html) /// /// - Parameters: /// - second: another `Signal` /// - third: another `Signal` /// - Returns: a signal that emits the values from `self`, paired with corresponding value from `second` and `third`. public func zipWith<U: SignalInterface, V: SignalInterface>(_ second: U, _ third: V) -> Signal<(OutputValue, U.OutputValue, V.OutputValue)> { return combine(second, third, initialState: (Array<OutputValue>(), Array<U.OutputValue>(), Array<V.OutputValue>(), false, false, false)) { (queues: inout (first: Array<OutputValue>, second: Array<U.OutputValue>, third: Array<V.OutputValue>, firstClosed: Bool, secondClosed: Bool, thirdClosed: Bool), r: EitherResult3<OutputValue, U.OutputValue, V.OutputValue>) -> Signal<(OutputValue, U.OutputValue, V.OutputValue)>.Next in switch (r, queues.first.first, queues.second.first, queues.third.first) { case (.result1(.success(let first)), _, .some(let second), .some(let third)): queues.second.removeFirst() queues.third.removeFirst() if (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) { return .value((first, second, third), end: .complete) } else { return .value((first, second, third)) } case (.result1(.success(let first)), _, _, _): queues.first.append(first) return .none case (.result1(.failure(let e)), _, _, _): if queues.first.isEmpty || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) { return .end(e) } else { queues.firstClosed = true return .none } case (.result2(.success(let second)), .some(let first), _, .some(let third)): queues.first.removeFirst() queues.third.removeFirst() if (queues.first.isEmpty && queues.firstClosed) || (queues.third.isEmpty && queues.thirdClosed) { return .value((first, second, third), end: .complete) } else { return .value((first, second, third)) } case (.result2(.success(let second)), _, _, _): queues.second.append(second) return .none case (.result2(.failure(let e)), _, _, _): if queues.second.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.third.isEmpty && queues.thirdClosed) { return .end(e) } else { queues.secondClosed = true return .none } case (.result3(.success(let third)), .some(let first), .some(let second), _): queues.first.removeFirst() queues.second.removeFirst() if (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) { return .value((first, second, third), end: .complete) } else { return .value((first, second, third)) } case (.result3(.success(let third)), _, _, _): queues.third.append(third) return .none case (.result3(.failure(let e)), _, _, _): if queues.third.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) { return .end(e) } else { queues.thirdClosed = true return .none } } } } @available(*, deprecated, message:"Renamed to zipWith. Alternately, use static zip function.") public func zip<U: SignalInterface, V: SignalInterface, W: SignalInterface>(_ second: U, _ third: V, _ fourth: W) -> Signal<(OutputValue, U.OutputValue, V.OutputValue, W.OutputValue)> { return zipWith(second, third, fourth) } /// Implementation of [Reactive X operator "zip"](http://reactivex.io/documentation/operators/zip.html) /// /// - Parameters: /// - second: another `Signal` /// - third: another `Signal` /// - fourth: another `Signal` /// - Returns: a signal that emits the values from `self`, paired with corresponding value from `second`,`third` and `fourth`. public static func zip<U: SignalInterface, V: SignalInterface, W: SignalInterface>(_ first: Self, _ second: U, _ third: V, _ fourth: W) -> Signal<(Self.OutputValue, U.OutputValue, V.OutputValue, W.OutputValue)> { return first.zipWith(second, third, fourth) } /// Implementation of [Reactive X operator "zip"](http://reactivex.io/documentation/operators/zip.html) /// /// - Parameters: /// - second: another `Signal` /// - third: another `Signal` /// - fourth: another `Signal` /// - Returns: a signal that emits the values from `self`, paired with corresponding value from `second`,`third` and `fourth`. public func zipWith<U: SignalInterface, V: SignalInterface, W: SignalInterface>(_ second: U, _ third: V, _ fourth: W) -> Signal<(OutputValue, U.OutputValue, V.OutputValue, W.OutputValue)> { return combine(second, third, fourth, initialState: (Array<OutputValue>(), Array<U.OutputValue>(), Array<V.OutputValue>(), Array<W.OutputValue>(), false, false, false, false)) { (queues: inout (first: Array<OutputValue>, second: Array<U.OutputValue>, third: Array<V.OutputValue>, fourth: Array<W.OutputValue>, firstClosed: Bool, secondClosed: Bool, thirdClosed: Bool, fourthClosed: Bool), r: EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>) -> Signal<(OutputValue, U.OutputValue, V.OutputValue, W.OutputValue)>.Next in switch (r, queues.first.first, queues.second.first, queues.third.first, queues.fourth.first) { case (.result1(.success(let first)), _, .some(let second), .some(let third), .some(let fourth)): queues.second.removeFirst() queues.third.removeFirst() queues.fourth.removeFirst() if (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) { return .value((first, second, third, fourth), end: .complete) } else { return .value((first, second, third, fourth)) } case (.result1(.success(let first)), _, _, _, _): queues.first.append(first) return .none case (.result1(.failure(let e)), _, _, _, _): if queues.first.isEmpty || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) { return .end(e) } else { queues.firstClosed = true return .none } case (.result2(.success(let second)), .some(let first), _, .some(let third), .some(let fourth)): queues.first.removeFirst() queues.third.removeFirst() queues.fourth.removeFirst() if (queues.first.isEmpty && queues.firstClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) { return .value((first, second, third, fourth), end: .complete) } else { return .value((first, second, third, fourth)) } case (.result2(.success(let second)), _, _, _, _): queues.second.append(second) return .none case (.result2(.failure(let e)), _, _, _, _): if queues.second.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) { return .end(e) } else { queues.secondClosed = true return .none } case (.result3(.success(let third)), .some(let first), .some(let second), _, .some(let fourth)): queues.first.removeFirst() queues.second.removeFirst() queues.fourth.removeFirst() if (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.fourth.isEmpty && queues.fourthClosed) { return .value((first, second, third, fourth), end: .complete) } else { return .value((first, second, third, fourth)) } case (.result3(.success(let third)), _, _, _, _): queues.third.append(third) return .none case (.result3(.failure(let e)), _, _, _, _): if queues.third.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.fourth.isEmpty && queues.fourthClosed) { return .end(e) } else { queues.thirdClosed = true return .none } case (.result4(.success(let fourth)), .some(let first), .some(let second), .some(let third), _): queues.first.removeFirst() queues.second.removeFirst() queues.third.removeFirst() if (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) { return .value((first, second, third, fourth), end: .complete) } else { return .value((first, second, third, fourth)) } case (.result4(.success(let fourth)), _, _, _, _): queues.fourth.append(fourth) return .none case (.result4(.failure(let e)), _, _, _, _): if queues.fourth.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) { return .end(e) } else { queues.fourthClosed = true return .none } } } } @available(*, deprecated, message:"Renamed to zipWith. Alternately, use static zip function.") public func zip<U: SignalInterface, V: SignalInterface, W: SignalInterface, X: SignalInterface>(_ second: U, _ third: V, _ fourth: W, _ fifth: X) -> Signal<(OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue)> { return zipWith(second, third, fourth, fifth) } /// Implementation of [Reactive X operator "zip"](http://reactivex.io/documentation/operators/zip.html) /// /// - Parameters: /// - second: another `Signal` /// - third: another `Signal` /// - fourth: another `Signal` /// - fifth: another `Signal` /// - Returns: a signal that emits the values from `self`, paired with corresponding value from `second`,`third`, `fourth` and `fifth`. public static func zip<U: SignalInterface, V: SignalInterface, W: SignalInterface, X: SignalInterface>(_ first: Self, _ second: U, _ third: V, _ fourth: W, _ fifth: X) -> Signal<(Self.OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue)> { return first.zipWith(second, third, fourth, fifth) } /// Implementation of [Reactive X operator "zip"](http://reactivex.io/documentation/operators/zip.html) /// /// - Parameters: /// - second: another `Signal` /// - third: another `Signal` /// - fourth: another `Signal` /// - fifth: another `Signal` /// - Returns: a signal that emits the values from `self`, paired with corresponding value from `second`,`third`, `fourth` and `fifth`. public func zipWith<U: SignalInterface, V: SignalInterface, W: SignalInterface, X: SignalInterface>(_ second: U, _ third: V, _ fourth: W, _ fifth: X) -> Signal<(OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue)> { return combine(second, third, fourth, fifth, initialState: (Array<OutputValue>(), Array<U.OutputValue>(), Array<V.OutputValue>(), Array<W.OutputValue>(), Array<X.OutputValue>(), false, false, false, false, false)) { (queues: inout (first: Array<OutputValue>, second: Array<U.OutputValue>, third: Array<V.OutputValue>, fourth: Array<W.OutputValue>, fifth: Array<X.OutputValue>, firstClosed: Bool, secondClosed: Bool, thirdClosed: Bool, fourthClosed: Bool, fifthClosed: Bool), r: EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>) -> Signal<(OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue)>.Next in switch (r, queues.first.first, queues.second.first, queues.third.first, queues.fourth.first, queues.fifth.first) { case (.result1(.success(let first)), _, .some(let second), .some(let third), .some(let fourth), .some(let fifth)): queues.second.removeFirst() queues.third.removeFirst() queues.fourth.removeFirst() queues.fifth.removeFirst() if (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) || (queues.fifth.isEmpty && queues.fifthClosed) { return .value((first, second, third, fourth, fifth), end: .complete) } else { return .value((first, second, third, fourth, fifth)) } case (.result1(.success(let first)), _, _, _, _, _): queues.first.append(first) return .none case (.result1(.failure(let e)), _, _, _, _, _): if queues.first.isEmpty || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) || (queues.fifth.isEmpty && queues.fifthClosed) { return .end(e) } else { queues.firstClosed = true return .none } case (.result2(.success(let second)), .some(let first), _, .some(let third), .some(let fourth), .some(let fifth)): queues.first.removeFirst() queues.third.removeFirst() queues.fourth.removeFirst() queues.fifth.removeFirst() if (queues.first.isEmpty && queues.firstClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) || (queues.fifth.isEmpty && queues.fifthClosed) { return .value((first, second, third, fourth, fifth), end: .complete) } else { return .value((first, second, third, fourth, fifth)) } case (.result2(.success(let second)), _, _, _, _, _): queues.second.append(second) return .none case (.result2(.failure(let e)), _, _, _, _, _): if queues.second.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) || (queues.fifth.isEmpty && queues.fifthClosed) { return .end(e) } else { queues.secondClosed = true return .none } case (.result3(.success(let third)), .some(let first), .some(let second), _, .some(let fourth), .some(let fifth)): queues.first.removeFirst() queues.second.removeFirst() queues.fourth.removeFirst() queues.fifth.removeFirst() if (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.fourth.isEmpty && queues.fourthClosed) || (queues.fifth.isEmpty && queues.fifthClosed) { return .value((first, second, third, fourth, fifth), end: .complete) } else { return .value((first, second, third, fourth, fifth)) } case (.result3(.success(let third)), _, _, _, _, _): queues.third.append(third) return .none case (.result3(.failure(let e)), _, _, _, _, _): if queues.third.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.fourth.isEmpty && queues.fourthClosed) || (queues.fifth.isEmpty && queues.fifthClosed) { return .end(e) } else { queues.thirdClosed = true return .none } case (.result4(.success(let fourth)), .some(let first), .some(let second), .some(let third), _, .some(let fifth)): queues.first.removeFirst() queues.second.removeFirst() queues.third.removeFirst() queues.fifth.removeFirst() if (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fifth.isEmpty && queues.fifthClosed) { return .value((first, second, third, fourth, fifth), end: .complete) } else { return .value((first, second, third, fourth, fifth)) } case (.result4(.success(let fourth)), _, _, _, _, _): queues.fourth.append(fourth) return .none case (.result4(.failure(let e)), _, _, _, _, _): if queues.fourth.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fifth.isEmpty && queues.fifthClosed) { return .end(e) } else { queues.fourthClosed = true return .none } case (.result5(.success(let fifth)), .some(let first), .some(let second), .some(let third), .some(let fourth), _): queues.first.removeFirst() queues.second.removeFirst() queues.third.removeFirst() queues.fourth.removeFirst() if (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) { return .value((first, second, third, fourth, fifth), end: .complete) } else { return .value((first, second, third, fourth, fifth)) } case (.result5(.success(let fifth)), _, _, _, _, _): queues.fifth.append(fifth) return .none case (.result5(.failure(let e)), _, _, _, _, _): if queues.fifth.isEmpty || (queues.first.isEmpty && queues.firstClosed) || (queues.second.isEmpty && queues.secondClosed) || (queues.third.isEmpty && queues.thirdClosed) || (queues.fourth.isEmpty && queues.fourthClosed) { return .end(e) } else { queues.fifthClosed = true return .none } } } } } // Essentially a closure type used by `catchError`, defined as a separate class so the function can reference itself fileprivate class CatchErrorRecovery<OutputValue> { let recover: (SignalEnd) -> Signal<OutputValue> let catchTypes: SignalEndPropagation init(recover: @escaping (SignalEnd) -> Signal<OutputValue>, catchTypes: SignalEndPropagation) { self.recover = recover self.catchTypes = catchTypes } func catchErrorRejoin(j: SignalJunction<OutputValue>, e: SignalEnd, i: SignalInput<OutputValue>) { if catchTypes.shouldPropagateEnd(e) { do { let f: SignalJunction<OutputValue>.Handler = self.catchErrorRejoin try recover(e).junction().bind(to: i, onEnd: f) } catch { i.send(end: .other(error)) } } else { i.send(end: e) } } } // Essentially a closure type used by `retry`, defined as a separate class so the function can reference itself fileprivate class RetryRecovery<U> { let shouldRetry: (inout U, SignalEnd) -> DispatchTimeInterval? let catchTypes: SignalEndPropagation var state: U let context: Exec var timer: Lifetime? = nil init(shouldRetry: @escaping (inout U, SignalEnd) -> DispatchTimeInterval?, catchTypes: SignalEndPropagation, state: U, context: Exec) { self.shouldRetry = shouldRetry self.catchTypes = catchTypes self.state = state self.context = context } func retryRejoin<OutputValue>(j: SignalJunction<OutputValue>, e: SignalEnd, i: SignalInput<OutputValue>) { if catchTypes.shouldPropagateEnd(e), let t = shouldRetry(&state, e) { timer = context.singleTimer(interval: t) { do { try j.bind(to: i, onEnd: self.retryRejoin) } catch { i.send(end: .other(error)) } } } else { i.send(end: e) } } } extension SignalInterface { /// Implementation of [Reactive X operator "catch"](http://reactivex.io/documentation/operators/catch.html), returning a `Signal` on error in `self`. /// /// - Parameters: /// - context: context where `recover` will run /// - catchSignalComplete: by default, the `recover` closure will be invoked only for unexpected errors, i.e. when `Error` is *not* a `SignalComplete`. Set this parameter to `true` to invoke the `recover` closure for *all* errors, including `SignalEnd.complete` and `SignalComplete.cancelled`. /// - recover: a function that, when passed the `Error` that closed `self`, optionally returns a new signal. /// - Returns: a signal that emits the values from `self` until an error is received and then, if `recover` returns non-`nil` emits the values from `recover` and then emits the error from `recover`, otherwise if `recover` returns `nil`, emits the `Error` from `self`. public func catchError(context: Exec = .direct, catchSignalComplete: Bool = false, recover: @escaping (SignalEnd) -> Signal<OutputValue>) -> Signal<OutputValue> { let (input, sig) = Signal<OutputValue>.create() // Both `junction` and `input` are newly created so this can't be an error try! junction().bind(to: input, onEnd: CatchErrorRecovery(recover: recover, catchTypes: catchSignalComplete ? .all : .errors).catchErrorRejoin) return sig } /// Implementation of [Reactive X operator "retry"](http://reactivex.io/documentation/operators/retry.html) where the choice to retry and the delay between retries is controlled by a function. /// /// - Note: a ReactiveX "resubscribe" is interpreted as a disconnect and reconnect, which will trigger reactivation iff (if and only if) the preceding nodes have behavior that supports that. /// /// - Parameters: /// - initialState: a mutable state value that will be passed into `shouldRetry`. /// - context: the `Exec` where timed reconnection will occcur (default: .global). /// - catchSignalComplete: by default, the `shouldRetry` closure will be invoked only for unexpected errors, i.e. when `Error` is *not* a `SignalComplete`. Set this parameter to `true` to invoke the `recover` closure for *all* errors, including `SignalEnd.complete` and `SignalComplete.cancelled`. /// - shouldRetry: a function that, when passed the current state value and the `Error` that closed `self`, returns an `Optional<Double>`. /// - Returns: a signal that emits the values from `self` until an error is received and then, if `shouldRetry` returns non-`nil`, disconnects from `self`, delays by the number of seconds returned from `shouldRetry`, and reconnects to `self` (triggering re-activation), otherwise if `shouldRetry` returns `nil`, emits the `Error` from `self`. If the number of seconds is `0`, the reconnect is synchronous, otherwise it will occur in `context` using `invokeAsync`. public func retry<U>(_ initialState: U, context: Exec = .direct, catchSignalComplete: Bool = false, shouldRetry: @escaping (inout U, SignalEnd) -> DispatchTimeInterval?) -> Signal<OutputValue> { let (input, sig) = Signal<OutputValue>.create() // Both `junction` and `input` are newly created so this can't be an error try! junction().bind(to: input, onEnd: RetryRecovery(shouldRetry: shouldRetry, catchTypes: catchSignalComplete ? .all : .errors, state: initialState, context: context).retryRejoin) return sig } /// Implementation of [Reactive X operator "retry"](http://reactivex.io/documentation/operators/retry.html) where retries occur until the error is not `isSignalComplete` or `count` number of retries has occurred. /// /// - Note: a ReactiveX "resubscribe" is interpreted as a disconnect and reconnect, which will trigger reactivation iff the preceding nodes have behavior that supports that. /// /// - Parameters: /// - count: the maximum number of retries /// - delayInterval: the number of seconds between retries /// - context: the `Exec` where timed reconnection will occcur (default: .global). /// - catchSignalComplete: by default, retry attempts will occur only for unexpected errors, i.e. when `Error` is *not* a `SignalComplete`. Set this parameter to `true` to invoke the `recover` closure for *all* errors, including `SignalEnd.complete` and `SignalComplete.cancelled`. /// - Returns: a signal that emits the values from `self` until an error is received and then, if fewer than `count` retries have occurred, disconnects from `self`, delays by `delaySeconds` and reconnects to `self` (triggering re-activation), otherwise if `count` retries have occurred, emits the `Error` from `self`. If the number of seconds is `0`, the reconnect is synchronous, otherwise it will occur in `context` using `invokeAsync`. public func retry(count: Int, delayInterval: DispatchTimeInterval, context: Exec = .direct, catchSignalComplete: Bool = false) -> Signal<OutputValue> { return retry(0, context: context) { (retryCount: inout Int, e: SignalEnd) -> DispatchTimeInterval? in if !catchSignalComplete && e.isComplete { return nil } else if retryCount < count { retryCount += 1 return delayInterval } else { return nil } } } /// Implementation of [Reactive X operator "delay"](http://reactivex.io/documentation/operators/delay.html) where delay for each value is determined by running an `offset` function. /// /// - Parameters: /// - initialState: a user state value passed into the `offset` function /// - closePropagation: determines how errors and closure in `offset` affects the resulting signal /// - context: the `Exec` where `offset` will run (default: .global). /// - offset: a function that, when passed the current state value and the latest value from `self`, returns the number of seconds that the value should be delayed (values less or equal to 0 are sent immediately). /// - Returns: a mirror of `self` where values are offset according to `offset` – closing occurs when `self` closes or when the last delayed value is sent (whichever occurs last). public func delay<U>(initialState: U, closePropagation: SignalEndPropagation = .none, context: Exec = .direct, offset: @escaping (inout U, OutputValue) -> DispatchTimeInterval) -> Signal<OutputValue> { return delay(initialState: initialState, closePropagation: closePropagation, context: context) { (state: inout U, value: OutputValue) -> Signal<Void> in return Signal<Void>.timer(interval: offset(&state, value), context: context) } } /// Implementation of [Reactive X operator "delay"](http://reactivex.io/documentation/operators/delay.html) where delay for each value is constant. /// /// - Parameters: /// - interval: the delay for each value /// - context: the `Exec` where timed reconnection will occcur (default: .global). /// - Returns: a mirror of `self` where values are delayed by `seconds` – closing occurs when `self` closes or when the last delayed value is sent (whichever occurs last). public func delay(interval: DispatchTimeInterval, context: Exec = .direct) -> Signal<OutputValue> { return delay(initialState: interval, context: context) { (s: inout DispatchTimeInterval, v: OutputValue) -> DispatchTimeInterval in s } } /// Implementation of [Reactive X operator "delay"](http://reactivex.io/documentation/operators/delay.html) where delay for each value is determined by the duration of a signal returned from `offset`. /// /// - Parameters: /// - closePropagation: determines how errors and closure in `offset` affects the resulting signal /// - context: the `Exec` where `offset` will run (default: .global). /// - offset: a function that, when passed the current state value emits a signal, the first value of which will trigger the end of the delay /// - Returns: a mirror of `self` where values are offset according to `offset` – closing occurs when `self` closes or when the last delayed value is sent (whichever occurs last). public func delay<U>(closePropagation: SignalEndPropagation = .none, context: Exec = .direct, offset: @escaping (OutputValue) -> Signal<U>) -> Signal<OutputValue> { return delay(initialState: (), closePropagation: closePropagation, context: context) { (state: inout (), value: OutputValue) -> Signal<U> in return offset(value) } } /// Implementation of [Reactive X operator "delay"](http://reactivex.io/documentation/operators/delay.html) where delay for each value is determined by the duration of a signal returned from `offset`. /// /// - Parameters: /// - initialState: a user state value passed into the `offset` function /// - closePropagation: determines how errors and closure in `offset` affects the resulting signal /// - context: the `Exec` where `offset` will run (default: .global). /// - offset: a function that, when passed the current state value emits a signal, the first value of which will trigger the end of the delay /// - Returns: a mirror of `self` where values are offset according to `offset` – closing occurs when `self` closes or when the last delayed value is sent (whichever occurs last). public func delay<U, V>(initialState: V, closePropagation: SignalEndPropagation = .none, context: Exec = .direct, offset: @escaping (inout V, OutputValue) -> Signal<U>) -> Signal<OutputValue> { return valueDurations(initialState: initialState, closePropagation: closePropagation, context: context, offset).transform(initialState: [Int: OutputValue]()) { (values: inout [Int: OutputValue], r: Result<(Int, OutputValue?), SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success((let index, .some(let t))): values[index] = t return .none case .success((let index, .none)): return values[index].map { .value($0) } ?? .none case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "do"](http://reactivex.io/documentation/operators/do.html) for "activation" (not a concept that directly exists in ReactiveX but similar to doOnSubscribe). /// /// - Parameters: /// - context: where the handler will be invoked /// - handler: invoked when self is activated /// - Returns: a signal that emits the same outputs as self public func onActivate(context: Exec = .direct, _ handler: @escaping () -> ()) -> Signal<OutputValue> { let j = junction() let s = Signal<OutputValue>.generate { input in if let i = input { handler() _ = try? j.bind(to: i) } else { _ = j.disconnect() } } return s } /// Implementation of [Reactive X operator "do"](http://reactivex.io/documentation/operators/do.html) for "deactivation" (not a concept that directly exists in ReactiveX but similar to doOnUnsubscribe). /// /// - Parameters: /// - context: where the handler will be invoked /// - handler: invoked when self is deactivated /// - Returns: a signal that emits the same outputs as self public func onDeactivate(context: Exec = .direct, _ handler: @escaping () -> ()) -> Signal<OutputValue> { let j = junction() let s = Signal<OutputValue>.generate { input in if let i = input { _ = try? j.bind(to: i) } else { handler() _ = j.disconnect() } } return s } /// Implementation of [Reactive X operator "do"](http://reactivex.io/documentation/operators/do.html) for "result" (equivalent to doOnEach). /// /// - Parameters: /// - context: where the handler will be invoked /// - handler: invoked for each `Result` in the signal /// - Returns: a signal that emits the same outputs as self public func onResult(context: Exec = .direct, _ handler: @escaping (Result<OutputValue, SignalEnd>) -> ()) -> Signal<OutputValue> { return transform(context: context) { (r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in handler(r) return .single(r) } } /// Implementation of [Reactive X operator "do"](http://reactivex.io/documentation/operators/do.html) for "values" (equivalent to doOnNext). /// /// - Parameters: /// - context: where the handler will be invoked /// - handler: invoked for each value (Result.success) in the signal /// - Returns: a signal that emits the same outputs as self public func onValue(context: Exec = .direct, _ handler: @escaping (OutputValue) -> ()) -> Signal<OutputValue> { return transform(context: context) { (r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(let v): handler(v) return .value(v) case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "do"](http://reactivex.io/documentation/operators/do.html) for "errors" (equivalent to doOnTerminate). /// /// - Parameters: /// - context: where the handler will be invoked /// - handler: invoked for each error (Result.failure) in the signal /// - Returns: a signal that emits the same outputs as self public func onError(context: Exec = .direct, catchSignalComplete: Bool = false, _ handler: @escaping (SignalEnd) -> ()) -> Signal<OutputValue> { return transform(context: context) { (r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(let v): return .value(v) case .failure(let e): if catchSignalComplete || !e.isComplete { handler(e) } return .end(e) } } } /// Appends an onActivate, onValue, onError and onDeactivate operator to monitor behavior and inspect lifecycle events. /// /// - Parameters: /// - logPrefix: Prepended to the front of log statements. If non-empty, ": " is *also* prepended. /// - file: suffixed to the log statement (defaults to #file) /// - line: suffixed to the log statement (defaults to #line) /// - Returns: the otherwise untransformed signal public func debug(logPrefix: String = "", file: String = #file, line: Int = #line) -> Signal<OutputValue> { let prefix = logPrefix + (logPrefix.isEmpty ? "" : ": ") return onActivate { print("\(prefix)Activated at \(file):\(line)") } .onValue { print("\(prefix)Value at \(file):\(line) - \($0)") } .onError { print("\(prefix)Error at \(file):\(line) - \($0)") } .onDeactivate { print("\(prefix)Deactivated at \(file):\(line)") } } /// Implementation of [Reactive X operator "materialize"](http://reactivex.io/documentation/operators/materialize-dematerialize.html) /// /// WARNING: in CwlSignal, this operator will emit a `SignalEnd.complete` into the output signal immediately after emitting the first wrapped error. Within the "first error closes signal" behavior of CwlSignal, this is the only behavior that makes sense (since no further upstream values will be received), however, it does limit the usefulness of `materialize` to constructions where the `materialize` signal immediately outputs into a `SignalMultiInput` (including abstractions built on top, like `switchLatest` or child signals of a `flatMap`) that ignore non-error close conditions from the source signal. /// /// - Returns: a signal where each `Result` emitted from self is further wrapped in a Result.success. public func materialize() -> Signal<Result<OutputValue, SignalEnd>> { return transform { r in if r.isFailure { return .value(r, end: .complete) } else { return .value(r) } } } /// Implementation of [Reactive X operator "dematerialize"](http://reactivex.io/documentation/operators/materialize-dematerialize.html) /// /// NOTE: ideally, this would not be a static function but a "same type" conditional extension. In a future Swift release this will probably change. /// /// - Parameter signal: a signal whose OutputValue is a `Result` wrapped version of an underlying type /// - Returns: a signal whose OutputValue is the unwrapped value from the input, with unwrapped errors sent as errors. public static func dematerialize<OutputValue>(_ signal: Signal<Result<OutputValue, SignalEnd>>) -> Signal<OutputValue> { return signal.transform { (r: Result<Result<OutputValue, SignalEnd>, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(.success(let v)): return .value(v) case .success(.failure(let e)): return .end(e) case .failure(let e): return .end(e) } } } } extension SignalInterface { /// - Note: the [Reactive X operator "ObserveOn"](http://reactivex.io/documentation/operators/observeon.html) doesn't apply to CwlSignal.Signal since any CwlSignal.Signal that runs work can specify their own execution context and control scheduling in that way. /// - Note: the [Reactive X operator "Serialize"](http://reactivex.io/documentation/operators/serialize.html) doesn't apply to CwlSignal.Signal since all CwlSignal.Signal instances are always serialized and well-behaved under multi-threaded access. /// - Note: the [Reactive X operator "Subscribe" and "SubscribeOn"](http://reactivex.io/documentation/operators/subscribe.html) are implemented as `subscribe`. } extension SignalInterface { /// Implementation of [Reactive X operator "TimeInterval"](http://reactivex.io/documentation/operators/timeinterval.html) /// /// - Parameter context: time between emissions will be calculated based on the timestamps from this context /// - Returns: a signal where the values are seconds between emissions from self public func timeInterval(context: Exec = .direct) -> Signal<Double> { let junction = self.map { v in () }.junction() // This `generate` transform is used to capture the start of the stream let s = Signal<Void>.generate { input in if let i = input { i.send(value: ()) // Then after sending the initial value, connect to upstream try! junction.bind(to: i) } else { _ = junction.disconnect() } }.transform(initialState: nil, context: context) { (lastTime: inout DispatchTime?, r: Result<Void, SignalEnd>) -> Signal<Double>.Next in switch r { case .success: let currentTime = context.timestamp() if let l = lastTime { lastTime = currentTime return .value(currentTime.since(l).seconds) } else { lastTime = currentTime return .none } case .failure(let e): return .end(e) } } return s } /// Implementation of [Reactive X operator "Timeout"](http://reactivex.io/documentation/operators/timeout.html) /// /// - Parameters: /// - interval: the duration before a SignalReactiveError.timeout will be emitted /// - resetOnValue: if `true`, each value sent through the signal will reset the timer (making the timeout an "idle" timeout). If `false`, the timeout duration is measured from the start of the signal and is unaffected by whether values are received. /// - context: timestamps will be added based on the time in this context /// - Returns: a mirror of self unless a timeout occurs, in which case it will closed by a SignalReactiveError.timeout public func timeout(interval: DispatchTimeInterval, resetOnValue: Bool = true, context: Exec = .direct) -> Signal<OutputValue> { let (input, s) = Signal<Void>.create() let junction = Signal<Void>.timer(interval: interval, context: context).junction() // Both `junction` and `input` are newly created so this can't be an error try! junction.bind(to: input) return combine(s, context: context) { (cr: EitherResult2<OutputValue, ()>) -> Signal<OutputValue>.Next in switch cr { case .result1(let r): if resetOnValue { junction.rebind() } return .single(r) case .result2: return .end(.other(SignalReactiveError.timeout)) } } } /// Implementation of [Reactive X operator "Timestamp"](http://reactivex.io/documentation/operators/timestamp.html) /// /// - Parameter context: used as the source of time /// - Returns: a signal where the values are a two element tuple, first element is self.OutputValue, second element is the `DispatchTime` timestamp that this element was emitted from self. public func timestamp(context: Exec = .direct) -> Signal<(OutputValue, DispatchTime)> { return transform(context: context) { (r: Result<OutputValue, SignalEnd>) -> Signal<(OutputValue, DispatchTime)>.Next in switch r { case .success(let v): return .value((v, context.timestamp())) case .failure(let e): return .end(e) } } } } extension SignalInterface { /// - Note: the [Reactive X operator "Using"](http://reactivex.io/documentation/operators/using.html) doesn't apply to CwlSignal.Signal which uses standard Swift reference counted lifetimes. Resources should be captured by closures or `transform(initialState:...)`. } extension SignalInterface { /// Implementation of [Reactive X operator "All"](http://reactivex.io/documentation/operators/all.html) /// /// - Parameters: /// - context: the `test` function will be run in this context /// - test: will be invoked for every value /// - Returns: a signal that emits true and then closes if every value emitted by self returned true from the `test` function and self closed normally, otherwise emits false and then closes public func all(context: Exec = .direct, test: @escaping (OutputValue) -> Bool) -> Signal<Bool> { return transform(context: context) { (r: Result<OutputValue, SignalEnd>) -> Signal<Bool>.Next in switch r { case .success(let v) where !test(v): return .value(false, end: .complete) case .failure(.complete): return .value(true, end: .complete) case .failure(let e): return .end(e) case .success: return .none } } } } extension Signal { /// Implementation of [Reactive X operator "Amb"](http://reactivex.io/documentation/operators/amb.html) using the alternate name `race`, since it better conveys the purpose. /// /// - Parameter inputs: a set of inputs /// - Returns: connects to all inputs then emits the full set of values from the first of these to emit a value public static func race<S: Sequence>(sequence: S) -> Signal<OutputValue> where S.Iterator.Element == Signal<OutputValue> { let (mergedInput, sig) = Signal<(Int, Result)>.createMergedInput() sequence.enumerated().forEach { s in mergedInput.add(s.element.transform { r in return .value((s.offset, r)) }, closePropagation: .errors) } return sig.transform(initialState: -1) { (first: inout Int, r: Signal<(Int, Result)>.Result) -> Signal<OutputValue>.Next in switch r { case .success((let index, let underlying)) where first < 0: first = index return .single(underlying) case .success((let index, let underlying)) where first < 0 || first == index: return .single(underlying) case .failure(let e): return .end(e) case .success: return .none } } } public static func race(_ signals: Signal<OutputValue>...) -> Signal<OutputValue> { return race(sequence: signals) } } extension SignalInterface { /// Implementation of [Reactive X operator "Some"](http://reactivex.io/documentation/operators/some.html) /// /// - Parameters: /// - context: the `test` function will be run in this context /// - test: will be invoked for every value /// - Returns: a signal that emits true and then closes when a value emitted by self returns true from the `test` function, otherwise if no values from self return true, emits false and then closes public func find(context: Exec = .direct, test: @escaping (OutputValue) -> Bool) -> Signal<Bool> { return transform(context: context) { (r: Result<OutputValue, SignalEnd>) -> Signal<Bool>.Next in switch r { case .success(let v) where test(v): return .value(true, end: .complete) case .success: return .none case .failure(let e): return .value(false, end: e) } } } /// Implementation of [Reactive X operator "Some"](http://reactivex.io/documentation/operators/some.html) /// /// - Parameters: /// - context: the `test` function will be run in this context /// - test: will be invoked for every value /// - Returns: a signal that emits true and then closes when a value emitted by self returns true from the `test` function, otherwise if no values from self return true, emits false and then closes public func findIndex(context: Exec = .direct, test: @escaping (OutputValue) -> Bool) -> Signal<Int?> { return transform(initialState: 0, context: context) { (index: inout Int, r: Result<OutputValue, SignalEnd>) -> Signal<Int?>.Next in switch r { case .success(let v) where test(v): return .value(index, end: .complete) case .success: index += 1 return .none case .failure(let e): return .value(nil, end: e) } } } } extension SignalInterface where OutputValue: Equatable { /// Implementation of [Reactive X operator "Some"](http://reactivex.io/documentation/operators/some.html) /// /// - Parameter value: every value emitted by self is tested for equality with this value /// - Returns: a signal that emits true and then closes when a value emitted by self tests as `==` to `value`, otherwise if no values from self test as equal, emits false and then closes public func find(value: OutputValue) -> Signal<Bool> { return find { value == $0 } } } extension SignalInterface { /// Implementation of [Reactive X operator "DefaultIfEmpty"](http://reactivex.io/documentation/operators/defaultifempty.html) /// /// - Parameter value: value to emit if self closes without a value /// - Returns: a signal that emits the same values as self or `value` if self closes without emitting a value public func defaultIfEmpty(value: OutputValue) -> Signal<OutputValue> { return transform(initialState: false) { (started: inout Bool, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in switch r { case .success(let v): started = true return .value(v) case .failure(let e) where !started: return .value(value, end: e) case .failure(let e): return .end(e) } } } /// Implementation of [Reactive X operator "SwitchIfEmpty"](http://reactivex.io/documentation/operators/switchifempty.html) /// /// - Parameter alternate: content will be used if self closes without emitting a value /// - Returns: a signal that emits the same values as self or mirrors `alternate` if self closes without emitting a value public func switchIfEmpty(alternate: Signal<OutputValue>) -> Signal<OutputValue> { var fallback: Signal<OutputValue>? = alternate let (input, preMappedSignal) = Signal<OutputValue>.create() let s = preMappedSignal.map { (t: OutputValue) -> OutputValue in fallback = nil return t } // Both `junction` and `input` are newly created so this can't be an error try! junction().bind(to: input) { (j: SignalJunction<OutputValue>, e: SignalEnd, i: SignalInput<OutputValue>) in if let f = fallback { f.bind(to: i) } else { i.send(end: e) } } return s } } extension SignalInterface where OutputValue: Equatable { /// Implementation of [Reactive X operator "SequenceEqual"](http://reactivex.io/documentation/operators/sequenceequal.html) /// /// - Parameter to: another signal whose contents will be compared to this signal /// - Returns: a signal that emits `true` if `self` and `to` are equal, `false` otherwise public func sequenceEqual(to: Signal<OutputValue>) -> Signal<Bool> { return combine(to, initialState: (Array<OutputValue>(), Array<OutputValue>(), false, false)) { (state: inout (lq: Array<OutputValue>, rq: Array<OutputValue>, lc: Bool, rc: Bool), r: EitherResult2<OutputValue, OutputValue>) -> Signal<Bool>.Next in // state consists of lq (left queue), rq (right queue), lc (left closed), rc (right closed) switch (r, state.lq.first, state.rq.first) { case (.result1(.success(let left)), _, .some(let right)): if left != right { return .value(false, end: .complete) } state.rq.removeFirst() return .none case (.result1(.success(let left)), _, _): state.lq.append(left) return .none case (.result2(.success(let right)), .some(let left), _): if left != right { return .value(false, end: .complete) } state.lq.removeFirst() return .none case (.result2(.success(let right)), _, _): state.rq.append(right) return .none case (.result1(.failure(let e)), _, _): state.lc = true if state.rc { if state.lq.count == state.rq.count { return .value(true, end: e) } else { return .value(false, end: e) } } return .none case (.result2(.failure(let e)), _, _): state.rc = true if state.lc { if state.lq.count == state.rq.count { return .value(true, end: e) } else { return .value(false, end: e) } } return .none } } } } extension SignalInterface { /// Implementation of [Reactive X operator "SkipUntil"](http://reactivex.io/documentation/operators/skipuntil.html) /// /// - Parameter other: until this signal emits a value, all values from self will be dropped /// - Returns: a signal that mirrors `self` after `other` emits a value (but won't emit anything prior) public func skipUntil<U: SignalInterface>(_ other: U) -> Signal<OutputValue> { return combine(other, initialState: false) { (started: inout Bool, cr: EitherResult2<OutputValue, U.OutputValue>) -> Signal<OutputValue>.Next in switch cr { case .result1(.success(let v)) where started: return .value(v) case .result1(.success): return .none case .result1(.failure(let e)): return .end(e) case .result2(.success): started = true return .none case .result2(.failure): return .none } } } /// Implementation of [Reactive X operator "SkipWhile"](http://reactivex.io/documentation/operators/skipwhile.html) /// /// - Parameters: /// - context: execution context where `condition` will be run /// - condition: will be run for every value emitted from `self` until `condition` returns `true` /// - Returns: a signal that mirrors `self` dropping values until `condition` returns `true` for one of the values public func skipWhile(context: Exec = .direct, condition: @escaping (OutputValue) throws -> Bool) -> Signal<OutputValue> { return transform(initialState: false, context: context) { (started: inout Bool, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in do { switch r { case .success(let v) where try !started && condition(v): return .none case .success(let v): started = true return .value(v) case .failure(let e): return .end(e) } } catch { return .error(error) } } } /// Implementation of [Reactive X operator "SkipWhile"](http://reactivex.io/documentation/operators/skipwhile.html) /// /// - Parameters: /// - initialState: intial value for a state parameter that will be passed to `condition` on each invocation /// - context: execution context where `condition` will be run /// - condition: will be run for every value emitted from `self` until `condition` returns `true` /// - Returns: a signal that mirrors `self` dropping values until `condition` returns `true` for one of the values public func skipWhile<U>(initialState initial: U, context: Exec = .direct, condition: @escaping (inout U, OutputValue) throws -> Bool) -> Signal<OutputValue> { return transform(initialState: (initial, false), context: context) { (started: inout (U, Bool), r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in do { switch r { case .success(let v) where try !started.1 && condition(&started.0, v): return .none case .success(let v): started.1 = true return .value(v) case .failure(let e): return .end(e) } } catch { return .error(error) } } } /// Implementation of [Reactive X operator "TakeUntil"](http://reactivex.io/documentation/operators/takeuntil.html) /// /// - Parameter other: after this signal emits a value, all values from self will be dropped /// - Returns: a signal that mirrors `self` until `other` emits a value (but won't emit anything after) public func takeUntil<U: SignalInterface>(_ other: U) -> Signal<OutputValue> { return combine(other, initialState: false) { (started: inout Bool, cr: EitherResult2<OutputValue, U.OutputValue>) -> Signal<OutputValue>.Next in switch cr { case .result1(.success(let v)) where !started: return .value(v) case .result1(.success): return .none case .result1(.failure(let e)): return .end(e) case .result2(.success): started = true return .none case .result2(.failure): return .none } } } /// Implementation of [Reactive X operator "TakeWhile"](http://reactivex.io/documentation/operators/takewhile.html) /// /// - Parameters: /// - context: execution context where `condition` will be run /// - condition: will be run for every value emitted from `self` until `condition` returns `true` /// - Returns: a signal that mirrors `self` dropping values after `condition` returns `true` for one of the values public func takeWhile(context: Exec = .direct, condition: @escaping (OutputValue) throws -> Bool) -> Signal<OutputValue> { return transform(context: context) { (r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in do { switch r { case .success(let v) where try condition(v): return .value(v) case .success: return .complete() case .failure(let e): return .end(e) } } catch { return .error(error) } } } /// Implementation of [Reactive X operator "TakeWhile"](http://reactivex.io/documentation/operators/takewhile.html) /// /// - Parameters: /// - initialState: intial value for a state parameter that will be passed to `condition` on each invocation /// - context: execution context where `condition` will be run /// - condition: will be run for every value emitted from `self` until `condition` returns `true` /// - Returns: a signal that mirrors `self` dropping values after `condition` returns `true` for one of the values public func takeWhile<U>(initialState initial: U, context: Exec = .direct, condition: @escaping (inout U, OutputValue) throws -> Bool) -> Signal<OutputValue> { return transform(initialState: initial, context: context) { (i: inout U, r: Result<OutputValue, SignalEnd>) -> Signal<OutputValue>.Next in do { switch r { case .success(let v) where try condition(&i, v): return .value(v) case .success: return .complete() case .failure(let e): return .end(e) } } catch { return .error(error) } } } /// A helper method used for mathematical operators. Performs a basic `fold` over the values emitted by `self` then passes the final result through another `finalize` function before emitting the result as a value in the returned signal. /// /// - Parameters: /// - initial: used to initialize the fold state /// - context: all functions will be invoked in this context /// - finalize: invoked when `self` closes, with the current fold state value /// - fold: invoked for each value emitted by `self` along with the current fold state value /// - Returns: a signal which emits the `finalize` result public func foldAndFinalize<U, V>(_ initial: V, context: Exec = .direct, finalize: @escaping (V) throws -> U?, fold: @escaping (V, OutputValue) throws -> V) -> Signal<U> { return transform(initialState: initial, context: context) { (state: inout V, r: Result<OutputValue, SignalEnd>) -> Signal<U>.Next in do { switch r { case .success(let v): state = try fold(state, v) return .none case .failure(let e): if let v = try finalize(state) { return .value(v, end: e) } else { return .end(e) } } } catch { return .error(error) } } } } extension SignalInterface where OutputValue: BinaryInteger { /// Implementation of [Reactive X operator "Average"](http://reactivex.io/documentation/operators/average.html) /// /// - Returns: a signal that emits a single value... the sum of all values emitted by `self` public func average() -> Signal<OutputValue> { return foldAndFinalize((0, 0), finalize: { (fold: (OutputValue, OutputValue)) -> OutputValue? in fold.0 > 0 ? fold.1 / fold.0 : nil }) { (fold: (OutputValue, OutputValue), value: OutputValue) -> (OutputValue, OutputValue) in return (fold.0 + 1, fold.1 + value) } } } extension SignalInterface { /// Implementation of [Reactive X operator "Concat"](http://reactivex.io/documentation/operators/concat.html) /// /// - Parameter other: a second signal /// - Returns: a signal that emits all the values from `self` followed by all the values from `other` (including those emitted while `self` was still active) public func concat(_ other: Signal<OutputValue>) -> Signal<OutputValue> { return combine(other, initialState: ([OutputValue](), nil, nil)) { (state: inout (secondValues: [OutputValue], firstError: SignalEnd?, secondError: SignalEnd?), cr: EitherResult2<OutputValue, OutputValue>) -> Signal<OutputValue>.Next in switch (cr, state.firstError) { case (.result1(.success(let v)), _): return .value(v) case (.result1(.failure(.complete)), _): if let e2 = state.secondError { return .values(sequence: state.secondValues, end: e2) } else { state.firstError = .complete return .values(sequence: state.secondValues) } case (.result1(.failure(let e1)), _): // In the event of an "unexpected" error, don't emit the second signal. return .end(e1) case (.result2(.success(let v)), .none): state.secondValues.append(v) return .none case (.result2(.success(let v)), .some): return .value(v) case (.result2(.failure(let e2)), .none): state.secondError = e2 return .none case (.result2(.failure(let e2)), .some): return .end(e2) } } } /// Implementation of [Reactive X operator "Count"](http://reactivex.io/documentation/operators/count.html) /// /// - Returns: a signal that emits the number of values emitted by `self` public func count() -> Signal<Int> { return aggregate(0) { (fold: (Int), value: OutputValue) -> Int in return fold + 1 } } } extension SignalInterface where OutputValue: Comparable { /// Implementation of [Reactive X operator "Min"](http://reactivex.io/documentation/operators/min.html) /// /// - Returns: the smallest value emitted by self public func min() -> Signal<OutputValue> { return foldAndFinalize(nil, finalize: { $0 }) { (fold: OutputValue?, value: OutputValue) -> OutputValue? in return fold.map { value < $0 ? value : $0 } ?? value } } /// Implementation of [Reactive X operator "Max"](http://reactivex.io/documentation/operators/max.html) /// /// - Returns: the largest value emitted by self public func max() -> Signal<OutputValue> { return foldAndFinalize(nil, finalize: { $0 }) { (fold: OutputValue?, value: OutputValue) -> OutputValue? in return fold.map { value > $0 ? value : $0 } ?? value } } } extension SignalInterface { /// Implementation of [Reactive X operator "Reduce"](http://reactivex.io/documentation/operators/reduce.html). The .NET/alternate name of `aggregate` is used to avoid conflict with the Signal.reduce function. /// /// See also: `scan` which applies the same logic but emits the `fold` value on *every* invocation. /// /// - Parameters: /// - initial: initialize the state value /// - context: the `fold` function will be invoked on this context /// - fold: invoked for every value emitted from self /// - Returns: emits the last emitted `fold` state value public func aggregate<U>(_ initial: U, context: Exec = .direct, fold: @escaping (U, OutputValue) -> U) -> Signal<U> { return foldAndFinalize(initial, context: context, finalize: { $0 }) { (state: U, value: OutputValue) in return fold(state, value) } } } extension SignalInterface where OutputValue: Numeric { /// Implementation of [Reactive X operator "Sum"](http://reactivex.io/documentation/operators/sum.html) /// /// - Returns: a signal that emits the sum of all values emitted by self public func sum() -> Signal<OutputValue> { return aggregate(0) { (fold: OutputValue, value: OutputValue) -> OutputValue in return fold + value } } }
isc
1a3b3c9e93aacbf75b5c0f3a7ca99717
49.02924
660
0.693311
3.626024
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Core/PaymentMethodSelector/ViewModel/PXPaymentSelectorViewModel+InitFlow.swift
1
2580
import Foundation // MARK: Init Flow extension PXPaymentMethodSelectorViewModel { func createInitFlow() { // Create init flow props. let initFlowProperties: InitFlowProperties initFlowProperties.checkoutPreference = checkoutPreference initFlowProperties.paymentData = paymentData initFlowProperties.paymentPlugin = nil initFlowProperties.paymentMethodSearchResult = search initFlowProperties.chargeRules = chargeRules initFlowProperties.serviceAdapter = mercadoPagoServices initFlowProperties.advancedConfig = getAdvancedConfiguration() initFlowProperties.paymentConfigurationService = PXPaymentConfigurationServices() initFlowProperties.privateKey = accessToken initFlowProperties.productId = getAdvancedConfiguration().productId initFlowProperties.checkoutType = PXTrackingStore.TrackingChoType.one_tap_selector // Create init flow. initFlow = InitFlow(flowProperties: initFlowProperties, finishInitCallback: { [weak self] checkoutPreference, initSearch in guard let self = self else { return } self.checkoutPreference = checkoutPreference self.updateCustomTexts() self.updateCheckoutModel(paymentMethodSearch: initSearch) self.paymentData.updatePaymentDataWith(payer: checkoutPreference.getPayer()) PXTrackingStore.sharedInstance.addData(forKey: PXTrackingStore.cardIdsESC, value: self.getCardsIdsWithESC()) let selectedDiscountConfigurartion = initSearch.selectedDiscountConfiguration // self.attemptToApplyDiscount(selectedDiscountConfigurartion) self.initFlowProtocol?.didFinishInitFlow() }, errorInitCallback: { [weak self] initFlowError in self?.initFlowProtocol?.didFailInitFlow(flowError: initFlowError) }) } func setInitFlowProtocol(flowInitProtocol: InitFlowProtocol) { initFlowProtocol = flowInitProtocol } func startInitFlow() { initFlow?.start() } func refreshInitFlow(cardId: String) { initFlow?.initFlowModel.updateInitModel(paymentMethodsResponse: nil) initFlow?.newCardId = cardId initFlow?.start() } func refreshAddAccountFlow(accountId: String) { initFlow?.initFlowModel.updateInitModel(paymentMethodsResponse: nil) initFlow?.newAccountId = accountId initFlow?.start() } func updateInitFlow() { initFlow?.updateModel(paymentPlugin: nil, chargeRules: self.chargeRules) } }
mit
e2f422139501b6c9192ae57305860876
39.952381
132
0.722481
5.058824
false
true
false
false
infobip/mobile-messaging-sdk-ios
Classes/Vendor/PSOperations/OperationCondition.swift
1
3908
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains the fundamental logic relating to Operation conditions. */ import Foundation public let OperationConditionKey = "OperationCondition" /** A protocol for defining conditions that must be satisfied in order for an operation to begin execution. */ public protocol OperationCondition { /** The name of the condition. This is used in userInfo dictionaries of `.ConditionFailed` errors as the value of the `OperationConditionKey` key. */ static var name: String { get } /** Specifies whether multiple instances of the conditionalized operation may be executing simultaneously. */ static var isMutuallyExclusive: Bool { get } /** Some conditions may have the ability to satisfy the condition if another operation is executed first. Use this method to return an operation that (for example) asks for permission to perform the operation - parameter operation: The `Operation` to which the Condition has been added. - returns: An `NSOperation`, if a dependency should be automatically added. Otherwise, `nil`. - note: Only a single operation may be returned as a dependency. If you find that you need to return multiple operations, then you should be expressing that as multiple conditions. Alternatively, you could return a single `GroupOperation` that executes multiple operations internally. */ func dependencyForOperation(_ operation: Operation) -> Foundation.Operation? /// Evaluate the condition, to see if it has been satisfied or not. func evaluateForOperation(_ operation: Operation, completion: @escaping (OperationConditionResult) -> Void) } /** An enum to indicate whether an `OperationCondition` was satisfied, or if it failed with an error. */ public enum OperationConditionResult { case satisfied case failed(NSError) var error: NSError? { switch self { case .failed(let error): return error default: return nil } } } func ==(lhs: OperationConditionResult, rhs: OperationConditionResult) -> Bool { switch (lhs, rhs) { case (.satisfied, .satisfied): return true case (.failed(let lError), .failed(let rError)) where lError == rError: return true default: return false } } // MARK: Evaluate Conditions struct OperationConditionEvaluator { static func evaluate(_ conditions: [OperationCondition], operation: Operation, completion: @escaping ([NSError]) -> Void) { // Check conditions. let conditionGroup = DispatchGroup() var results = [OperationConditionResult?](repeating: nil, count: conditions.count) // Ask each condition to evaluate and store its result in the "results" array. for (index, condition) in conditions.enumerated() { conditionGroup.enter() condition.evaluateForOperation(operation) { result in results[index] = result conditionGroup.leave() } } // After all the conditions have evaluated, this block will execute. conditionGroup.notify(queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default)) { // Aggregate the errors that occurred, in order. var failures = results.compactMap { $0?.error } /* If any of the conditions caused this operation to be cancelled, check for that. */ if operation.isCancelled { failures.append(NSError(code: .conditionFailed)) } completion(failures) } } }
apache-2.0
9bad6b9e936b64bfa0cc6b5ddb25f7fb
33.875
127
0.649258
5.285521
false
false
false
false
johnno1962c/swift-corelibs-foundation
Foundation/XMLElement.swift
5
11483
// 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 /*! @class XMLElement @abstract An XML element @discussion Note: Trying to add a document, namespace, attribute, or node with a parent throws an exception. To add a node with a parent first detach or create a copy of it. */ open class XMLElement: XMLNode { /*! @method initWithName: @abstract Returns an element <tt>&lt;name>&lt;/name></tt>. */ public convenience init(name: String) { self.init(name: name, uri: nil) } /*! @method initWithName:URI: @abstract Returns an element whose full QName is specified. */ public init(name: String, uri URI: String?) { super.init(kind: .element, options: []) self.uri = URI self.name = name } /*! @method initWithName:stringValue: @abstract Returns an element with a single text node child <tt>&lt;name>string&lt;/name></tt>. */ public convenience init(name: String, stringValue string: String?) { self.init(name: name, uri: nil) if let string = string { let child = _CFXMLNewTextNode(string) _CFXMLNodeAddChild(_xmlNode, child) } } /*! @method initWithXMLString:error: @abstract Returns an element created from a string. Parse errors are collected in <tt>error</tt>. */ public convenience init(xmlString string: String) throws { // If we prepend the XML line to the string let docString = """ <?xml version="1.0" encoding="utf-8" standalone="yes"?>\(string) """ // we can use the document string parser to get the element let doc = try XMLDocument(xmlString: docString, options: []) // We know the doc has a root element and first child or else the above line would have thrown self.init(ptr: _CFXMLCopyNode(_CFXMLNodeGetFirstChild(doc._xmlNode)!, true)) } public convenience override init(kind: XMLNode.Kind, options: XMLNode.Options = []) { self.init(name: "", uri: nil) } /*! @method elementsForName: @abstract Returns all of the child elements that match this name. */ open func elements(forName name: String) -> [XMLElement] { return self.filter({ _CFXMLNodeGetType($0._xmlNode) == _kCFXMLTypeElement }).filter({ $0.name == name }).flatMap({ $0 as? XMLElement }) } /*! @method elementsForLocalName:URI @abstract Returns all of the child elements that match this localname URI pair. */ open func elements(forLocalName localName: String, uri URI: String?) -> [XMLElement] { return self.filter({ _CFXMLNodeGetType($0._xmlNode) == _kCFXMLTypeElement }).filter({ $0.localName == localName && $0.uri == uri }).flatMap({ $0 as? XMLElement }) } /*! @method addAttribute: @abstract Adds an attribute. Attributes with duplicate names are not added. */ open func addAttribute(_ attribute: XMLNode) { guard let name = _CFXMLNodeCopyName(attribute._xmlNode)?._swiftObject else { fatalError("Attributes must have a name!") } name.cString(using: .utf8)!.withUnsafeBufferPointer() { guard let ptr = $0.baseAddress, _CFXMLNodeHasProp(_xmlNode, ptr) == nil else { return } addChild(attribute) } } /*! @method removeAttributeForName: @abstract Removes an attribute based on its name. */ open func removeAttribute(forName name: String) { if let prop = _CFXMLNodeHasProp(_xmlNode, name) { let propNode = XMLNode._objectNodeForNode(_CFXMLNodePtr(prop)) _childNodes.remove(propNode) // We can't use `xmlRemoveProp` because someone else may still have a reference to this attribute _CFXMLUnlinkNode(_CFXMLNodePtr(prop)) } } /*! @method setAttributes @abstract Set the attributes. In the case of duplicate names, the first attribute with the name is used. */ open var attributes: [XMLNode]? { get { var result: [XMLNode] = [] var nextAttribute = _CFXMLNodeProperties(_xmlNode) while let attribute = nextAttribute { result.append(XMLNode._objectNodeForNode(attribute)) nextAttribute = _CFXMLNodeGetNextSibling(attribute) } return !result.isEmpty ? result : nil // This appears to be how Darwin does it } set { removeAttributes() guard let attributes = newValue else { return } for attribute in attributes { addAttribute(attribute) } } } private func removeAttributes() { var nextAttribute = _CFXMLNodeProperties(_xmlNode) while let attribute = nextAttribute { var shouldFreeNode = true if let privateData = _CFXMLNodeGetPrivateData(attribute) { _childNodes.remove(XMLNode.unretainedReference(privateData)) shouldFreeNode = false } let temp = _CFXMLNodeGetNextSibling(attribute) _CFXMLUnlinkNode(attribute) if shouldFreeNode { _CFXMLFreeNode(attribute) } nextAttribute = temp } } /*! @method setAttributesWithDictionary: @abstract Set the attributes based on a name-value dictionary. */ open func setAttributesWith(_ attributes: [String : String]) { removeAttributes() for (name, value) in attributes { addAttribute(XMLNode.attribute(withName: name, stringValue: value) as! XMLNode) } } /*! @method attributeForName: @abstract Returns an attribute matching this name. */ open func attribute(forName name: String) -> XMLNode? { guard let attribute = _CFXMLNodeHasProp(_xmlNode, name) else { return nil } return XMLNode._objectNodeForNode(attribute) } /*! @method attributeForLocalName:URI: @abstract Returns an attribute matching this localname URI pair. */ open func attribute(forLocalName localName: String, uri URI: String?) -> XMLNode? { NSUnimplemented() } /*! @method addNamespace:URI: @abstract Adds a namespace. Namespaces with duplicate names are not added. */ open func addNamespace(_ aNamespace: XMLNode) { if ((namespaces ?? []).flatMap({ $0.name }).contains(aNamespace.name ?? "")) { return } _CFXMLAddNamespace(_xmlNode, aNamespace._xmlNode) } /*! @method addNamespace:URI: @abstract Removes a namespace with a particular name. */ open func removeNamespace(forPrefix name: String) { _CFXMLRemoveNamespace(_xmlNode, name) } /*! @method namespaces @abstract Set the namespaces. In the case of duplicate names, the first namespace with the name is used. */ open var namespaces: [XMLNode]? { get { var count: Int = 0 if let result = _CFXMLNamespaces(_xmlNode, &count) { defer { free(result) } let namespacePtrs = UnsafeBufferPointer<_CFXMLNodePtr>(start: result, count: count) return namespacePtrs.map { XMLNode._objectNodeForNode($0) } } return nil } set { if var nodes = newValue?.map({ $0._xmlNode }) { nodes.withUnsafeMutableBufferPointer({ (bufPtr) in _CFXMLSetNamespaces(_xmlNode, bufPtr.baseAddress, bufPtr.count) }) } else { _CFXMLSetNamespaces(_xmlNode, nil, 0); } } } /*! @method namespaceForPrefix: @abstract Returns the namespace matching this prefix. */ open func namespace(forPrefix name: String) -> XMLNode? { NSUnimplemented() } /*! @method resolveNamespaceForName: @abstract Returns the namespace who matches the prefix of the name given. Looks in the entire namespace chain. */ open func resolveNamespace(forName name: String) -> XMLNode? { NSUnimplemented() } /*! @method resolvePrefixForNamespaceURI: @abstract Returns the URI of this prefix. Looks in the entire namespace chain. */ open func resolvePrefix(forNamespaceURI namespaceURI: String) -> String? { NSUnimplemented() } /*! @method insertChild:atIndex: @abstract Inserts a child at a particular index. */ open func insertChild(_ child: XMLNode, at index: Int) { _insertChild(child, atIndex: index) } /*! @method insertChildren:atIndex: @abstract Insert several children at a particular index. */ open func insertChildren(_ children: [XMLNode], at index: Int) { _insertChildren(children, atIndex: index) } /*! @method removeChildAtIndex:atIndex: @abstract Removes a child at a particular index. */ open func removeChild(at index: Int) { _removeChildAtIndex(index) } /*! @method setChildren: @abstract Removes all existing children and replaces them with the new children. Set children to nil to simply remove all children. */ open func setChildren(_ children: [XMLNode]?) { _setChildren(children) } /*! @method addChild: @abstract Adds a child to the end of the existing children. */ open func addChild(_ child: XMLNode) { _addChild(child) } /*! @method replaceChildAtIndex:withNode: @abstract Replaces a child at a particular index with another child. */ open func replaceChild(at index: Int, with node: XMLNode) { _replaceChildAtIndex(index, withNode: node) } /*! @method normalizeAdjacentTextNodesPreservingCDATA: @abstract Adjacent text nodes are coalesced. If the node's value is the empty string, it is removed. This should be called with a value of NO before using XQuery or XPath. */ open func normalizeAdjacentTextNodesPreservingCDATA(_ preserve: Bool) { NSUnimplemented() } internal override class func _objectNodeForNode(_ node: _CFXMLNodePtr) -> XMLElement { precondition(_CFXMLNodeGetType(node) == _kCFXMLTypeElement) if let privateData = _CFXMLNodeGetPrivateData(node) { return XMLElement.unretainedReference(privateData) } return XMLElement(ptr: node) } internal override init(ptr: _CFXMLNodePtr) { super.init(ptr: ptr) } } extension XMLElement { /*! @method setAttributesAs: @abstract Set the attributes base on a name-value dictionary. @discussion This method is deprecated and does not function correctly. Use -setAttributesWith: instead. */ @available(*, unavailable, renamed:"setAttributesWith") public func setAttributesAs(_ attributes: [NSObject : AnyObject]) { NSUnimplemented() } }
apache-2.0
41bceaf01fe6d8ba35aa8fee9ed6867c
33.175595
179
0.617086
4.639596
false
false
false
false
AngryLi/Onmyouji
Carthage/Checkouts/IQKeyboardManager/Demo/Swift_Demo/ViewController/TextFieldViewController.swift
1
5324
// // TextFieldViewController.swift // IQKeyboard // // Created by Iftekhar on 23/09/14. // Copyright (c) 2014 Iftekhar. All rights reserved. // import UIKit import IQKeyboardManagerSwift import IQDropDownTextField class TextFieldViewController: UIViewController, UITextViewDelegate, UIPopoverPresentationControllerDelegate { @IBOutlet fileprivate var textField3 : UITextField! @IBOutlet var textView1: IQTextView! @IBOutlet fileprivate var dropDownTextField : IQDropDownTextField! @IBOutlet fileprivate var buttonPush : UIButton! @IBOutlet fileprivate var buttonPresent : UIButton! func previousAction(_ sender : UITextField) { print("PreviousAction") } func nextAction(_ sender : UITextField) { print("nextAction") } func doneAction(_ sender : UITextField) { print("doneAction") } override func viewDidLoad() { super.viewDidLoad() textView1.delegate = self textField3.keyboardToolbar.previousBarButton.setTarget(self, action: #selector(self.previousAction(_:))) textField3.keyboardToolbar.nextBarButton.setTarget(self, action: #selector(self.nextAction(_:))) textField3.keyboardToolbar.doneBarButton.setTarget(self, action: #selector(self.doneAction(_:))) dropDownTextField.keyboardDistanceFromTextField = 150; var itemLists = [String]() itemLists.append("Zero Line Of Code") itemLists.append("No More UIScrollView") itemLists.append("No More Subclasses") itemLists.append("No More Manual Work") itemLists.append("No More #imports") itemLists.append("Device Orientation support") itemLists.append("UITextField Category for Keyboard") itemLists.append("Enable/Desable Keyboard Manager") itemLists.append("Customize InputView support") itemLists.append("IQTextView for placeholder support") itemLists.append("Automanage keyboard toolbar") itemLists.append("Can set keyboard and textFiled distance") itemLists.append("Can resign on touching outside") itemLists.append("Auto adjust textView's height") itemLists.append("Adopt tintColor from textField") itemLists.append("Customize keyboardAppearance") itemLists.append("Play sound on next/prev/done") dropDownTextField.itemList = itemLists } override func viewWillAppear(_ animated : Bool) { super.viewWillAppear(animated) if (self.presentingViewController != nil) { buttonPush.isHidden = true buttonPresent.setTitle("Dismiss", for:UIControlState()) } } @IBAction func presentClicked (_ sender: AnyObject!) { if self.presentingViewController == nil { let controller: UIViewController = (storyboard?.instantiateViewController(withIdentifier: "TextFieldViewController"))! let navController : UINavigationController = UINavigationController(rootViewController: controller) navController.navigationBar.tintColor = self.navigationController?.navigationBar.tintColor navController.navigationBar.barTintColor = self.navigationController?.navigationBar.barTintColor navController.navigationBar.titleTextAttributes = self.navigationController?.navigationBar.titleTextAttributes navController.modalTransitionStyle = UIModalTransitionStyle(rawValue: Int(arc4random()%4))! // TransitionStylePartialCurl can only be presented by FullScreen style. if (navController.modalTransitionStyle == UIModalTransitionStyle.partialCurl) { navController.modalPresentationStyle = UIModalPresentationStyle.fullScreen } else { navController.modalPresentationStyle = UIModalPresentationStyle.formSheet } present(navController, animated: true, completion: nil) } else { dismiss(animated: true, completion: nil) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { if identifier == "SettingsNavigationController" { let controller = segue.destination controller.modalPresentationStyle = .popover controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem let heightWidth = max(UIScreen.main.bounds.width, UIScreen.main.bounds.height); controller.preferredContentSize = CGSize(width: heightWidth, height: heightWidth) controller.popoverPresentationController?.delegate = self } } } func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) { self.view.endEditing(true) } func textViewDidBeginEditing(_ textView: UITextView) { print("textViewDidBeginEditing"); } override var shouldAutorotate : Bool { return true } }
mit
ed6c3f587145f8bf3ddae688776a98c7
38.437037
130
0.675056
5.988751
false
false
false
false
QuazerTV/TinyPlayer
Examples/Demo/TinyPlayerDemo/RootViewModel.swift
2
2775
// // RootViewModel.swift // TinyPlayerDemo // // Created by Xi Chen on 2017/2/26. // Copyright © 2017年 CocoaPods. All rights reserved. // import Foundation import UIKit import TinyPlayer class RootViewModel { internal weak var viewDelegate: RootViewUpdateDelegate? internal var playButtonDisplayMode: PlayButtonDisplayMode = .playButton /** A command receiver will take commands from this view model. */ internal weak var commandReceiver: RootViewModelCommandReceiver? init(viewDelegate: RootViewUpdateDelegate) { self.viewDelegate = viewDelegate } /* UI update logic. */ func needToUpdatePlayButtonMode(_ buttonMode: PlayButtonDisplayMode) { guard playButtonDisplayMode != buttonMode else { return } playButtonDisplayMode = buttonMode viewDelegate?.updatePlayButtonToMode(buttonMode: playButtonDisplayMode) } } // MARK: - Handle commands received from the correspond view controller. extension RootViewModel { func playButtonTapped() { commandReceiver?.playButtonTapped() } func seekBackwardsFor5Secs() { commandReceiver?.seekBackwardsFor5Secs() } func seekForwardsFor5Secs() { commandReceiver?.seekForwardsFor5Secs() } func freePlayerItemResource() { commandReceiver?.freePlayerItemResource() } } // MARK: - PlayerViewModelObserver extension RootViewModel: PlayerViewModelObserver { func demoPlayerIsReadyToStartPlayingFromBeginning(isReady: Bool) { needToUpdatePlayButtonMode(.playButton) } func demoPlayerHasUpdatedState(state: TinyPlayerState) { if state == .playing { needToUpdatePlayButtonMode(.pauseButton) } else if state == .paused { needToUpdatePlayButtonMode(.playButton) } } } // MARK: - Additional definitions /** Display modes of the play/pause button. */ internal enum PlayButtonDisplayMode { case playButton case pauseButton case hidden } /** This protocol defines the UI update commands that the coorespond view needs to implement. */ internal protocol RootViewUpdateDelegate: class { func updatePlayButtonToMode(buttonMode: PlayButtonDisplayMode) } /** This protocol defines all the commands that a CommandReceiver can take as input. In our case, a CommandReceiver will be a VideoPlayerViewModel instance. */ internal protocol RootViewModelCommandReceiver: class { func playButtonTapped() func seekBackwardsFor5Secs() func seekForwardsFor5Secs() func freePlayerItemResource() }
mit
39bf21a6c1c1d4e7b24b4073f5083d79
22.692308
93
0.67316
5.067642
false
false
false
false
filipealva/WWDC15-Scholarship
Filipe Alvarenga/View/GreetingsView.swift
1
1925
// // GreetingsView.swift // Filipe Alvarenga // // Created by Filipe Alvarenga on 23/04/15. // Copyright (c) 2015 Filipe Alvarenga. All rights reserved. // import UIKit class GreetingsView: UIView { @IBOutlet weak var shimmeringView: FBShimmeringView! @IBOutlet weak var scrollDownArrow: UIImageView! @IBOutlet weak var greetingsContent: UIView! @IBOutlet weak var greetingsMessageContainer: UIView! @IBOutlet weak var greetingsContentHeightConstraint: NSLayoutConstraint! @IBOutlet weak var greetingsMessageContainerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var greetingsMessage: UILabel! override func drawRect(rect: CGRect) { super.drawRect(rect) setupShimmeringView() } override func layoutSubviews() { super.layoutSubviews() frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: superview!.bounds.width, height: superview!.bounds.height) adjustConstraintsToFit() } // MARK: - Views Setup func setupShimmeringView() { shimmeringView.contentView = scrollDownArrow shimmeringView.shimmering = true shimmeringView.shimmeringPauseDuration = 0.4 shimmeringView.shimmeringAnimationOpacity = 0.2 shimmeringView.shimmeringOpacity = 1.0 shimmeringView.shimmeringSpeed = 70 shimmeringView.shimmeringHighlightLength = 1.0 shimmeringView.shimmeringDirection = .Right shimmeringView.shimmeringBeginFadeDuration = 0.1 shimmeringView.shimmeringEndFadeDuration = 0.3 } // MARK: - Resizing Helpers func adjustConstraintsToFit() { greetingsMessage.layoutIfNeeded() let containerHeight = greetingsMessage.frame.origin.y + greetingsMessage.frame.size.height + 8.0 greetingsMessageContainerHeightConstraint.constant = containerHeight } }
mit
b59eafcc5cc4ff46b391ee1db6215125
31.627119
126
0.698701
5.106101
false
false
false
false
infakt/DrawerController
KitchenSink/ExampleFiles/VisualStateManager/ExampleDrawerVisualStateManager.swift
4
4193
// Copyright (c) 2014 evolved.io (http://evolved.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import DrawerController enum DrawerAnimationType: Int { case None case Slide case SlideAndScale case SwingingDoor case Parallax case AnimatedBarButton } class ExampleDrawerVisualStateManager: NSObject { var leftDrawerAnimationType: DrawerAnimationType = .Parallax var rightDrawerAnimationType: DrawerAnimationType = .Parallax class var sharedManager: ExampleDrawerVisualStateManager { struct Static { static let instance: ExampleDrawerVisualStateManager = ExampleDrawerVisualStateManager() } return Static.instance } func drawerVisualStateBlockForDrawerSide(drawerSide: DrawerSide) -> DrawerControllerDrawerVisualStateBlock? { var animationType: DrawerAnimationType if drawerSide == DrawerSide.Left { animationType = self.leftDrawerAnimationType } else { animationType = self.rightDrawerAnimationType } var visualStateBlock: DrawerControllerDrawerVisualStateBlock? switch animationType { case .Slide: visualStateBlock = DrawerVisualState.slideVisualStateBlock case .SlideAndScale: visualStateBlock = DrawerVisualState.slideAndScaleVisualStateBlock case .Parallax: visualStateBlock = DrawerVisualState.parallaxVisualStateBlock(2.0) case .SwingingDoor: visualStateBlock = DrawerVisualState.swingingDoorVisualStateBlock case .AnimatedBarButton: visualStateBlock = DrawerVisualState.animatedHamburgerButtonVisualStateBlock default: visualStateBlock = { drawerController, drawerSide, percentVisible in var sideDrawerViewController: UIViewController? var transform = CATransform3DIdentity var maxDrawerWidth: CGFloat = 0.0 if drawerSide == .Left { sideDrawerViewController = drawerController.leftDrawerViewController maxDrawerWidth = drawerController.maximumLeftDrawerWidth } else if drawerSide == .Right { sideDrawerViewController = drawerController.rightDrawerViewController maxDrawerWidth = drawerController.maximumRightDrawerWidth } if percentVisible > 1.0 { transform = CATransform3DMakeScale(percentVisible, 1.0, 1.0) if drawerSide == .Left { transform = CATransform3DTranslate(transform, maxDrawerWidth * (percentVisible - 1.0) / 2, 0.0, 0.0) } else if drawerSide == .Right { transform = CATransform3DTranslate(transform, -maxDrawerWidth * (percentVisible - 1.0) / 2, 0.0, 0.0) } } sideDrawerViewController?.view.layer.transform = transform } } return visualStateBlock } }
mit
38321b06a3365e4bde325e0b594d2723
42.226804
125
0.664202
5.767538
false
false
false
false
ahoppen/swift
test/Generics/sr16040.swift
5
1548
// RUN: %target-swift-frontend -typecheck %s -disable-availability-checking -debug-generic-signatures 2>&1 | %FileCheck %s public protocol View { associatedtype Body : View var body: Body { get } } public struct Text : View { public init(_: String) {} public var body: Self { return self } } public protocol DisplayableValue {} public protocol SingleValueDisplay: View { associatedtype DisplayedValue init (_ singleValue: DisplayedValue) var displayedValue: DisplayedValue { get } } // CHECK-LABEL: .RawDisplayableValue@ // CHECK-NEXT: Requirement signature: <Self where Self : DisplayableValue, Self == Self.[RawDisplayableValue]RawDisplay.[SingleValueDisplay]DisplayedValue, Self.[RawDisplayableValue]RawDisplay : SingleValueDisplay> public protocol RawDisplayableValue: DisplayableValue { associatedtype RawDisplay: SingleValueDisplay where RawDisplay.DisplayedValue == Self } // CHECK-LABEL: .RawTextDisplayableValue@ // CHECK-NEXT: Requirement signature: <Self where Self : CustomStringConvertible, Self : RawDisplayableValue, Self.[RawDisplayableValue]RawDisplay == RawTextDisplay<Self>> public protocol RawTextDisplayableValue: RawDisplayableValue where Self: CustomStringConvertible, RawDisplay == RawTextDisplay<Self> { } public struct RawTextDisplay <Value: CustomStringConvertible>: SingleValueDisplay { public var displayedValue: Value public init (_ singleValue: Value) { self.displayedValue = singleValue } public var body: some View { Text(displayedValue.description) } }
apache-2.0
bb5c09dd470ed1981a61e45ae536ea62
34.181818
214
0.76938
4.461095
false
false
false
false
dreamsxin/swift
test/1_stdlib/Runtime.swift
2
43754
// RUN: rm -rf %t && mkdir %t // // RUN: %target-build-swift -parse-stdlib -module-name a %s -o %t.out // RUN: %target-run %t.out // REQUIRES: executable_test import Swift import StdlibUnittest import SwiftShims @warn_unused_result @_silgen_name("swift_demangle") public func _stdlib_demangleImpl( mangledName: UnsafePointer<UInt8>?, mangledNameLength: UInt, outputBuffer: UnsafeMutablePointer<UInt8>?, outputBufferSize: UnsafeMutablePointer<UInt>?, flags: UInt32 ) -> UnsafeMutablePointer<CChar>? @warn_unused_result func _stdlib_demangleName(_ mangledName: String) -> String { return mangledName.nulTerminatedUTF8.withUnsafeBufferPointer { (mangledNameUTF8) in let demangledNamePtr = _stdlib_demangleImpl( mangledName: mangledNameUTF8.baseAddress, mangledNameLength: UInt(mangledNameUTF8.count - 1), outputBuffer: nil, outputBufferSize: nil, flags: 0) if let demangledNamePtr = demangledNamePtr { let demangledName = String(cString: demangledNamePtr) _swift_stdlib_free(demangledNamePtr) return demangledName } return mangledName } } var swiftObjectCanaryCount = 0 class SwiftObjectCanary { init() { swiftObjectCanaryCount += 1 } deinit { swiftObjectCanaryCount -= 1 } } struct SwiftObjectCanaryStruct { var ref = SwiftObjectCanary() } var Runtime = TestSuite("Runtime") Runtime.test("_canBeClass") { expectEqual(1, _canBeClass(SwiftObjectCanary.self)) expectEqual(0, _canBeClass(SwiftObjectCanaryStruct.self)) typealias SwiftClosure = () -> () expectEqual(0, _canBeClass(SwiftClosure.self)) } //===----------------------------------------------------------------------===// // The protocol should be defined in the standard library, otherwise the cast // does not work. typealias P1 = Boolean typealias P2 = CustomStringConvertible protocol Q1 {} // A small struct that can be stored inline in an opaque buffer. struct StructConformsToP1 : Boolean, Q1 { var boolValue: Bool { return true } } // A small struct that can be stored inline in an opaque buffer. struct Struct2ConformsToP1<T : Boolean> : Boolean, Q1 { init(_ value: T) { self.value = value } var boolValue: Bool { return value.boolValue } var value: T } // A large struct that cannot be stored inline in an opaque buffer. struct Struct3ConformsToP2 : CustomStringConvertible, Q1 { var a: UInt64 = 10 var b: UInt64 = 20 var c: UInt64 = 30 var d: UInt64 = 40 var description: String { // Don't rely on string interpolation, it uses the casts that we are trying // to test. var result = "" result += _uint64ToString(a) + " " result += _uint64ToString(b) + " " result += _uint64ToString(c) + " " result += _uint64ToString(d) return result } } // A large struct that cannot be stored inline in an opaque buffer. struct Struct4ConformsToP2<T : CustomStringConvertible> : CustomStringConvertible, Q1 { var value: T var e: UInt64 = 50 var f: UInt64 = 60 var g: UInt64 = 70 var h: UInt64 = 80 init(_ value: T) { self.value = value } var description: String { // Don't rely on string interpolation, it uses the casts that we are trying // to test. var result = value.description + " " result += _uint64ToString(e) + " " result += _uint64ToString(f) + " " result += _uint64ToString(g) + " " result += _uint64ToString(h) return result } } struct StructDoesNotConformToP1 : Q1 {} class ClassConformsToP1 : Boolean, Q1 { var boolValue: Bool { return true } } class Class2ConformsToP1<T : Boolean> : Boolean, Q1 { init(_ value: T) { self.value = [value] } var boolValue: Bool { return value[0].boolValue } // FIXME: should be "var value: T", but we don't support it now. var value: Array<T> } class ClassDoesNotConformToP1 : Q1 {} Runtime.test("dynamicCasting with as") { var someP1Value = StructConformsToP1() var someP1Value2 = Struct2ConformsToP1(true) var someNotP1Value = StructDoesNotConformToP1() var someP2Value = Struct3ConformsToP2() var someP2Value2 = Struct4ConformsToP2(Struct3ConformsToP2()) var someP1Ref = ClassConformsToP1() var someP1Ref2 = Class2ConformsToP1(true) var someNotP1Ref = ClassDoesNotConformToP1() expectTrue(someP1Value is P1) expectTrue(someP1Value2 is P1) expectFalse(someNotP1Value is P1) expectTrue(someP2Value is P2) expectTrue(someP2Value2 is P2) expectTrue(someP1Ref is P1) expectTrue(someP1Ref2 is P1) expectFalse(someNotP1Ref is P1) expectTrue(someP1Value as P1 is P1) expectTrue(someP1Value2 as P1 is P1) expectTrue(someP2Value as P2 is P2) expectTrue(someP2Value2 as P2 is P2) expectTrue(someP1Ref as P1 is P1) expectTrue(someP1Value as Q1 is P1) expectTrue(someP1Value2 as Q1 is P1) expectFalse(someNotP1Value as Q1 is P1) expectTrue(someP2Value as Q1 is P2) expectTrue(someP2Value2 as Q1 is P2) expectTrue(someP1Ref as Q1 is P1) expectTrue(someP1Ref2 as Q1 is P1) expectFalse(someNotP1Ref as Q1 is P1) expectTrue(someP1Value as Any is P1) expectTrue(someP1Value2 as Any is P1) expectFalse(someNotP1Value as Any is P1) expectTrue(someP2Value as Any is P2) expectTrue(someP2Value2 as Any is P2) expectTrue(someP1Ref as Any is P1) expectTrue(someP1Ref2 as Any is P1) expectFalse(someNotP1Ref as Any is P1) expectTrue(someP1Ref as AnyObject is P1) expectTrue(someP1Ref2 as AnyObject is P1) expectFalse(someNotP1Ref as AnyObject is P1) expectTrue((someP1Value as P1).boolValue) expectTrue((someP1Value2 as P1).boolValue) expectEqual("10 20 30 40", (someP2Value as P2).description) expectEqual("10 20 30 40 50 60 70 80", (someP2Value2 as P2).description) expectTrue((someP1Ref as P1).boolValue) expectTrue((someP1Ref2 as P1).boolValue) expectTrue(((someP1Value as Q1) as! P1).boolValue) expectTrue(((someP1Value2 as Q1) as! P1).boolValue) expectEqual("10 20 30 40", ((someP2Value as Q1) as! P2).description) expectEqual("10 20 30 40 50 60 70 80", ((someP2Value2 as Q1) as! P2).description) expectTrue(((someP1Ref as Q1) as! P1).boolValue) expectTrue(((someP1Ref2 as Q1) as! P1).boolValue) expectTrue(((someP1Value as Any) as! P1).boolValue) expectTrue(((someP1Value2 as Any) as! P1).boolValue) expectEqual("10 20 30 40", ((someP2Value as Any) as! P2).description) expectEqual("10 20 30 40 50 60 70 80", ((someP2Value2 as Any) as! P2).description) expectTrue(((someP1Ref as Any) as! P1).boolValue) expectTrue(((someP1Ref2 as Any) as! P1).boolValue) expectTrue(((someP1Ref as AnyObject) as! P1).boolValue) expectEmpty((someNotP1Value as? P1)) expectEmpty((someNotP1Ref as? P1)) expectTrue(((someP1Value as Q1) as? P1)!.boolValue) expectTrue(((someP1Value2 as Q1) as? P1)!.boolValue) expectEmpty(((someNotP1Value as Q1) as? P1)) expectEqual("10 20 30 40", ((someP2Value as Q1) as? P2)!.description) expectEqual("10 20 30 40 50 60 70 80", ((someP2Value2 as Q1) as? P2)!.description) expectTrue(((someP1Ref as Q1) as? P1)!.boolValue) expectTrue(((someP1Ref2 as Q1) as? P1)!.boolValue) expectEmpty(((someNotP1Ref as Q1) as? P1)) expectTrue(((someP1Value as Any) as? P1)!.boolValue) expectTrue(((someP1Value2 as Any) as? P1)!.boolValue) expectEmpty(((someNotP1Value as Any) as? P1)) expectEqual("10 20 30 40", ((someP2Value as Any) as? P2)!.description) expectEqual("10 20 30 40 50 60 70 80", ((someP2Value2 as Any) as? P2)!.description) expectTrue(((someP1Ref as Any) as? P1)!.boolValue) expectTrue(((someP1Ref2 as Any) as? P1)!.boolValue) expectEmpty(((someNotP1Ref as Any) as? P1)) expectTrue(((someP1Ref as AnyObject) as? P1)!.boolValue) expectTrue(((someP1Ref2 as AnyObject) as? P1)!.boolValue) expectEmpty(((someNotP1Ref as AnyObject) as? P1)) let doesThrow: (Int) throws -> Int = { $0 } let doesNotThrow: (String) -> String = { $0 } var any: Any = doesThrow expectTrue(doesThrow as Any is (Int) throws -> Int) expectFalse(doesThrow as Any is (String) throws -> Int) expectFalse(doesThrow as Any is (String) throws -> String) expectFalse(doesThrow as Any is (Int) throws -> String) expectFalse(doesThrow as Any is (Int) -> Int) expectFalse(doesThrow as Any is (String) throws -> String) expectFalse(doesThrow as Any is (String) -> String) expectTrue(doesNotThrow as Any is (String) throws -> String) expectTrue(doesNotThrow as Any is (String) -> String) expectFalse(doesNotThrow as Any is (Int) -> String) expectFalse(doesNotThrow as Any is (Int) -> Int) expectFalse(doesNotThrow as Any is (String) -> Int) expectFalse(doesNotThrow as Any is (Int) throws -> Int) expectFalse(doesNotThrow as Any is (Int) -> Int) } extension Int { class ExtensionClassConformsToP2 : P2 { var description: String { return "abc" } } private class PrivateExtensionClassConformsToP2 : P2 { var description: String { return "def" } } } Runtime.test("dynamic cast to existential with cross-module extensions") { let internalObj = Int.ExtensionClassConformsToP2() let privateObj = Int.PrivateExtensionClassConformsToP2() expectTrue(internalObj is P2) expectTrue(privateObj is P2) } class SomeClass {} struct SomeStruct {} enum SomeEnum { case A init() { self = .A } } Runtime.test("typeName") { expectEqual("a.SomeClass", _typeName(SomeClass.self)) expectEqual("a.SomeStruct", _typeName(SomeStruct.self)) expectEqual("a.SomeEnum", _typeName(SomeEnum.self)) expectEqual("protocol<>.Protocol", _typeName(Any.Protocol.self)) expectEqual("Swift.AnyObject.Protocol", _typeName(AnyObject.Protocol.self)) expectEqual("Swift.AnyObject.Type.Protocol", _typeName(AnyClass.Protocol.self)) expectEqual("Swift.Optional<Swift.AnyObject>.Type", _typeName((AnyObject?).Type.self)) var a: Any = SomeClass() expectEqual("a.SomeClass", _typeName(a.dynamicType)) a = SomeStruct() expectEqual("a.SomeStruct", _typeName(a.dynamicType)) a = SomeEnum() expectEqual("a.SomeEnum", _typeName(a.dynamicType)) a = AnyObject.self expectEqual("Swift.AnyObject.Protocol", _typeName(a.dynamicType)) a = AnyClass.self expectEqual("Swift.AnyObject.Type.Protocol", _typeName(a.dynamicType)) a = (AnyObject?).self expectEqual("Swift.Optional<Swift.AnyObject>.Type", _typeName(a.dynamicType)) a = Any.self expectEqual("protocol<>.Protocol", _typeName(a.dynamicType)) } class SomeSubclass : SomeClass {} protocol SomeProtocol {} class SomeConformingClass : SomeProtocol {} Runtime.test("typeByName") { expectTrue(_typeByName("a.SomeClass") == SomeClass.self) expectTrue(_typeByName("a.SomeSubclass") == SomeSubclass.self) // name lookup will be via protocol conformance table expectTrue(_typeByName("a.SomeConformingClass") == SomeConformingClass.self) // FIXME: NonObjectiveCBase is slated to die, but I can't think of another // nongeneric public class in the stdlib... expectTrue(_typeByName("Swift.NonObjectiveCBase") == NonObjectiveCBase.self) } Runtime.test("demangleName") { expectEqual("", _stdlib_demangleName("")) expectEqual("abc", _stdlib_demangleName("abc")) expectEqual("\0", _stdlib_demangleName("\0")) expectEqual("Swift.Double", _stdlib_demangleName("_TtSd")) expectEqual("x.a : x.Foo<x.Foo<x.Foo<Swift.Int, Swift.Int>, x.Foo<Swift.Int, Swift.Int>>, x.Foo<x.Foo<Swift.Int, Swift.Int>, x.Foo<Swift.Int, Swift.Int>>>", _stdlib_demangleName("_Tv1x1aGCS_3FooGS0_GS0_SiSi_GS0_SiSi__GS0_GS0_SiSi_GS0_SiSi___")) expectEqual("Foobar", _stdlib_demangleName("_TtC13__lldb_expr_46Foobar")) } Runtime.test("_stdlib_atomicCompareExchangeStrongPtr") { typealias IntPtr = UnsafeMutablePointer<Int> var origP1 = IntPtr(bitPattern: 0x10101010)! var origP2 = IntPtr(bitPattern: 0x20202020)! var origP3 = IntPtr(bitPattern: 0x30303030)! do { var object = origP1 var expected = origP1 let r = _stdlib_atomicCompareExchangeStrongPtr( object: &object, expected: &expected, desired: origP2) expectTrue(r) expectEqual(origP2, object) expectEqual(origP1, expected) } do { var object = origP1 var expected = origP2 let r = _stdlib_atomicCompareExchangeStrongPtr( object: &object, expected: &expected, desired: origP3) expectFalse(r) expectEqual(origP1, object) expectEqual(origP1, expected) } struct FooStruct { var i: Int var object: IntPtr var expected: IntPtr init(_ object: IntPtr, _ expected: IntPtr) { self.i = 0 self.object = object self.expected = expected } } do { var foo = FooStruct(origP1, origP1) let r = _stdlib_atomicCompareExchangeStrongPtr( object: &foo.object, expected: &foo.expected, desired: origP2) expectTrue(r) expectEqual(origP2, foo.object) expectEqual(origP1, foo.expected) } do { var foo = FooStruct(origP1, origP2) let r = _stdlib_atomicCompareExchangeStrongPtr( object: &foo.object, expected: &foo.expected, desired: origP3) expectFalse(r) expectEqual(origP1, foo.object) expectEqual(origP1, foo.expected) } } Runtime.test("casting AnyObject to class metatypes") { do { var ao: AnyObject = SomeClass() expectTrue(ao as? Any.Type == nil) expectTrue(ao as? AnyClass == nil) } do { var a: Any = SomeClass() expectTrue(a as? Any.Type == nil) expectTrue(a as? AnyClass == nil) a = SomeClass.self expectTrue(a as? Any.Type == SomeClass.self) expectTrue(a as? AnyClass == SomeClass.self) expectTrue(a as? SomeClass.Type == SomeClass.self) } } class Malkovich: Malkovichable { var malkovich: String { return "malkovich" } } protocol Malkovichable: class { var malkovich: String { get } } struct GenericStructWithReferenceStorage<T> { var a: T unowned(safe) var unownedConcrete: Malkovich unowned(unsafe) var unmanagedConcrete: Malkovich weak var weakConcrete: Malkovich? unowned(safe) var unownedProto: Malkovichable unowned(unsafe) var unmanagedProto: Malkovichable weak var weakProto: Malkovichable? } func exerciseReferenceStorageInGenericContext<T>( _ x: GenericStructWithReferenceStorage<T>, forceCopy y: GenericStructWithReferenceStorage<T> ) { expectEqual(x.unownedConcrete.malkovich, "malkovich") expectEqual(x.unmanagedConcrete.malkovich, "malkovich") expectEqual(x.weakConcrete!.malkovich, "malkovich") expectEqual(x.unownedProto.malkovich, "malkovich") expectEqual(x.unmanagedProto.malkovich, "malkovich") expectEqual(x.weakProto!.malkovich, "malkovich") expectEqual(y.unownedConcrete.malkovich, "malkovich") expectEqual(y.unmanagedConcrete.malkovich, "malkovich") expectEqual(y.weakConcrete!.malkovich, "malkovich") expectEqual(y.unownedProto.malkovich, "malkovich") expectEqual(y.unmanagedProto.malkovich, "malkovich") expectEqual(y.weakProto!.malkovich, "malkovich") } Runtime.test("Struct layout with reference storage types") { let malkovich = Malkovich() let x = GenericStructWithReferenceStorage(a: malkovich, unownedConcrete: malkovich, unmanagedConcrete: malkovich, weakConcrete: malkovich, unownedProto: malkovich, unmanagedProto: malkovich, weakProto: malkovich) exerciseReferenceStorageInGenericContext(x, forceCopy: x) expectEqual(x.unownedConcrete.malkovich, "malkovich") expectEqual(x.unmanagedConcrete.malkovich, "malkovich") expectEqual(x.weakConcrete!.malkovich, "malkovich") expectEqual(x.unownedProto.malkovich, "malkovich") expectEqual(x.unmanagedProto.malkovich, "malkovich") expectEqual(x.weakProto!.malkovich, "malkovich") // Make sure malkovich lives long enough. print(malkovich) } var Reflection = TestSuite("Reflection") func wrap1 (_ x: Any) -> Any { return x } func wrap2<T>(_ x: T) -> Any { return wrap1(x) } func wrap3 (_ x: Any) -> Any { return wrap2(x) } func wrap4<T>(_ x: T) -> Any { return wrap3(x) } func wrap5 (_ x: Any) -> Any { return wrap4(x) } class JustNeedAMetatype {} Reflection.test("nested existential containers") { let wrapped = wrap5(JustNeedAMetatype.self) expectEqual("\(wrapped)", "JustNeedAMetatype") } Reflection.test("dumpToAStream") { var output = "" dump([ 42, 4242 ], to: &output) expectEqual("▿ 2 elements\n - 42\n - 4242\n", output) } struct StructWithDefaultMirror { let s: String init (_ s: String) { self.s = s } } Reflection.test("Struct/NonGeneric/DefaultMirror") { do { var output = "" dump(StructWithDefaultMirror("123"), to: &output) expectEqual("▿ a.StructWithDefaultMirror\n - s: \"123\"\n", output) } do { // Build a String around an interpolation as a way of smoke-testing that // the internal _Mirror implementation gets memory management right. var output = "" dump(StructWithDefaultMirror("\(456)"), to: &output) expectEqual("▿ a.StructWithDefaultMirror\n - s: \"456\"\n", output) } expectEqual( .`struct`, Mirror(reflecting: StructWithDefaultMirror("")).displayStyle) } struct GenericStructWithDefaultMirror<T, U> { let first: T let second: U } Reflection.test("Struct/Generic/DefaultMirror") { do { var value = GenericStructWithDefaultMirror<Int, [Any?]>( first: 123, second: ["abc", 456, 789.25]) var output = "" dump(value, to: &output) let expected = "▿ a.GenericStructWithDefaultMirror<Swift.Int, Swift.Array<Swift.Optional<protocol<>>>>\n" + " - first: 123\n" + " ▿ second: 3 elements\n" + " ▿ Optional(\"abc\")\n" + " - some: \"abc\"\n" + " ▿ Optional(456)\n" + " - some: 456\n" + " ▿ Optional(789.25)\n" + " - some: 789.25\n" expectEqual(expected, output) } } enum NoPayloadEnumWithDefaultMirror { case A, ß } Reflection.test("Enum/NoPayload/DefaultMirror") { do { let value: [NoPayloadEnumWithDefaultMirror] = [.A, .ß] var output = "" dump(value, to: &output) let expected = "▿ 2 elements\n" + " - a.NoPayloadEnumWithDefaultMirror.A\n" + " - a.NoPayloadEnumWithDefaultMirror.ß\n" expectEqual(expected, output) } } enum SingletonNonGenericEnumWithDefaultMirror { case OnlyOne(Int) } Reflection.test("Enum/SingletonNonGeneric/DefaultMirror") { do { let value = SingletonNonGenericEnumWithDefaultMirror.OnlyOne(5) var output = "" dump(value, to: &output) let expected = "▿ a.SingletonNonGenericEnumWithDefaultMirror.OnlyOne\n" + " - OnlyOne: 5\n" expectEqual(expected, output) } } enum SingletonGenericEnumWithDefaultMirror<T> { case OnlyOne(T) } Reflection.test("Enum/SingletonGeneric/DefaultMirror") { do { let value = SingletonGenericEnumWithDefaultMirror.OnlyOne("IIfx") var output = "" dump(value, to: &output) let expected = "▿ a.SingletonGenericEnumWithDefaultMirror<Swift.String>.OnlyOne\n" + " - OnlyOne: \"IIfx\"\n" expectEqual(expected, output) } expectEqual(0, LifetimeTracked.instances) do { let value = SingletonGenericEnumWithDefaultMirror.OnlyOne( LifetimeTracked(0)) expectEqual(1, LifetimeTracked.instances) var output = "" dump(value, to: &output) } expectEqual(0, LifetimeTracked.instances) } enum SinglePayloadNonGenericEnumWithDefaultMirror { case Cat case Dog case Volleyball(String, Int) } Reflection.test("Enum/SinglePayloadNonGeneric/DefaultMirror") { do { let value: [SinglePayloadNonGenericEnumWithDefaultMirror] = [.Cat, .Dog, .Volleyball("Wilson", 2000)] var output = "" dump(value, to: &output) let expected = "▿ 3 elements\n" + " - a.SinglePayloadNonGenericEnumWithDefaultMirror.Cat\n" + " - a.SinglePayloadNonGenericEnumWithDefaultMirror.Dog\n" + " ▿ a.SinglePayloadNonGenericEnumWithDefaultMirror.Volleyball\n" + " ▿ Volleyball: (2 elements)\n" + " - .0: \"Wilson\"\n" + " - .1: 2000\n" expectEqual(expected, output) } } enum SinglePayloadGenericEnumWithDefaultMirror<T, U> { case Well case Faucet case Pipe(T, U) } Reflection.test("Enum/SinglePayloadGeneric/DefaultMirror") { do { let value: [SinglePayloadGenericEnumWithDefaultMirror<Int, [Int]>] = [.Well, .Faucet, .Pipe(408, [415])] var output = "" dump(value, to: &output) let expected = "▿ 3 elements\n" + " - a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Well\n" + " - a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Faucet\n" + " ▿ a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Pipe\n" + " ▿ Pipe: (2 elements)\n" + " - .0: 408\n" + " ▿ .1: 1 element\n" + " - 415\n" expectEqual(expected, output) } } enum MultiPayloadTagBitsNonGenericEnumWithDefaultMirror { case Plus case SE30 case Classic(mhz: Int) case Performa(model: Int) } Reflection.test("Enum/MultiPayloadTagBitsNonGeneric/DefaultMirror") { do { let value: [MultiPayloadTagBitsNonGenericEnumWithDefaultMirror] = [.Plus, .SE30, .Classic(mhz: 16), .Performa(model: 220)] var output = "" dump(value, to: &output) let expected = "▿ 4 elements\n" + " - a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Plus\n" + " - a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.SE30\n" + " ▿ a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Classic\n" + " - Classic: 16\n" + " ▿ a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Performa\n" + " - Performa: 220\n" expectEqual(expected, output) } } class Floppy { let capacity: Int init(capacity: Int) { self.capacity = capacity } } class CDROM { let capacity: Int init(capacity: Int) { self.capacity = capacity } } enum MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror { case MacWrite case MacPaint case FileMaker case ClarisWorks(floppy: Floppy) case HyperCard(cdrom: CDROM) } Reflection.test("Enum/MultiPayloadSpareBitsNonGeneric/DefaultMirror") { do { let value: [MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror] = [.MacWrite, .MacPaint, .FileMaker, .ClarisWorks(floppy: Floppy(capacity: 800)), .HyperCard(cdrom: CDROM(capacity: 600))] var output = "" dump(value, to: &output) let expected = "▿ 5 elements\n" + " - a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacWrite\n" + " - a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacPaint\n" + " - a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.FileMaker\n" + " ▿ a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.ClarisWorks\n" + " ▿ ClarisWorks: a.Floppy #0\n" + " - capacity: 800\n" + " ▿ a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.HyperCard\n" + " ▿ HyperCard: a.CDROM #1\n" + " - capacity: 600\n" expectEqual(expected, output) } } enum MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror { case MacWrite case MacPaint case FileMaker case ClarisWorks(floppy: Bool) case HyperCard(cdrom: Bool) } Reflection.test("Enum/MultiPayloadTagBitsSmallNonGeneric/DefaultMirror") { do { let value: [MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror] = [.MacWrite, .MacPaint, .FileMaker, .ClarisWorks(floppy: true), .HyperCard(cdrom: false)] var output = "" dump(value, to: &output) let expected = "▿ 5 elements\n" + " - a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacWrite\n" + " - a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacPaint\n" + " - a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.FileMaker\n" + " ▿ a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.ClarisWorks\n" + " - ClarisWorks: true\n" + " ▿ a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.HyperCard\n" + " - HyperCard: false\n" expectEqual(expected, output) } } enum MultiPayloadGenericEnumWithDefaultMirror<T, U> { case IIe case IIgs case Centris(ram: T) case Quadra(hdd: U) case PowerBook170 case PowerBookDuo220 } Reflection.test("Enum/MultiPayloadGeneric/DefaultMirror") { do { let value: [MultiPayloadGenericEnumWithDefaultMirror<Int, String>] = [.IIe, .IIgs, .Centris(ram: 4096), .Quadra(hdd: "160MB"), .PowerBook170, .PowerBookDuo220] var output = "" dump(value, to: &output) let expected = "▿ 6 elements\n" + " - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIe\n" + " - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIgs\n" + " ▿ a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Centris\n" + " - Centris: 4096\n" + " ▿ a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Quadra\n" + " - Quadra: \"160MB\"\n" + " - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBook170\n" + " - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBookDuo220\n" expectEqual(expected, output) } expectEqual(0, LifetimeTracked.instances) do { let value = MultiPayloadGenericEnumWithDefaultMirror<LifetimeTracked, LifetimeTracked> .Quadra(hdd: LifetimeTracked(0)) expectEqual(1, LifetimeTracked.instances) var output = "" dump(value, to: &output) } expectEqual(0, LifetimeTracked.instances) } enum Foo<T> { indirect case Foo(Int) case Bar(T) } enum List<T> { case Nil indirect case Cons(first: T, rest: List<T>) } Reflection.test("Enum/IndirectGeneric/DefaultMirror") { let x = Foo<String>.Foo(22) let y = Foo<String>.Bar("twenty-two") expectEqual("\(x)", "Foo(22)") expectEqual("\(y)", "Bar(\"twenty-two\")") let list = List.Cons(first: 0, rest: .Cons(first: 1, rest: .Nil)) expectEqual("\(list)", "Cons(0, a.List<Swift.Int>.Cons(1, a.List<Swift.Int>.Nil))") } class Brilliant : CustomReflectable { let first: Int let second: String init(_ fst: Int, _ snd: String) { self.first = fst self.second = snd } var customMirror: Mirror { return Mirror(self, children: ["first": first, "second": second, "self": self]) } } /// Subclasses inherit their parents' custom mirrors. class Irradiant : Brilliant { init() { super.init(400, "") } } Reflection.test("CustomMirror") { do { var output = "" dump(Brilliant(123, "four five six"), to: &output) let expected = "▿ a.Brilliant #0\n" + " - first: 123\n" + " - second: \"four five six\"\n" + " ▿ self: a.Brilliant #0\n" expectEqual(expected, output) } do { var output = "" dump(Brilliant(123, "four five six"), to: &output, maxDepth: 0) expectEqual("▹ a.Brilliant #0\n", output) } do { var output = "" dump(Brilliant(123, "four five six"), to: &output, maxItems: 3) let expected = "▿ a.Brilliant #0\n" + " - first: 123\n" + " - second: \"four five six\"\n" + " (1 more child)\n" expectEqual(expected, output) } do { var output = "" dump(Brilliant(123, "four five six"), to: &output, maxItems: 2) let expected = "▿ a.Brilliant #0\n" + " - first: 123\n" + " (2 more children)\n" expectEqual(expected, output) } do { var output = "" dump(Brilliant(123, "four five six"), to: &output, maxItems: 1) let expected = "▿ a.Brilliant #0\n" + " (3 children)\n" expectEqual(expected, output) } do { // Check that object identifiers are unique to class instances. let a = Brilliant(1, "") let b = Brilliant(2, "") let c = Brilliant(3, "") // Equatable checkEquatable(true, ObjectIdentifier(a), ObjectIdentifier(a)) checkEquatable(false, ObjectIdentifier(a), ObjectIdentifier(b)) // Comparable func isComparable<X : Comparable>(_ x: X) {} isComparable(ObjectIdentifier(a)) // Check the ObjectIdentifier created is stable expectTrue( (ObjectIdentifier(a) < ObjectIdentifier(b)) != (ObjectIdentifier(a) > ObjectIdentifier(b))) expectFalse( ObjectIdentifier(a) >= ObjectIdentifier(b) && ObjectIdentifier(a) <= ObjectIdentifier(b)) // Check that ordering is transitive. expectEqual( [ ObjectIdentifier(a), ObjectIdentifier(b), ObjectIdentifier(c) ].sorted(), [ ObjectIdentifier(c), ObjectIdentifier(b), ObjectIdentifier(a) ].sorted()) } } Reflection.test("CustomMirrorIsInherited") { do { var output = "" dump(Irradiant(), to: &output) let expected = "▿ a.Brilliant #0\n" + " - first: 400\n" + " - second: \"\"\n" + " ▿ self: a.Brilliant #0\n" expectEqual(expected, output) } } protocol SomeNativeProto {} extension Int: SomeNativeProto {} Reflection.test("MetatypeMirror") { do { var output = "" let concreteMetatype = Int.self dump(concreteMetatype, to: &output) let expectedInt = "- Swift.Int #0\n" expectEqual(expectedInt, output) let anyMetatype: Any.Type = Int.self output = "" dump(anyMetatype, to: &output) expectEqual(expectedInt, output) let nativeProtocolMetatype: SomeNativeProto.Type = Int.self output = "" dump(nativeProtocolMetatype, to: &output) expectEqual(expectedInt, output) let concreteClassMetatype = SomeClass.self let expectedSomeClass = "- a.SomeClass #0\n" output = "" dump(concreteClassMetatype, to: &output) expectEqual(expectedSomeClass, output) let nativeProtocolConcreteMetatype = SomeNativeProto.self let expectedNativeProtocolConcrete = "- a.SomeNativeProto #0\n" output = "" dump(nativeProtocolConcreteMetatype, to: &output) expectEqual(expectedNativeProtocolConcrete, output) } } Reflection.test("TupleMirror") { do { var output = "" let tuple = (Brilliant(384, "seven six eight"), StructWithDefaultMirror("nine")) dump(tuple, to: &output) let expected = "▿ (2 elements)\n" + " ▿ .0: a.Brilliant #0\n" + " - first: 384\n" + " - second: \"seven six eight\"\n" + " ▿ self: a.Brilliant #0\n" + " ▿ .1: a.StructWithDefaultMirror\n" + " - s: \"nine\"\n" expectEqual(expected, output) expectEqual(.tuple, Mirror(reflecting: tuple).displayStyle) } do { // A tuple of stdlib types with mirrors. var output = "" let tuple = (1, 2.5, false, "three") dump(tuple, to: &output) let expected = "▿ (4 elements)\n" + " - .0: 1\n" + " - .1: 2.5\n" + " - .2: false\n" + " - .3: \"three\"\n" expectEqual(expected, output) } do { // A nested tuple. var output = "" let tuple = (1, ("Hello", "World")) dump(tuple, to: &output) let expected = "▿ (2 elements)\n" + " - .0: 1\n" + " ▿ .1: (2 elements)\n" + " - .0: \"Hello\"\n" + " - .1: \"World\"\n" expectEqual(expected, output) } } class DullClass {} Reflection.test("ClassReflection") { expectEqual(.`class`, Mirror(reflecting: DullClass()).displayStyle) } Reflection.test("String/Mirror") { do { var output = "" dump("", to: &output) let expected = "- \"\"\n" expectEqual(expected, output) } do { // U+0061 LATIN SMALL LETTER A // U+304B HIRAGANA LETTER KA // U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK // U+1F425 FRONT-FACING BABY CHICK var output = "" dump("\u{61}\u{304b}\u{3099}\u{1f425}", to: &output) let expected = "- \"\u{61}\u{304b}\u{3099}\u{1f425}\"\n" expectEqual(expected, output) } } Reflection.test("String.UTF8View/Mirror") { // U+0061 LATIN SMALL LETTER A // U+304B HIRAGANA LETTER KA // U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK var output = "" dump("\u{61}\u{304b}\u{3099}".utf8, to: &output) let expected = "▿ UTF8View(\"\u{61}\u{304b}\u{3099}\")\n" + " - 97\n" + " - 227\n" + " - 129\n" + " - 139\n" + " - 227\n" + " - 130\n" + " - 153\n" expectEqual(expected, output) } Reflection.test("String.UTF16View/Mirror") { // U+0061 LATIN SMALL LETTER A // U+304B HIRAGANA LETTER KA // U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK // U+1F425 FRONT-FACING BABY CHICK var output = "" dump("\u{61}\u{304b}\u{3099}\u{1f425}".utf16, to: &output) let expected = "▿ StringUTF16(\"\u{61}\u{304b}\u{3099}\u{1f425}\")\n" + " - 97\n" + " - 12363\n" + " - 12441\n" + " - 55357\n" + " - 56357\n" expectEqual(expected, output) } Reflection.test("String.UnicodeScalarView/Mirror") { // U+0061 LATIN SMALL LETTER A // U+304B HIRAGANA LETTER KA // U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK // U+1F425 FRONT-FACING BABY CHICK var output = "" dump("\u{61}\u{304b}\u{3099}\u{1f425}".unicodeScalars, to: &output) let expected = "▿ StringUnicodeScalarView(\"\u{61}\u{304b}\u{3099}\u{1f425}\")\n" + " - \"\u{61}\"\n" + " - \"\\u{304B}\"\n" + " - \"\\u{3099}\"\n" + " - \"\\u{0001F425}\"\n" expectEqual(expected, output) } Reflection.test("Character/Mirror") { do { // U+0061 LATIN SMALL LETTER A let input: Character = "\u{61}" var output = "" dump(input, to: &output) let expected = "- \"\u{61}\"\n" expectEqual(expected, output) } do { // U+304B HIRAGANA LETTER KA // U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK let input: Character = "\u{304b}\u{3099}" var output = "" dump(input, to: &output) let expected = "- \"\u{304b}\u{3099}\"\n" expectEqual(expected, output) } do { // U+1F425 FRONT-FACING BABY CHICK let input: Character = "\u{1f425}" var output = "" dump(input, to: &output) let expected = "- \"\u{1f425}\"\n" expectEqual(expected, output) } } Reflection.test("UnicodeScalar") { do { // U+0061 LATIN SMALL LETTER A let input: UnicodeScalar = "\u{61}" var output = "" dump(input, to: &output) let expected = "- \"\u{61}\"\n" expectEqual(expected, output) } do { // U+304B HIRAGANA LETTER KA let input: UnicodeScalar = "\u{304b}" var output = "" dump(input, to: &output) let expected = "- \"\\u{304B}\"\n" expectEqual(expected, output) } do { // U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK let input: UnicodeScalar = "\u{3099}" var output = "" dump(input, to: &output) let expected = "- \"\\u{3099}\"\n" expectEqual(expected, output) } do { // U+1F425 FRONT-FACING BABY CHICK let input: UnicodeScalar = "\u{1f425}" var output = "" dump(input, to: &output) let expected = "- \"\\u{0001F425}\"\n" expectEqual(expected, output) } } Reflection.test("Bool") { do { var output = "" dump(false, to: &output) let expected = "- false\n" expectEqual(expected, output) } do { var output = "" dump(true, to: &output) let expected = "- true\n" expectEqual(expected, output) } } // FIXME: these tests should cover Float80. // FIXME: these tests should be automatically generated from the list of // available floating point types. Reflection.test("Float") { do { var output = "" dump(Float.nan, to: &output) let expected = "- nan\n" expectEqual(expected, output) } do { var output = "" dump(Float.infinity, to: &output) let expected = "- inf\n" expectEqual(expected, output) } do { var input: Float = 42.125 var output = "" dump(input, to: &output) let expected = "- 42.125\n" expectEqual(expected, output) } } Reflection.test("Double") { do { var output = "" dump(Double.nan, to: &output) let expected = "- nan\n" expectEqual(expected, output) } do { var output = "" dump(Double.infinity, to: &output) let expected = "- inf\n" expectEqual(expected, output) } do { var input: Double = 42.125 var output = "" dump(input, to: &output) let expected = "- 42.125\n" expectEqual(expected, output) } } // A struct type and class type whose NominalTypeDescriptor.FieldNames // data is exactly eight bytes long. FieldNames data of exactly // 4 or 8 or 16 bytes was once miscompiled on arm64. struct EightByteFieldNamesStruct { let abcdef = 42 } class EightByteFieldNamesClass { let abcdef = 42 } Reflection.test("FieldNamesBug") { do { let expected = "▿ a.EightByteFieldNamesStruct\n" + " - abcdef: 42\n" var output = "" dump(EightByteFieldNamesStruct(), to: &output) expectEqual(expected, output) } do { let expected = "▿ a.EightByteFieldNamesClass #0\n" + " - abcdef: 42\n" var output = "" dump(EightByteFieldNamesClass(), to: &output) expectEqual(expected, output) } } Reflection.test("MirrorMirror") { var object = 1 var mirror = Mirror(reflecting: object) var mirrorMirror = Mirror(reflecting: mirror) expectEqual(0, mirrorMirror.children.count) } Reflection.test("OpaquePointer/null") { // Don't crash on null pointers. rdar://problem/19708338 let pointer: OpaquePointer? = nil let mirror = Mirror(reflecting: pointer) expectEqual(0, mirror.children.count) } Reflection.test("StaticString/Mirror") { do { var output = "" dump("" as StaticString, to: &output) let expected = "- \"\"\n" expectEqual(expected, output) } do { // U+0061 LATIN SMALL LETTER A // U+304B HIRAGANA LETTER KA // U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK // U+1F425 FRONT-FACING BABY CHICK var output = "" dump("\u{61}\u{304b}\u{3099}\u{1f425}" as StaticString, to: &output) let expected = "- \"\u{61}\u{304b}\u{3099}\u{1f425}\"\n" expectEqual(expected, output) } } Reflection.test("DictionaryIterator/Mirror") { let d: [MinimalHashableValue : OpaqueValue<Int>] = [ MinimalHashableValue(0) : OpaqueValue(0) ] var output = "" dump(d.makeIterator(), to: &output) let expected = "- Swift.DictionaryIterator<StdlibUnittest.MinimalHashableValue, StdlibUnittest.OpaqueValue<Swift.Int>>\n" expectEqual(expected, output) } Reflection.test("SetIterator/Mirror") { let s: Set<MinimalHashableValue> = [ MinimalHashableValue(0)] var output = "" dump(s.makeIterator(), to: &output) let expected = "- Swift.SetIterator<StdlibUnittest.MinimalHashableValue>\n" expectEqual(expected, output) } var BitTwiddlingTestSuite = TestSuite("BitTwiddling") func computeCountLeadingZeroes(_ x: Int64) -> Int64 { var x = x var r: Int64 = 64 while x != 0 { x >>= 1 r -= 1 } return r } BitTwiddlingTestSuite.test("_pointerSize") { #if arch(i386) || arch(arm) expectEqual(4, sizeof(Optional<AnyObject>.self)) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) expectEqual(8, sizeof(Optional<AnyObject>.self)) #else fatalError("implement") #endif } BitTwiddlingTestSuite.test("_countLeadingZeros") { for i in Int64(0)..<1000 { expectEqual(computeCountLeadingZeroes(i), _countLeadingZeros(i)) } expectEqual(0, _countLeadingZeros(Int64.min)) } BitTwiddlingTestSuite.test("_isPowerOf2/Int") { func asInt(_ a: Int) -> Int { return a } expectFalse(_isPowerOf2(asInt(-1025))) expectFalse(_isPowerOf2(asInt(-1024))) expectFalse(_isPowerOf2(asInt(-1023))) expectFalse(_isPowerOf2(asInt(-4))) expectFalse(_isPowerOf2(asInt(-3))) expectFalse(_isPowerOf2(asInt(-2))) expectFalse(_isPowerOf2(asInt(-1))) expectFalse(_isPowerOf2(asInt(0))) expectTrue(_isPowerOf2(asInt(1))) expectTrue(_isPowerOf2(asInt(2))) expectFalse(_isPowerOf2(asInt(3))) expectTrue(_isPowerOf2(asInt(1024))) #if arch(i386) || arch(arm) // Not applicable to 32-bit architectures. #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) expectTrue(_isPowerOf2(asInt(0x8000_0000))) #else fatalError("implement") #endif expectFalse(_isPowerOf2(Int.min)) expectFalse(_isPowerOf2(Int.max)) } BitTwiddlingTestSuite.test("_isPowerOf2/UInt") { func asUInt(_ a: UInt) -> UInt { return a } expectFalse(_isPowerOf2(asUInt(0))) expectTrue(_isPowerOf2(asUInt(1))) expectTrue(_isPowerOf2(asUInt(2))) expectFalse(_isPowerOf2(asUInt(3))) expectTrue(_isPowerOf2(asUInt(1024))) expectTrue(_isPowerOf2(asUInt(0x8000_0000))) expectFalse(_isPowerOf2(UInt.max)) } BitTwiddlingTestSuite.test("_floorLog2") { expectEqual(_floorLog2(1), 0) expectEqual(_floorLog2(8), 3) expectEqual(_floorLog2(15), 3) expectEqual(_floorLog2(Int64.max), 62) // 63 minus 1 for sign bit. } var AvailabilityVersionsTestSuite = TestSuite("AvailabilityVersions") AvailabilityVersionsTestSuite.test("lexicographic_compare") { func version( _ major: Int, _ minor: Int, _ patch: Int ) -> _SwiftNSOperatingSystemVersion { return _SwiftNSOperatingSystemVersion( majorVersion: major, minorVersion: minor, patchVersion: patch ) } checkComparable(.eq, version(0, 0, 0), version(0, 0, 0)) checkComparable(.lt, version(0, 0, 0), version(0, 0, 1)) checkComparable(.lt, version(0, 0, 0), version(0, 1, 0)) checkComparable(.lt, version(0, 0, 0), version(1, 0, 0)) checkComparable(.lt,version(10, 9, 0), version(10, 10, 0)) checkComparable(.lt,version(10, 9, 11), version(10, 10, 0)) checkComparable(.lt,version(10, 10, 3), version(10, 11, 0)) checkComparable(.lt, version(8, 3, 0), version(9, 0, 0)) checkComparable(.lt, version(0, 11, 0), version(10, 10, 4)) checkComparable(.lt, version(0, 10, 0), version(10, 10, 4)) checkComparable(.lt, version(3, 2, 1), version(4, 3, 2)) checkComparable(.lt, version(1, 2, 3), version(2, 3, 1)) checkComparable(.eq, version(10, 11, 12), version(10, 11, 12)) checkEquatable(true, version(1, 2, 3), version(1, 2, 3)) checkEquatable(false, version(1, 2, 3), version(1, 2, 42)) checkEquatable(false, version(1, 2, 3), version(1, 42, 3)) checkEquatable(false, version(1, 2, 3), version(42, 2, 3)) } AvailabilityVersionsTestSuite.test("_stdlib_isOSVersionAtLeast") { func isAtLeastOS(_ major: Int, _ minor: Int, _ patch: Int) -> Bool { return _getBool(_stdlib_isOSVersionAtLeast(major._builtinWordValue, minor._builtinWordValue, patch._builtinWordValue)) } // _stdlib_isOSVersionAtLeast is broken for // watchOS. rdar://problem/20234735 #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) // This test assumes that no version component on an OS we test upon // will ever be greater than 1066 and that every major version will always // be greater than 1. expectFalse(isAtLeastOS(1066, 0, 0)) expectTrue(isAtLeastOS(0, 1066, 0)) expectTrue(isAtLeastOS(0, 0, 1066)) #endif } runAllTests()
apache-2.0
702516af2522fe11188bdf711431abe3
26.554924
158
0.655051
3.744595
false
false
false
false
jawwad/swift-algorithm-club
Segment Tree/LazyPropagation/LazyPropagation.playground/Contents.swift
3
5062
public class LazySegmentTree { private var value: Int private var leftBound: Int private var rightBound: Int private var leftChild: LazySegmentTree? private var rightChild: LazySegmentTree? // Interval Update Lazy Element private var lazyValue: Int // MARK: - Push Up Operation // Description: pushUp() - update items to the top private func pushUp(lson: LazySegmentTree, rson: LazySegmentTree) { self.value = lson.value + rson.value } // MARK: - Push Down Operation // Description: pushDown() - update items to the bottom private func pushDown(round: Int, lson: LazySegmentTree, rson: LazySegmentTree) { guard lazyValue != 0 else { return } lson.lazyValue += lazyValue rson.lazyValue += lazyValue lson.value += lazyValue * (round - (round >> 1)) rson.value += lazyValue * (round >> 1) lazyValue = 0 } public init(array: [Int], leftBound: Int, rightBound: Int) { self.leftBound = leftBound self.rightBound = rightBound self.value = 0 self.lazyValue = 0 guard leftBound != rightBound else { value = array[leftBound] return } let middle = leftBound + (rightBound - leftBound) / 2 leftChild = LazySegmentTree(array: array, leftBound: leftBound, rightBound: middle) rightChild = LazySegmentTree(array: array, leftBound: middle + 1, rightBound: rightBound) if let leftChild = leftChild, let rightChild = rightChild { pushUp(lson: leftChild, rson: rightChild) } } public convenience init(array: [Int]) { self.init(array: array, leftBound: 0, rightBound: array.count - 1) } public func query(leftBound: Int, rightBound: Int) -> Int { if leftBound <= self.leftBound && self.rightBound <= rightBound { return value } guard let leftChild = leftChild else { fatalError("leftChild should not be nil") } guard let rightChild = rightChild else { fatalError("rightChild should not be nil") } pushDown(round: self.rightBound - self.leftBound + 1, lson: leftChild, rson: rightChild) let middle = self.leftBound + (self.rightBound - self.leftBound) / 2 var result = 0 if leftBound <= middle { result += leftChild.query(leftBound: leftBound, rightBound: rightBound) } if rightBound > middle { result += rightChild.query(leftBound: leftBound, rightBound: rightBound) } return result } // MARK: - One Item Update public func update(index: Int, incremental: Int) { guard self.leftBound != self.rightBound else { self.value += incremental return } guard let leftChild = leftChild else { fatalError("leftChild should not be nil") } guard let rightChild = rightChild else { fatalError("rightChild should not be nil") } let middle = self.leftBound + (self.rightBound - self.leftBound) / 2 if index <= middle { leftChild.update(index: index, incremental: incremental) } else { rightChild.update(index: index, incremental: incremental) } pushUp(lson: leftChild, rson: rightChild) } // MARK: - Interval Item Update public func update(leftBound: Int, rightBound: Int, incremental: Int) { if leftBound <= self.leftBound && self.rightBound <= rightBound { self.lazyValue += incremental self.value += incremental * (self.rightBound - self.leftBound + 1) return } guard let leftChild = leftChild else { fatalError("leftChild should not be nil") } guard let rightChild = rightChild else { fatalError("rightChild should not be nil") } pushDown(round: self.rightBound - self.leftBound + 1, lson: leftChild, rson: rightChild) let middle = self.leftBound + (self.rightBound - self.leftBound) / 2 if leftBound <= middle { leftChild.update(leftBound: leftBound, rightBound: rightBound, incremental: incremental) } if middle < rightBound { rightChild.update(leftBound: leftBound, rightBound: rightBound, incremental: incremental) } pushUp(lson: leftChild, rson: rightChild) } } let array = [1, 2, 3, 4, 1, 3, 2] let sumSegmentTree = LazySegmentTree(array: array) print(sumSegmentTree.query(leftBound: 0, rightBound: 3)) // 10 = 1 + 2 + 3 + 4 sumSegmentTree.update(index: 1, incremental: 2) print(sumSegmentTree.query(leftBound: 0, rightBound: 3)) // 12 = 1 + 4 + 3 + 4 sumSegmentTree.update(leftBound: 0, rightBound: 2, incremental: 2) print(sumSegmentTree.query(leftBound: 0, rightBound: 3)) // 18 = 3 + 6 + 5 + 4 for index in 2 ... 5 { sumSegmentTree.update(index: index, incremental: 3) } sumSegmentTree.update(leftBound: 0, rightBound: 5, incremental: 2) print(sumSegmentTree.query(leftBound: 0, rightBound: 2))
mit
78f5d6f58dbee2c2a7f62b69ffcb61b1
38.248062
124
0.629593
4.503559
false
false
false
false
dst-hackathon/socialradar-ios
SocialRadar/SocialRadar/SignupViewController.swift
1
6956
// // SignupViewController.swift // SocialRadar // // Created by Sasitorn Aramcharoenrat on 10/31/2557 BE. // Copyright (c) 2557 dsthackathon. All rights reserved. // import UIKit class SignupViewController: UIViewController { @IBOutlet weak var txtUsername: UITextField! @IBOutlet weak var txtPassword: UITextField! @IBOutlet weak var txtConfirmPassword: UITextField! let signUpUrl: String = "http://api.radar.codedeck.com/signup" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func performSignup(sender: UIButton) { var username:String = txtUsername.text var password:String = txtPassword.text var confirm_password:String = txtConfirmPassword.text if ( username == ("") || password == ("") ) { var alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = "Please enter Username and Password" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } else if ( password != confirm_password ) { var alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = "Passwords don't Match" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } else { let params: [String: String] = ["email": username, "password": password] //var image:UIImage = UIImage(named: "apple.jpeg")! println("email: \(username) password: \(password)") /*let imageData:NSData = NSData.dataWithData(UIImageJPEGRepresentation(image, 1.0)) as NSData SRWebClient.POST(signUpUrl) .data(imageData, fieldName: "file", data: params) .send({(response:AnyObject!, status:Int) -> Void in //process success response println("signup success") self.dismissViewControllerAnimated(true, completion: nil) },failure:{(error:NSError!) -> Void in //process failure response var alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = "error" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() })*/ } } @IBAction func gotoLoginPage(sender: UIButton) { } /*func old(){ var post:NSString = "username=\(username)&password=\(password)&c_password=\(confirm_password)" NSLog("PostData: %@",post); var url:NSURL = NSURL(string: "http://test.com/jsonsignup.php")! var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! var postLength:NSString = String( postData.length ) var request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.HTTPBody = postData request.setValue(postLength, forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") var reponseError: NSError? var response: NSURLResponse? var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError) if ( urlData != nil ) { let res = response as NSHTTPURLResponse!; NSLog("Response code: %ld", res.statusCode); if (res.statusCode >= 200 && res.statusCode < 300) { var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)! NSLog("Response ==> %@", responseData); var error: NSError? let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary let success:NSInteger = jsonData.valueForKey("success") as NSInteger //[jsonData[@"success"] integerValue]; NSLog("Success: %ld", success); if(success == 1) { NSLog("Sign Up SUCCESS"); self.dismissViewControllerAnimated(true, completion: nil) } else { var error_msg:NSString if jsonData["error_message"] as? NSString != nil { error_msg = jsonData["error_message"] as NSString } else { error_msg = "Unknown Error" } var alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = error_msg alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } else { var alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = "Connection Failed" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } else { var alertView:UIAlertView = UIAlertView() alertView.title = "Sign in Failed!" alertView.message = "Connection Failure" if let error = reponseError { alertView.message = (error.localizedDescription) } alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } }*/ /* // 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
6c0b18437e49ae4c8a4a1947b82f37ce
36.397849
172
0.543416
5.753515
false
false
false
false
VKoskiv/NoMansCanvas
Sources/App/Models/Canvas.swift
1
3978
// // Canvas.swift // place // // Created by Valtteri Koskivuori on 18/06/2017. // // import Vapor import MySQLProvider class Canvas { //Connection is a key-val pair; User:WebSocket var connections: [User: WebSocket] var tiles: [Tile] = [] var width: Int = 250 var height: Int = 250 //Colors, people may add additional ones var colors: [TileColor] func updateTileToClients(tile: Tile) { //We've received a tile change, it's been approved, send that update to ALL connected clients var structure = [[String: NodeRepresentable]]() structure.append(["responseType": "tileUpdate", "X": tile.pos.x, "Y": tile.pos.y, "colorID": tile.color]) //Create json guard let json = try? JSON(node: structure) else { print("Failed to create JSON in updateTileToClients()") return } //Send to all connected users sendJSON(json: json) } func sendAnnouncement(msg: String) { var structure = [[String: NodeRepresentable]]() structure.append(["responseType": "announcement", "message": msg]) guard let json = try? JSON(node: structure) else { print("Failed to create JSON in sendAnnouncement()") return } sendJSON(json: json) } func shutdown() { var structure = [[String: NodeRepresentable]]() structure.append(["responseType": "disconnecting"]) guard let json = try? JSON(node: structure) else { print("Failed to create JSON in shutdown()") return } for (user, socket) in connections { do { try socket.send(json.serialize().makeString()) try socket.close() canvas.connections.removeValue(forKey: user) } catch { print("oops?") } } print("Closed all connections.") } //Send to all users func sendJSON(json: JSON) { for (user, socket) in connections { do { try socket.send(json.serialize().makeString()) } catch { try? socket.close() canvas.connections.removeValue(forKey: user) } } } //Init canvas, load it from the DB here init() { connections = [:] //Add some default colors. Remember to preserve IDs, as existing drawings use em for now colors = [ TileColor(color: Color(with: 255, green: 255, blue: 255), id: 3),//White TileColor(color: Color(with: 221, green: 221, blue: 221), id: 10),//Dark white TileColor(color: Color(with: 117, green: 117, blue: 117), id: 11),//Grey TileColor(color: Color(with: 0, green: 0, blue: 0), id: 4),//Black TileColor(color: Color(with: 219, green: 0, blue: 5 ), id: 0),//Red TileColor(color: Color(with: 252, green: 145, blue: 199), id: 8),//Pink TileColor(color: Color(with: 142, green: 87, blue: 51), id: 12),//Brown TileColor(color: Color(with: 255, green: 153, blue: 51), id: 7),//Orange TileColor(color: Color(with: 255, green: 255, blue: 0), id: 9),//Yellow TileColor(color: Color(with: 133, green: 222, blue: 53), id: 1),//Green TileColor(color: Color(with: 24, green: 181, blue: 4), id: 6),//Dark green TileColor(color: Color(with: 0, green: 0, blue: 255), id: 2),//Blue TileColor(color: Color(with: 13, green: 109, blue: 187), id: 13),//almostLight blue TileColor(color: Color(with: 26, green: 203, blue: 213), id: 5),//Light blue TileColor(color: Color(with: 195, green: 80, blue: 222), id: 14),//light purple TileColor(color: Color(with: 110, green: 0, blue: 108), id: 15)//purple ] //init the tiles var initTileDB: Bool = false let dbTiles = try? Tile.makeQuery().all() if dbTiles?.count == 0 { initTileDB = true } if initTileDB { print("Running first tile db init!") for y in 0..<height { for x in 0..<width { let tile = Tile() tile.pos = Coord(x: x, y: y) tile.color = 3 //Only run once, check the row count try? tile.save() self.tiles.append(tile) } } } else { print("Loading canvas from DB...") dbTiles?.forEach { dbTile in self.tiles.append(dbTile) } } } }
mit
1c0eaa7c7c2bacae01565709563d06c7
28.466667
95
0.629965
3.0553
false
false
false
false
lioonline/Swift
SpriteKit/SpriteKit/GameViewController.swift
1
2021
// // GameViewController.swift // SpriteKit // // Created by Carlos Butron on 07/12/14. // Copyright (c) 2014 Carlos Butron. // // This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License along with this program. If not, see // http:/www.gnu.org/licenses/. // import UIKit import QuartzCore import SceneKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Configurar la vista let skView = self.view as SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit optimiza el Renderizado */ skView.ignoresSiblingOrder = true /* Ajustar la escena GameScene al dispositivo */ let scene = GameScene(size: skView.bounds.size) scene.scaleMode = .AspectFill skView.presentScene(scene) } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
gpl-3.0
65bc55bed52c85175018ebec1c3d94e5
32.7
121
0.676398
4.929268
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.ChatTests/Controllers/MessagesSizingViewModelSpec.swift
1
1736
// // MessagesSizingViewModelSpec.swift // Rocket.ChatTests // // Created by Rafael Streit on 25/09/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation import XCTest @testable import Rocket_Chat final class MessagesSizingViewModelSpec: XCTestCase { func testInitialState() { let model = MessagesSizingManager() XCTAssertEqual(model.cache.count, 0) } func testCacheHeightValue() { let model = MessagesSizingManager() let identifier = "identifier" model.set(size: CGSize(width: 0, height: 150), for: identifier) XCTAssertEqual(model.size(for: identifier)?.height, 150) XCTAssertEqual(model.cache.count, 1) } func testCacheNegativeValues() { let model = MessagesSizingManager() let identifier = "identifier" model.set(size: CGSize(width: 0, height: -1), for: identifier) XCTAssertNil(model.size(for: identifier)) XCTAssertEqual(model.cache.count, 1) } func testCacheNotValidValues() { let model = MessagesSizingManager() let identifier = "identifier" model.set(size: CGSize(width: 0.0, height: Double.nan), for: identifier) XCTAssertNil(model.size(for: identifier)) XCTAssertEqual(model.cache.count, 1) } func testClearCache() { let model = MessagesSizingManager() model.set(size: CGSize(width: 0, height: 150), for: "identifier.1") model.set(size: CGSize(width: 0, height: 175), for: "identifier.2") model.set(size: CGSize(width: 0, height: 200), for: "identifier.3") XCTAssertEqual(model.cache.count, 3) model.clearCache() XCTAssertEqual(model.cache.count, 0) } }
mit
022a7ece5553e52b5e7a68c2fda9a56a
30.545455
80
0.655331
3.979358
false
true
false
false
frootloops/swift
test/DebugInfo/thunks.swift
1
876
// RUN: %target-swift-frontend -emit-ir -g %s -o - | %FileCheck %s // RUN: %target-swift-frontend -emit-sil -emit-verbose-sil -g %s -o - | %FileCheck %s --check-prefix=SIL-CHECK // REQUIRES: objc_interop import Foundation class Foo : NSObject { dynamic func foo(_ f: (Int64) -> Int64, x: Int64) -> Int64 { return f(x) } } let foo = Foo() let y = 3 as Int64 let i = foo.foo(-, x: y) // CHECK: define {{.*}}@_T0s5Int64VABIyByd_A2BIgyd_TR // CHECK-NOT: ret // CHECK: call {{.*}}, !dbg ![[LOC:.*]] // CHECK: ![[THUNK:.*]] = distinct !DISubprogram(linkageName: "_T0s5Int64VABIyByd_A2BIgyd_TR" // CHECK-NOT: line: // CHECK-SAME: ){{$}} // CHECK: ![[LOC]] = !DILocation(line: 0, scope: ![[THUNK]]) // SIL-CHECK: sil shared {{.*}}@_T0s5Int64VABIyByd_A2BIgyd_TR // SIL-CHECK-NOT: return // SIL-CHECK: apply {{.*}}auto_gen
apache-2.0
1ea392cf33c8cfe665e36f61d163899e
32.692308
110
0.579909
2.825806
false
false
false
false
NathanE73/Blackboard
Sources/BlackboardFramework/Storyboards/StoryboardSegue.swift
1
2697
// // Copyright (c) 2022 Nathan E. Walczak // // MIT License // // 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 extension StoryboardSegue { enum Kind: String { case embed case popoverPresentation case presentation case relationship case show case unwind } } struct StoryboardSegue { var id: String var kind: Kind var identifier: String? var destination: String var isAutomatic: Bool } extension StoryboardSegue: CustomStringConvertible { var description: String { "id: \(id), kind: \(kind), identifier: \(identifier ?? "nil"), destination: \(destination)" } } extension StoryboardSegue { init?(node: XMLNode?) { guard let element = node as? XMLElement, element.name == "segue" else { return nil } guard let id = element.attribute(forName: "id")?.stringValue else { return nil } self.id = id guard let kindAttribute = element.attribute(forName: "kind")?.stringValue, let kind = Kind(rawValue: kindAttribute) else { return nil } self.kind = kind identifier = element.attribute(forName: "identifier")?.stringValue guard let destination = element.attribute(forName: "destination")?.stringValue else { return nil } self.destination = destination // scene.objects.viewController.connections.segue isAutomatic = element.parent?.parent?.parent?.parent?.name != "scene" } }
mit
62bac1529b57f1b63728329b10386021
29.303371
99
0.651094
4.903636
false
false
false
false
itsjingun/govhacknz_mates
Mates/Data/Models/MTSParseGroup.swift
1
980
// // MTSParseGroup.swift // Mates // // Created by Jingun Lee on 4/07/15. // Copyright (c) 2015 Governmen. All rights reserved. // import UIKit class MTSParseGroup: PFObject, PFSubclassing { static let kKeyOwner = "owner" static let kKeyUsers = "users" static let kKeyLocation = "location" static let kKeyUserUsernames = "userUsernames" @NSManaged var owner: MTSParseUser @NSManaged var users: PFRelation @NSManaged var location: String @NSManaged var userUsernames: Array<String> /** Initializes and registers this class as a Parse subclass. */ override class func initialize() { struct Static { static var onceToken : dispatch_once_t = 0; } dispatch_once(&Static.onceToken) { self.registerSubclass() } } /** Returns the corresponding Parse class name. */ static func parseClassName() -> String { return "Group" } }
gpl-2.0
7d9f6e9e2d810fc26f673a3a9dea7f28
22.902439
61
0.626531
4.298246
false
false
false
false
klesh/cnodejs-swift
CNode/Options/UserViewController.swift
1
2644
// // UserViewController.swift // CNode // // Created by Klesh Wong on 1/11/16. // Copyright © 2016 Klesh Wong. All rights reserved. // import UIKit import SwiftyJSON class UserViewController : UITableViewController { var header: UserHeaderView! var loginname: String! var user: JSON! let menuItems = [ (code: "recent_replies", text: "最近回复"), (code: "recent_topics", text: "最近发表") ] override func viewDidLoad() { header = tableView.dequeueReusableCellWithIdentifier("userHeader") as! UserHeaderView tableView.tableHeaderView = header // bind ApiClient(self).getUser(loginname) { response in self.user = response["data"] self.header.bind(self.user) } // 添加关闭按钮 navigationItem.leftBarButtonItem = Utils.navButton(0xf00d, target: self, action: "close") // 设定标题 navigationItem.title = loginname // 去掉尾部线条 tableView.tableFooterView = UIView() } func close() { dismissViewControllerAnimated(true, completion: nil) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("userMenuItem", forIndexPath: indexPath) cell.textLabel?.text = menuItems[indexPath.row].text return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //performSegueWithIdentifier("recentActivities", sender: self) } class func create(loginname: String) -> UIViewController { let sb = UIStoryboard(name: "Options", bundle: nil) let navCtrl = sb.instantiateViewControllerWithIdentifier("userScene") as! UINavigationController let userCtrl = navCtrl.viewControllers[0] as! UserViewController userCtrl.loginname = loginname return navCtrl } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let dest = segue.destinationViewController as! UserActivitiesController let code = menuItems[tableView.indexPathForSelectedRow!.row].code dest.navigationItem.title = loginname dest.activities = user[code].arrayValue } }
apache-2.0
9173fc1ac6a22df38e759e9b65f8bf6e
32.714286
118
0.665125
5.128458
false
false
false
false
mownier/Umalahokan
Umalahokan/Source/UI/Chat/ChatDisplayData.swift
1
1466
// // ChatData.swift // Umalahokan // // Created by Mounir Ybanez on 17/03/2017. // Copyright © 2017 Ner. All rights reserved. // import UIKit protocol ChatDisplayData { var message: String { set get } var isMe: Bool { set get } var isAnimatable: Bool { set get } } struct ChatDisplayDataItem: ChatDisplayData { var message: String = "" var isMe: Bool = false var isAnimatable: Bool = true } func generateRandomChatDisplayItems() -> [ChatDisplayData] { var items = [ChatDisplayData]() for _ in 0..<(arc4random() % 20 + 20) { var item = ChatDisplayDataItem() item.isMe = arc4random() % 2 == 0 ? true : false switch arc4random() % 5 + 1 { case 1: item.message = "Hello! Are you free tonight?" case 2: item.message = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book." case 3: item.message = "No, I have an appointment with my boss." case 4: item.message = "Ok, how about tomorrow night?" default: item.message = "The quick brown fox jumps over the lazy dog." } items.append(item) } return items }
mit
a82896ff761622fc968fd0f44bf50da2
26.641509
274
0.588396
4.185714
false
false
false
false
qingpengchen2011/Cosmos
Cosmos/CosmosAccessibility.swift
1
2788
/** Functions for making cosmos view accessible. */ struct CosmosAccessibility { /** Makes the view accesible by settings its label and using rating as value. */ static func update(view: UIView, rating: Double, text: String?, settings: CosmosSettings) { view.isAccessibilityElement = true view.accessibilityTraits = settings.updateOnTouch ? UIAccessibilityTraitAdjustable :UIAccessibilityTraitNone var accessibilityLabel = CosmosLocalizedRating.ratingTranslation if let text = text where text != "" { accessibilityLabel += " \(text)" } view.accessibilityLabel = accessibilityLabel view.accessibilityValue = accessibilityValue(view, rating: rating, settings: settings) } /** Returns the rating that is used as accessibility value. The accessibility value depends on the star fill mode. For example, if rating is 4.6 and fill mode is .Half the value will be 4.5. And if the fill mode if .Full the value will be 5. */ static func accessibilityValue(view: UIView, rating: Double, settings: CosmosSettings) -> String { let accessibilityRating = CosmosRating.displayedRatingFromPreciseRating(rating, fillMode: settings.fillMode, totalStars: settings.totalStars) // Omit decimals if the value is an integer let isInteger = (accessibilityRating * 10) % 10 == 0 if isInteger { return "\(Int(accessibilityRating))" } else { // Only show a single decimal place let roundedToFirstDecimalPlace = Double( round(10 * accessibilityRating) / 10 ) return "\(roundedToFirstDecimalPlace)" } } /** Returns the amount of increment for the rating. When .Half and .Precise fill modes are used the rating is incremented by 0.5. */ static func accessibilityIncrement(rating: Double, settings: CosmosSettings) -> Double { var increment: Double = 0 switch settings.fillMode { case .Full: increment = ceil(rating) - rating if increment == 0 { increment = 1 } case .Half, .Precise: increment = (ceil(rating * 2) - rating * 2) / 2 if increment == 0 { increment = 0.5 } } if rating >= Double(settings.totalStars) { increment = 0 } return increment } static func accessibilityDecrement(rating: Double, settings: CosmosSettings) -> Double { var increment: Double = 0 switch settings.fillMode { case .Full: increment = rating - floor(rating) if increment == 0 { increment = 1 } case .Half, .Precise: increment = (rating * 2 - floor(rating * 2)) / 2 if increment == 0 { increment = 0.5 } } if rating <= settings.minTouchRating { increment = 0 } return increment } }
mit
4ae78634d0ff4d6cde387a5652fb287c
28.041667
100
0.658537
4.701518
false
false
false
false
watr/SwiftString-VersionNumberComparison
String+VersionNumber.swift
1
1025
// // String+VersionNumber.swift // // Created by hashimoto wataru on 2017/02/28. // Copyright © 2017年 wataruhash.info. All rights reserved. // import Foundation extension String { func compareVersion(with anotherVersionString: String) -> ComparisonResult { let string1 = self let string2 = anotherVersionString let separator: String = "." let components1 = string1.components(separatedBy: separator) let components2 = string2.components(separatedBy: separator) let maxCount = max(components1.count, components2.count) for i in 0..<maxCount { let zero: String = "0" let a: String = (i < components1.count) ? components1[i] : zero let b: String = (i < components2.count) ? components2[i] : zero let result = a.compare(b, options: .numeric) if result != .orderedSame { return result } } return .orderedSame } }
unlicense
695c1c41fd2722fc898addd9ec231596
29.969697
80
0.59002
4.367521
false
false
false
false
bm842/Brokers
Sources/OandaRestV1Trade.swift
2
3241
/* The MIT License (MIT) Copyright (c) 2016 Bertrand Marlier 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 class OandaTrade: GenericTrade, Trade { weak var account: OandaRestAccount! weak var oanda: OandaRestBroker! override init(instrument: Instrument, info: TradeInfo) { account = instrument.account as? OandaRestAccount oanda = account.oanda super.init(instrument: instrument, info: info) } func modify(change parameters: [TradeParameter], completion: @escaping (RequestStatus) -> ()) { var paramString: String = "" for param in parameters { switch param { case .stopLoss(let price): paramString += "&stopLoss=\(price ?? 0)" case .takeProfit(let price): paramString += "&takeProfit=\(price ?? 0)" } } paramString.remove(at: paramString.startIndex) oanda.restConnection.fetchJson("accounts/\(account.id)/trades/\(id)", method: "PATCH", data: paramString) { (status, json) in guard json != nil else { log.error("no json, status = \(status)") completion(status) return } completion(status) } } public func close(completion: @escaping (RequestStatus) -> ()) { oanda.restConnection.fetchJson("accounts/\(account.id)/trades/\(id)", method: "DELETE") { (status, json) in guard let json = json else { log.error("no json, status = \(status)") completion(status) return } do { let response = try OandaRestV1CloseTradeResponse(object: json) self.close(atTime: Timestamp(fromOanda: response.time), atPrice: response.price, reason: .closed) completion(status) } catch { completion(OandaStatus.jsonParsingError(error)) } } } }
mit
a370e1031ba345dbc1eae2611218afc6
32.071429
113
0.595495
5.079937
false
false
false
false
yasuoza/graphPON
GraphPonDataKit/Models/GPUserDefaults.swift
1
1215
import Foundation public class GPUserDefaults: NSObject { static let suiteName = NSBundle(forClass: GPUserDefaults.self).objectForInfoDictionaryKey("GraphPonAppGroupID") as! String private static let defaults = NSUserDefaults(suiteName: suiteName)! public class func sharedDefaults() -> NSUserDefaults { return defaults } public class func migrateFromOldDefaultsIfNeeded() { let userDefaultsAlreadyMigrated = "GPUserDefaultsAlreadyMigrated" if sharedDefaults().boolForKey(userDefaultsAlreadyMigrated) { return } let domain = NSBundle.mainBundle().bundleIdentifier! let systemDefaults = NSUserDefaults.standardUserDefaults() let dict = systemDefaults.persistentDomainForName(domain) if let dict = dict { for origKey in dict.keys { let key = String(_cocoaString: origKey) sharedDefaults().setObject(dict[origKey], forKey: key) systemDefaults.removeObjectForKey(key) } sharedDefaults().setBool(true, forKey: userDefaultsAlreadyMigrated) defaults.synchronize() systemDefaults.synchronize() } } }
mit
0252be6144df09adbd1e02050c53d22f
34.735294
126
0.671605
5.67757
false
false
false
false
tkremenek/swift
test/SILGen/objc_bridging_peephole.swift
13
30307
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -module-name objc_bridging_peephole %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import OtherSubscripts import objc_generics func useNS(_ : NSString) {} func useOptNS(_ : NSString?) {} func makeNS() -> NSString { return "help" as NSString } func makeOptNS() -> NSString? { return nil } func useAnyObject(_: AnyObject) {} func useOptAnyObject(_: AnyObject?) {} /*** Return values ***********************************************************/ // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole16testMethodResult5dummyySo10DummyClassC_tF func testMethodResult(dummy: DummyClass) { // CHECK: bb0([[SELF:%.*]] : @guaranteed $DummyClass): // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $DummyClass, #DummyClass.fetchNullableString!foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole8useOptNSyySo8NSStringCSgF // CHECK-NEXT: apply [[USE]]([[RESULT]]) useOptNS(dummy.fetchNullableString() as NSString?) // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $DummyClass, #DummyClass.fetchNullproneString!foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole8useOptNSyySo8NSStringCSgF // CHECK-NEXT: apply [[USE]]([[RESULT]]) useOptNS(dummy.fetchNullproneString() as NSString?) // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $DummyClass, #DummyClass.fetchNonnullString!foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole8useOptNSyySo8NSStringCSgF // CHECK-NEXT: apply [[USE]]([[RESULT]]) useOptNS(dummy.fetchNonnullString() as NSString?) // CHECK: [[METHOD:%.*]] = objc_method // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK-NEXT: [[ANYOBJECT:%.*]] = unchecked_ref_cast [[RESULT]] : $Optional<NSString> to $Optional<AnyObject> // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole15useOptAnyObjectyyyXlSgF // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]]) useOptAnyObject(dummy.fetchNullableString() as AnyObject?) // CHECK: [[METHOD:%.*]] = objc_method // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK-NEXT: [[ANYOBJECT:%.*]] = unchecked_ref_cast [[RESULT]] : $Optional<NSString> to $Optional<AnyObject> // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole15useOptAnyObjectyyyXlSgF // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]]) useOptAnyObject(dummy.fetchNullproneString() as AnyObject?) // CHECK: [[METHOD:%.*]] = objc_method // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK-NEXT: [[ANYOBJECT:%.*]] = unchecked_ref_cast [[RESULT]] : $Optional<NSString> to $Optional<AnyObject> // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole15useOptAnyObjectyyyXlSgF // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]]) useOptAnyObject(dummy.fetchNonnullString() as AnyObject?) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole23testNonNullMethodResult5dummyySo10DummyClassC_tF func testNonNullMethodResult(dummy: DummyClass) { // CHECK: bb0([[ARG:%.*]] @guaranteed $DummyClass): // CHECK: [[METHOD:%.*]] = objc_method // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK-NEXT: switch_enum [[RESULT]] // // CHECK: bb1: // CHECK: function_ref @$ss30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_line17_isImplicitUnwrapyBp_BwBi1_BwBi1_tF // CHECK: bb2([[RESULT:%.*]] : @owned $NSString): // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole5useNSyySo8NSStringCF // CHECK-NEXT: apply [[USE]]([[RESULT]]) useNS(dummy.fetchNonnullString() as NSString) // CHECK: [[METHOD:%.*]] = objc_method // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK-NEXT: switch_enum [[RESULT]] // CHECK: bb3: // CHECK: function_ref @$ss30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_line17_isImplicitUnwrapyBp_BwBi1_BwBi1_tF // CHECK: bb4([[RESULT:%.*]] : @owned $NSString): // CHECK-NEXT: [[ANYOBJECT:%.*]] = init_existential_ref [[RESULT]] : $NSString : $NSString, $AnyObject // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole12useAnyObjectyyyXlF // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]]) useAnyObject(dummy.fetchNonnullString() as AnyObject) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole22testForcedMethodResult5dummyySo10DummyClassC_tF // CHECK: bb0([[SELF:%.*]] : @guaranteed $DummyClass): func testForcedMethodResult(dummy: DummyClass) { // CHECK: [[METHOD:%.*]] = objc_method // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK-NEXT: switch_enum [[RESULT]] // CHECK: bb1: // CHECK: function_ref @$ss30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_line17_isImplicitUnwrapyBp_BwBi1_BwBi1_tF // CHECK: bb2([[RESULT:%.*]] : @owned $NSString): // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole5useNSyySo8NSStringCF // CHECK-NEXT: apply [[USE]]([[RESULT]]) useNS(dummy.fetchNullproneString() as NSString) // This is not a force. // TODO: we could do it more efficiently than this, though // CHECK: [[METHOD:%.*]] = objc_method // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK-NEXT: switch_enum [[RESULT]] // // CHECK: bb3([[RESULT:%.*]] : @owned $NSString): // CHECK: function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ // // CHECK: bb4: // CHECK: enum $Optional<String>, #Optional.none // // CHECK: bb5([[OPTSTRING:%.*]] : @owned $Optional<String>): // CHECK: [[BRIDGE:%.*]] = function_ref @$sSq19_bridgeToObjectiveCyXlyF // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Optional<String> // CHECK-NEXT: [[BORROW:%.*]] = begin_borrow [[OPTSTRING]] // CHECK-NEXT: store_borrow [[BORROW]] to [[TEMP]] : $*Optional<String> // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE]]<String>([[TEMP]]) // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole12useAnyObjectyyyXlF // CHECK: apply [[USE]]([[ANYOBJECT]]) useAnyObject(dummy.fetchNullproneString() as AnyObject) // CHECK: return } /*** Property loads **********************************************************/ // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole17testPropertyValue5dummyySo10DummyClassC_tF // CHECK: bb0([[SELF:%.*]] : @guaranteed $DummyClass): func testPropertyValue(dummy: DummyClass) { // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole8useOptNSyySo8NSStringCSgF // CHECK: apply [[USE]]([[RESULT]]) useOptNS(dummy.nullableStringProperty as NSString?) // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole8useOptNSyySo8NSStringCSgF // CHECK: apply [[USE]]([[RESULT]]) useOptNS(dummy.nullproneStringProperty as NSString?) // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole8useOptNSyySo8NSStringCSgF // CHECK: apply [[USE]]([[RESULT]]) useOptNS(dummy.nonnullStringProperty as NSString?) // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: [[ANYOBJECT:%.*]] = unchecked_ref_cast [[RESULT]] : $Optional<NSString> to $Optional<AnyObject> // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole15useOptAnyObjectyyyXlSgF // CHECK: apply [[USE]]([[ANYOBJECT]]) useOptAnyObject(dummy.nullableStringProperty as AnyObject?) // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: [[ANYOBJECT:%.*]] = unchecked_ref_cast [[RESULT]] : $Optional<NSString> to $Optional<AnyObject> // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole15useOptAnyObjectyyyXlSgF // CHECK: apply [[USE]]([[ANYOBJECT]]) useOptAnyObject(dummy.nullproneStringProperty as AnyObject?) // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: [[ANYOBJECT:%.*]] = unchecked_ref_cast [[RESULT]] : $Optional<NSString> to $Optional<AnyObject> // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole15useOptAnyObjectyyyXlSgF // CHECK: apply [[USE]]([[ANYOBJECT]]) useOptAnyObject(dummy.nonnullStringProperty as AnyObject?) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole24testNonNullPropertyValue5dummyySo10DummyClassC_tF func testNonNullPropertyValue(dummy: DummyClass) { // CHECK: bb0([[SELF:%.*]] : @guaranteed $DummyClass): // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: switch_enum [[RESULT]] // CHECK: bb1: // CHECK: function_ref @$ss30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_line17_isImplicitUnwrapyBp_BwBi1_BwBi1_tF // CHECK: bb2([[RESULT:%.*]] : @owned $NSString): // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole5useNSyySo8NSStringCF // CHECK: apply [[USE]]([[RESULT]]) useNS(dummy.nonnullStringProperty as NSString) // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: switch_enum [[RESULT]] // CHECK: bb3: // CHECK: function_ref @$ss30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_line17_isImplicitUnwrapyBp_BwBi1_BwBi1_tF // CHECK: bb4([[RESULT:%.*]] : @owned $NSString): // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[RESULT]] : $NSString : $NSString, $AnyObject // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole12useAnyObjectyyyXlF // CHECK: apply [[USE]]([[ANYOBJECT]]) useAnyObject(dummy.nonnullStringProperty as AnyObject) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole23testForcedPropertyValue5dummyySo10DummyClassC_tF func testForcedPropertyValue(dummy: DummyClass) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $DummyClass): // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: switch_enum [[RESULT]] // CHECK: bb1: // CHECK: function_ref @$ss30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_line17_isImplicitUnwrapyBp_BwBi1_BwBi1_tF // CHECK: bb2([[RESULT:%.*]] : @owned $NSString): // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole5useNSyySo8NSStringCF // CHECK: apply [[USE]]([[RESULT]]) useNS(dummy.nullproneStringProperty as NSString) // This is not a force. // TODO: we could do it more efficiently than this, though // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: switch_enum [[RESULT]] // CHECK: bb3([[RESULT:%.*]] : @owned $NSString): // CHECK: function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ // CHECK: bb4: // CHECK: enum $Optional<String>, #Optional.none // CHECK: bb5([[OPTSTRING:%.*]] : @owned $Optional<String>): // CHECK: [[BRIDGE:%.*]] = function_ref @$sSq19_bridgeToObjectiveCyXlyF // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Optional<String> // CHECK-NEXT: [[BORROW:%.*]] = begin_borrow [[OPTSTRING]] // CHECK-NEXT: store_borrow [[BORROW]] to [[TEMP]] : $*Optional<String> // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE]]<String>([[TEMP]]) // CHECK: dealloc_stack [[TEMP]] // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole12useAnyObjectyyyXlF // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]]) // CHECK: destroy_value [[OPTSTRING]] useAnyObject(dummy.nullproneStringProperty as AnyObject) // CHECK: return } /*** Subscript loads *********************************************************/ // FIXME: apply peepholes to indices, too! // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole23testNonnullSubscriptGet6object5indexySo0eF0C_yXltF func testNonnullSubscriptGet(object: NonnullSubscript, index: AnyObject) { // CHECK: bb0([[SELF:%.*]] : @guaranteed $NonnullSubscript, // CHECK: [[BRIDGE_TO_ID:%.*]] = function_ref @$ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]] // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[INDEX]], [[SELF]]) // CHECK-NEXT: destroy_value [[INDEX]] : $AnyObject // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole8useOptNSyySo8NSStringCSgF // CHECK-NEXT: apply [[USE]]([[RESULT]]) useOptNS(object[index] as NSString?) // CHECK: [[BRIDGE_TO_ID:%.*]] = function_ref @$ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]] // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[INDEX]], [[SELF]]) // CHECK-NEXT: destroy_value [[INDEX]] : $AnyObject // CHECK-NEXT: switch_enum [[RESULT]] // CHECK: function_ref @$ss30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_line17_isImplicitUnwrapyBp_BwBi1_BwBi1_tF // CHECK: bb{{[0-9]+}}([[RESULT:%.*]] : @owned $NSString): // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole5useNSyySo8NSStringCF // CHECK-NEXT: apply [[USE]]([[RESULT]]) useNS(object[index] as NSString) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole24testNullableSubscriptGet6object5indexySo0eF0C_yXltF func testNullableSubscriptGet(object: NullableSubscript, index: AnyObject) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $NullableSubscript, // CHECK: [[BRIDGE_TO_ID:%.*]] = function_ref @$ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]] // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[INDEX]], [[SELF]]) // CHECK-NEXT: destroy_value [[INDEX]] : $AnyObject // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole8useOptNSyySo8NSStringCSgF // CHECK-NEXT: apply [[USE]]([[RESULT]]) useOptNS(object[index] as NSString?) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole25testNullproneSubscriptGet6object5indexySo0eF0C_yXltF func testNullproneSubscriptGet(object: NullproneSubscript, index: AnyObject) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $NullproneSubscript, // CHECK: [[BRIDGE_TO_ID:%.*]] = function_ref @$ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]] // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[INDEX]], [[SELF]]) // CHECK-NEXT: destroy_value [[INDEX]] : $AnyObject // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole8useOptNSyySo8NSStringCSgF // CHECK-NEXT: apply [[USE]]([[RESULT]]) useOptNS(object[index] as NSString?) // CHECK: [[BRIDGE_TO_ID:%.*]] = function_ref @$ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]] // CHECK: [[METHOD:%.*]] = objc_method // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[INDEX]], [[SELF]]) // CHECK-NEXT: destroy_value [[INDEX]] : $AnyObject // CHECK-NEXT: switch_enum [[RESULT]] // CHECK: function_ref @$ss30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_line17_isImplicitUnwrapyBp_BwBi1_BwBi1_tF // CHECK: bb{{[0-9]+}}([[RESULT:%.*]] : @owned $NSString): // CHECK: [[USE:%.*]] = function_ref @$s22objc_bridging_peephole5useNSyySo8NSStringCF // CHECK-NEXT: apply [[USE]]([[RESULT]]) useNS(object[index] as NSString) // CHECK: return } /*** Call arguments **********************************************************/ // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole18testMethodArgument5dummyySo10DummyClassC_tF func testMethodArgument(dummy: DummyClass) { // CHECK: bb0([[SELF:%.*]] : @guaranteed $DummyClass): // CHECK: // function_ref // CHECK-NEXT: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[ARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[ARG]] dummy.takeNonnullString(makeNS() as String) // CHECK: // function_ref // CHECK-NEXT: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[ARG]] : $NSString // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[OPTARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[OPTARG]] dummy.takeNullableString(makeNS() as String) // CHECK-NEXT: // function_ref // CHECK-NEXT: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[ARG]] : $NSString // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[OPTARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[OPTARG]] dummy.takeNullproneString(makeNS() as String) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole28testValueToOptMethodArgument5dummyySo10DummyClassC_tF func testValueToOptMethodArgument(dummy: DummyClass) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $DummyClass): // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[ARG]] : $NSString // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[OPTARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[OPTARG]] dummy.takeNullableString(makeNS() as String?) // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[ARG]] : $NSString // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[OPTARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[OPTARG]] dummy.takeNullproneString(makeNS() as String?) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole09testOptToE14MethodArgument5dummyySo10DummyClassC_tF func testOptToOptMethodArgument(dummy: DummyClass) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $DummyClass): // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole9makeOptNSSo8NSStringCSgyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[ARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[ARG]] dummy.takeNullableString(makeOptNS() as String?) // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole9makeOptNSSo8NSStringCSgyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[ARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[ARG]] dummy.takeNullproneString(makeOptNS() as String?) // CHECK: return } /*** Property assignments ****************************************************/ // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole18testPropertySetter5dummyySo10DummyClassC_tF func testPropertySetter(dummy: DummyClass) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $DummyClass): // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[ARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[ARG]] dummy.nonnullStringProperty = makeNS() as String // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[ARG]] : $NSString // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[OPTARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[OPTARG]] dummy.nullableStringProperty = makeNS() as String // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[ARG]] : $NSString // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[OPTARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[OPTARG]] dummy.nullproneStringProperty = makeNS() as String // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole28testValueToOptPropertySetter5dummyySo10DummyClassC_tF func testValueToOptPropertySetter(dummy: DummyClass) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $DummyClass): // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[ARG]] : $NSString // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[OPTARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[OPTARG]] dummy.nullableStringProperty = makeNS() as String? // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[ARG]] : $NSString // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[OPTARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[OPTARG]] dummy.nullproneStringProperty = makeNS() as String? // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole09testOptToE14PropertySetter5dummyySo10DummyClassC_tF func testOptToOptPropertySetter(dummy: DummyClass) { // CHECK: bb0([[SELF:%.*]] : @guaranteed $DummyClass): // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole9makeOptNSSo8NSStringCSgyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[ARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[ARG]] dummy.nullableStringProperty = makeOptNS() as String? // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole9makeOptNSSo8NSStringCSgyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[METHOD:%.*]] = objc_method // CHECK-NEXT: apply [[METHOD]]([[ARG]], [[SELF]]) // CHECK-NEXT: destroy_value [[ARG]] dummy.nullproneStringProperty = makeOptNS() as String? // CHECK: return } /*** Subscript assignments ***************************************************/ // FIXME: apply peepholes to indices, too! // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole23testNonnullSubscriptSet6object5indexySo0eF0C_yXltF func testNonnullSubscriptSet(object: NonnullSubscript, index: AnyObject) { // CHECK: bb0([[SELF:%.*]] : @guaranteed $NonnullSubscript, // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK: [[BRIDGE_TO_ID:%.*]] = function_ref @$ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]] // CHECK: [[METHOD:%.*]] = objc_method // CHECK: apply [[METHOD]]([[ARG]], [[INDEX]], [[SELF]]) // CHECK: destroy_value [[INDEX]] // CHECK: destroy_value [[ARG]] object[index] = makeNS() as String // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole24testNullableSubscriptSet6object5indexySo0eF0C_yXltF func testNullableSubscriptSet(object: NullableSubscript, index: AnyObject) { // CHECK: bb0([[SELF:%.*]] : @guaranteed $NullableSubscript, // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[ARG]] // CHECK: [[BRIDGE_TO_ID:%.*]] = function_ref @$ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]] // CHECK: [[METHOD:%.*]] = objc_method // CHECK: apply [[METHOD]]([[OPTARG]], [[INDEX]], [[SELF]]) // CHECK: destroy_value [[INDEX]] // CHECK: destroy_value [[OPTARG]] object[index] = makeNS() as String // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[ARG]] // CHECK: [[BRIDGE_TO_ID:%.*]] = function_ref @$ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]] // CHECK: [[METHOD:%.*]] = objc_method // CHECK: apply [[METHOD]]([[OPTARG]], [[INDEX]], [[SELF]]) // CHECK: destroy_value [[INDEX]] // CHECK: destroy_value [[OPTARG]] object[index] = makeNS() as String? // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole9makeOptNSSo8NSStringCSgyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK: [[BRIDGE_TO_ID:%.*]] = function_ref @$ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]] // CHECK: [[METHOD:%.*]] = objc_method // CHECK: apply [[METHOD]]([[ARG]], [[INDEX]], [[SELF]]) // CHECK: destroy_value [[INDEX]] // CHECK: destroy_value [[ARG]] object[index] = makeOptNS() as String? // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole25testNullproneSubscriptSet6object5indexySo0eF0C_yXltF func testNullproneSubscriptSet(object: NullproneSubscript, index: AnyObject) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $NullproneSubscript, // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[ARG]] // CHECK: [[BRIDGE_TO_ID:%.*]] = function_ref @$ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]] // CHECK: [[METHOD:%.*]] = objc_method // CHECK: apply [[METHOD]]([[OPTARG]], [[INDEX]], [[SELF]]) // CHECK: destroy_value [[INDEX]] // CHECK: destroy_value [[OPTARG]] object[index] = makeNS() as String // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole6makeNSSo8NSStringCyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[ARG]] // CHECK: [[BRIDGE_TO_ID:%.*]] = function_ref @$ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]] // CHECK: [[METHOD:%.*]] = objc_method // CHECK: apply [[METHOD]]([[OPTARG]], [[INDEX]], [[SELF]]) // CHECK: destroy_value [[INDEX]] // CHECK: destroy_value [[OPTARG]] object[index] = makeNS() as String? // CHECK: [[MAKE:%.*]] = function_ref @$s22objc_bridging_peephole9makeOptNSSo8NSStringCSgyF // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]() // CHECK: [[BRIDGE_TO_ID:%.*]] = function_ref @$ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]] // CHECK: [[METHOD:%.*]] = objc_method // CHECK: apply [[METHOD]]([[ARG]], [[INDEX]], [[SELF]]) // CHECK: destroy_value [[INDEX]] // CHECK: destroy_value [[ARG]] object[index] = makeOptNS() as String? // CHECK: return } /*** Bugfixes ***************************************************************/ protocol P { var title : String { get } } func foo(p: P) { DummyClass().takeNullableString(p.title) } // rdar://35402853 // Make sure that we don't peephole AnyObject? -> Any? -> AnyObject naively. // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole017testOptionalToNonE6BridgeyyF func testOptionalToNonOptionalBridge() { // CHECK: apply {{.*}}() : $@convention(c) () -> @autoreleased Optional<AnyObject> // CHECK: function_ref @$ss018_bridgeAnyObjectToB0yypyXlSgF : // CHECK: [[T0:%.*]] = function_ref @$sSq19_bridgeToObjectiveCyXlyF // CHECK: apply [[T0]]<Any> useAnyObject(returnNullableId() as AnyObject) } // CHECK: end sil function '$s22objc_bridging_peephole017testOptionalToNonE6BridgeyyF' // CHECK-LABEL: sil hidden [ossa] @$s22objc_bridging_peephole34testBlockToOptionalAnyObjectBridge5blockyyyXB_tF func testBlockToOptionalAnyObjectBridge(block: @escaping @convention(block) () -> ()) { // CHECK: [[T0:%.*]] = begin_borrow {{%.*}} : $@convention(block) () -> () // CHECK-NEXT: [[T1:%.*]] = copy_value [[T0]] // CHECK-NEXT: [[REF:%.*]] = unchecked_ref_cast [[T1]] : $@convention(block) () -> () to $AnyObject // CHECK-NEXT: [[OPTREF:%.*]] = enum $Optional<AnyObject>, #Optional.some!enumelt, [[REF]] : $AnyObject // CHECK-NEXT: end_borrow [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FN:%.*]] = function_ref @takeNullableId : $@convention(c) (Optional<AnyObject>) -> () // CHECK-NEXT: apply [[FN]]([[OPTREF]]) // CHECK-NEXT: destroy_value [[OPTREF]] takeNullableId(block as Any) }
apache-2.0
01ca527b2d71697dc035c16c25bc8b92
50.194257
148
0.627974
3.871615
false
true
false
false
flypaper0/ethereum-wallet
ethereum-wallet/Classes/BusinessLayer/Services/Channel/Channel.swift
1
1067
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import Foundation class Channel<SignalData> { private var observers: Set<Observer<SignalData>> private var queue: DispatchQueue init(queue: DispatchQueue) { self.queue = queue self.observers = Set<Observer<SignalData>>() } func addObserver(_ observer: Observer<SignalData>) { if observers.contains(observer) { observers.remove(observer) observers.insert(observer) } else { observers.insert(observer) } } func removeObserver(withId observerId: Identifier) { if let observer = observers.first(where: { $0.id == observerId }) { removeObserver(observer) } } func removeObserver(_ observer: Observer<SignalData>) { _ = observers.remove(observer) } func send(_ value: SignalData) { for observer in self.observers { observer.send(value) } } } extension Channel { func removeObserver(withId observerId: String) { self.removeObserver(withId: Identifier(observerId)) } }
gpl-3.0
13cd666a94770e8a4c2080929e9c3801
22.173913
71
0.679174
4.19685
false
false
false
false
sivu22/AnyTracker
AnyTracker/ItemSumViewController.swift
1
7458
// // ItemSumViewController.swift // AnyTracker // // Created by Cristian Sava on 27/08/16. // Copyright © 2016 Cristian Sava. All rights reserved. // import UIKit class ItemSumViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, NotifyItemUpdate, CellKeyboardEvent { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var valueTextField: UITextField! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var sumLabel: UILabel! @IBOutlet weak var elementsTableView: UITableView! var simpleKeyboard: SimpleKeyboard! var itemChangeDelegate: ItemChangeDelegate? var item: ItemSum! var numberSeparator: Bool = false var keyboardVisible: Bool = false var shownKeyboardHeight: CGFloat = 0 var viewOffset: CGFloat = 0 var keyboardAnimationDuration: Double = Constants.Animations.keyboardDuration var keyboardAnimationCurve: UIView.AnimationCurve = Constants.Animations.keyboardCurve var reorderTableView: LongPressReorderTableView! override func viewDidLoad() { super.viewDidLoad() title = item.name addButton.disable() sumLabel.text = item.sum.asString(withSeparator: numberSeparator) elementsTableView.delegate = self elementsTableView.dataSource = self elementsTableView.tableFooterView = UIView(frame: CGRect.zero) simpleKeyboard = SimpleKeyboard(fromViewController: self) simpleKeyboard.add(control: nameTextField) simpleKeyboard.add(control: valueTextField) Utils.addDoneButton(toTextField: valueTextField, forTarget: view, negativeTarget: self, negativeSelector: #selector(ItemSumViewController.negativePressed)) reorderTableView = LongPressReorderTableView(elementsTableView, selectedRowScale: SelectedRowScale.small) reorderTableView.delegate = self reorderTableView.enableLongPressReorder() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) simpleKeyboard.enable() simpleKeyboard.textFieldShouldReturn = { textField in textField.resignFirstResponder() return true } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) simpleKeyboard.disable() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - CellKeyboardEvent func willBeginEditing(fromView view: UIView) { simpleKeyboard.setActive(view: view) } func willEndEditing(fromView view: UIView) { simpleKeyboard.clearActiveView() } // MARK: - Actions @IBAction func addPressed(_ sender: AnyObject) { let correctString = valueTextField.text!.replacingOccurrences(of: ",", with: ".") let element = Element(name: nameTextField.text!, value: Double(correctString)!) item.insert(element: element) { error in if let error = error { let alert = error.createErrorAlert() self.present(alert, animated: true, completion: nil) return } //Utils.debugLog("Successfully added element of Sum item \(self.item.ID)") self.itemChangeDelegate?.itemChanged() self.sumLabel.text = self.item.sum.asString(withSeparator: self.numberSeparator) self.elementsTableView.beginUpdates() self.elementsTableView.insertRows(at: [IndexPath(row: self.item.elements.count - 1, section: 0)], with: UITableView.RowAnimation.right) self.elementsTableView.endUpdates() } } @IBAction func valueChanged(_ sender: AnyObject) { if valueTextField.text!.isEmpty { addButton.disable() } else { let valueText = valueTextField.text!.replacingOccurrences(of: ",", with: ".") let value = Double(valueText) if value != nil { addButton.enable() } else { addButton.disable() } } } @objc func negativePressed() { let valueText = valueTextField.text! if valueText.first == "-" { valueTextField.text = String(valueText.dropFirst()) } else { valueTextField.text = "-" + valueText } } // MARK: - TableView func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return item.elements.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = elementsTableView.dequeueReusableCell(withIdentifier: "ItemSumCell", for: indexPath) as! ItemSumCell cell.viewController = self cell.delegate = self cell.initCell(withItem: item, andElementIndex: indexPath.row, showSeparator: numberSeparator) return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if keyboardVisible { return false } return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == UITableViewCell.EditingStyle.delete) { item.remove(atIndex: indexPath.row) { error in if let error = error { let alert = error.createErrorAlert() self.present(alert, animated: true, completion: nil) return } //Utils.debugLog("Successfully removed element of Sum item \(self.item.ID)") self.itemChangeDelegate?.itemChanged() self.sumLabel.text = self.item.sum.asString(withSeparator: self.numberSeparator) CATransaction.begin() CATransaction.setCompletionBlock({() in tableView.reloadData() }) tableView.beginUpdates() tableView.deleteRows(at: [indexPath], with: .fade) tableView.endUpdates() CATransaction.commit() } } } } // MARK: - Long press drag and drop reorder extension ItemSumViewController { override func positionChanged(currentIndex: IndexPath, newIndex: IndexPath) { item.exchangeElement(fromIndex: currentIndex.row, toIndex: newIndex.row) } override func reorderFinished(initialIndex: IndexPath, finalIndex: IndexPath) { DispatchQueue.global().async { var alert: UIAlertController? do { try self.item.saveToFile() } catch let error as Status { alert = error.createErrorAlert() } catch { alert = Status.errorDefault.createErrorAlert() } DispatchQueue.main.async { if let alert = alert { self.present(alert, animated: true, completion: nil) } } } } }
mit
0d65b802988f27b6d17226b784fb53de
33.845794
163
0.611908
5.487123
false
false
false
false
TakuSemba/DribbbleSwiftApp
Carthage/Checkouts/RxSwift/Rx.playground/Pages/Error_Handling_Operators.xcplaygroundpage/Contents.swift
1
4217
/*: > # IMPORTANT: To use **Rx.playground**: 1. Open **Rx.xcworkspace**. 1. Build the **RxSwift-OSX** scheme (**Product** → **Build**). 1. Open **Rx** playground in the **Project navigator**. 1. Show the Debug Area (**View** → **Debug Area** → **Show Debug Area**). ---- [Previous](@previous) - [Table of Contents](Table_of_Contents) */ import RxSwift /*: # Error Handling Operators Operators that help to recover from error notifications from an Observable. ## `catchErrorJustReturn` Recovers from an Error event by returning an `Observable` sequence that emits a single element and then terminates. [More info](http://reactivex.io/documentation/operators/catch.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/catch.png) */ example("catchErrorJustReturn") { let disposeBag = DisposeBag() let sequenceThatFails = PublishSubject<String>() sequenceThatFails .catchErrorJustReturn("😊") .subscribe { print($0) } .addDisposableTo(disposeBag) sequenceThatFails.onNext("😬") sequenceThatFails.onNext("😨") sequenceThatFails.onNext("😡") sequenceThatFails.onNext("🔴") sequenceThatFails.onError(Error.Test) } /*: ---- ## `catchError` Recovers from an Error event by switching to the provided recovery `Observable` sequence. [More info](http://reactivex.io/documentation/operators/catch.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/catch.png) */ example("catchError") { let disposeBag = DisposeBag() let sequenceThatErrors = PublishSubject<String>() let recoverySequence = PublishSubject<String>() sequenceThatErrors .catchError { print("Error:", $0) return recoverySequence } .subscribe { print($0) } .addDisposableTo(disposeBag) sequenceThatErrors.onNext("😬") sequenceThatErrors.onNext("😨") sequenceThatErrors.onNext("😡") sequenceThatErrors.onNext("🔴") sequenceThatErrors.onError(Error.Test) recoverySequence.onNext("😊") } /*: ---- ## `retry` Recovers repeatedly Error events by rescribing to the `Observable` sequence, indefinitely. [More info](http://reactivex.io/documentation/operators/retry.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/retry.png) */ example("retry") { let disposeBag = DisposeBag() var count = 1 let sequenceThatErrors = Observable<String>.create { observer in observer.onNext("🍎") observer.onNext("🍐") observer.onNext("🍊") if count == 1 { observer.onError(Error.Test) print("Error encountered") count += 1 } observer.onNext("🐶") observer.onNext("🐱") observer.onNext("🐭") observer.onCompleted() return NopDisposable.instance } sequenceThatErrors .retry() .subscribeNext { print($0) } .addDisposableTo(disposeBag) } /*: ---- ## `retry(_:)` Recovers repeatedly from Error events by resubscribing to the `Observable` sequence, up to `maxAttemptCount` number of retries. [More info](http://reactivex.io/documentation/operators/retry.html) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/retry.png) */ example("retry maxAttemptCount") { let disposeBag = DisposeBag() var count = 1 let sequenceThatErrors = Observable<String>.create { observer in observer.onNext("🍎") observer.onNext("🍐") observer.onNext("🍊") if count < 5 { observer.onError(Error.Test) print("Error encountered") count += 1 } observer.onNext("🐶") observer.onNext("🐱") observer.onNext("🐭") observer.onCompleted() return NopDisposable.instance } sequenceThatErrors .retry(3) .subscribeNext { print($0) } .addDisposableTo(disposeBag) } //: [Next](@next) - [Table of Contents](Table_of_Contents)
apache-2.0
a6ecd58046c54123743f0be976cbfcac
30.641221
195
0.64029
4.764368
false
false
false
false
WeirdMath/TimetableSDK
Sources/Room.swift
1
3479
// // Room.swift // TimetableSDK // // Created by Sergej Jaskiewicz on 07.03.2017. // // import Foundation import SwiftyJSON /// A room. Every `Event` takes place in some room. public final class Room : JSONRepresentable, TimetableEntity { public enum Seating : Int { case theater = 0, amphitheater, roundaTable } /// The Timetable this entity was fetched from. `nil` if it was initialized from a custom JSON object. public weak var timetable: Timetable? /// The address of a building where the room is located. public weak var address: Address? /// This property is not `nil` only if the week has been initialized /// using `init(from:)`. private var _json: JSON? public let name: String public let seating: Seating public let capacity: Int public let additionalInfo: String? public let wantingEquipment: String? public let oid: String internal init(name: String, seating: Seating, capacity: Int, additionalInfo: String, wantingEquipment: String?, oid: String) { self.name = name self.seating = seating self.capacity = capacity self.additionalInfo = additionalInfo self.wantingEquipment = wantingEquipment self.oid = oid } /// Creates a new entity from its JSON representation. /// /// - Parameters: /// - json: The JSON representation of the entity. /// - timetable: The timetable object to bind to. Default is `nil`. /// - Throws: `TimetableError.incorrectJSONFormat` public init(from json: JSON, bindingTo timetable: Timetable?) throws { do { name = try map(json["DisplayName1"]) if let _seating = Seating(rawValue: try map(json["SeatingType"])) { seating = _seating } else { throw TimetableError.incorrectJSON(json, whenConverting: Room.self) } capacity = try map(json["Capacity"]) additionalInfo = try map(json["AdditionalInfo"]) wantingEquipment = try map(json["wantingEquipment"]) oid = try map(json["Oid"]) _json = json self.timetable = timetable } catch { throw TimetableError.incorrectJSON(json, whenConverting: Room.self) } } public convenience init(from jsonData: Data, bindingTo timetable: Timetable?) throws { try self.init(from: jsonData) self.timetable = timetable } public convenience init(from json: JSON) throws { try self.init(from: json, bindingTo: nil) } } extension Room : Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func ==(lhs: Room, rhs: Room) -> Bool { return lhs.name == rhs.name && lhs.oid == rhs.oid && lhs.seating == rhs.seating && lhs.capacity == rhs.capacity && lhs.additionalInfo == rhs.additionalInfo && lhs.wantingEquipment == rhs.wantingEquipment } }
mit
4c99386966c9b344572559bf823c1d5b
31.514019
106
0.579477
4.506477
false
false
false
false
a2/arex-7
ArexKit/Models/Pistachio/MessagePackAdapter.swift
1
2275
import MessagePack import Pistachio import Result import ValueTransformer private let dictionaryTransformer: ReversibleValueTransformer<[String : MessagePackValue], MessagePackValue, ErrorType> = { let transformClosure: [String : MessagePackValue] -> Result<MessagePackValue, ErrorType> = { dictionary in var messagePackDict = [MessagePackValue : MessagePackValue]() for (key, value) in dictionary { messagePackDict[.String(key)] = value } return MessagePackValueTransformers.map.transform(messagePackDict) } let reverseTransformClosure: MessagePackValue -> Result<[String : MessagePackValue], ErrorType> = { value in return MessagePackValueTransformers.map.reverseTransform(value).flatMap { dictionary in var stringDict = [String : MessagePackValue]() for (key, value) in dictionary { if let string = key.stringValue { stringDict[string] = value } else { return .failure(MessagePackValueTransformersError.ExpectedStringKey) } } return .success(stringDict) } } return ReversibleValueTransformer(transformClosure: transformClosure, reverseTransformClosure: reverseTransformClosure) }() public struct MessagePackAdapter<Value>: AdapterType { private typealias Adapter = DictionaryAdapter<String, Value, MessagePackValue, ErrorType> private let adapter: Adapter public init(specification: Adapter.Specification, valueClosure: MessagePackValue -> Result<Value, ErrorType>) { adapter = DictionaryAdapter(specification: specification, dictionaryTransformer: dictionaryTransformer, valueClosure: valueClosure) } public init(specification: Adapter.Specification, @autoclosure(escaping) value: () -> Value) { self.init(specification: specification, valueClosure: { _ in return Result.Success(value()) }) } public func transform(value: Value) -> Result<MessagePackValue, ErrorType> { return adapter.transform(value) } public func reverseTransform(transformedValue: MessagePackValue) -> Result<Value, ErrorType> { return adapter.reverseTransform(transformedValue) } }
mit
de2b49113ad4115fe491b57a045136c5
40.363636
139
0.699341
5.455635
false
false
false
false
EZ-NET/CodePiece
XcodeSourceEditorExtension/SendToCodePieceCommand.swift
1
1685
// // SendToCodePieceCommand.swift // XcodeSourceEditorExtension // // Created by Tomohiro Kumagai on 2020/02/21. // Copyright © 2020 Tomohiro Kumagai. All rights reserved. // import AppKit import XcodeKit import CodePieceCore class SendToCodePieceCommand: NSObject, XCSourceEditorCommand { func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void { guard let selection = invocation.buffer.selections.firstObject as? XCSourceTextRange else { completionHandler(nil) return } guard let lines = invocation.buffer.lines as? [String] else { completionHandler(NSError(.failedToOpenCodePiece("Unexpected lines selected: \(selection)"))) return } var endLine: Int { switch selection.end.column { case 0: return selection.end.line - 1 default: return selection.end.line } } let startLine = selection.start.line let codes = lines[startLine ... endLine] let code = Code(newlineTerminatedLines: codes) guard !code.isEmpty else { completionHandler(nil) return } let scheme = CodePieceUrlScheme(method: "open", language: "Swift", code: code.description) guard let url = URL(scheme) else { completionHandler(NSError(.failedToOpenCodePiece("Failed to create URL scheme for CodePiece."))) return } NSLog("Try opening CodePiece app using URL scheme: %@", url.absoluteString) switch NSWorkspace.shared.open(url) { case true: completionHandler(nil) case false: completionHandler(NSError(.failedToOpenCodePiece("Failed to open CodePiece (\(url.absoluteString))"))) } } }
gpl-3.0
ceec4313a25e52e01260129a897f1af1
22.388889
124
0.702494
4.137592
false
false
false
false
RyanTech/SwinjectMVVMExample
ExampleViewModelTests/ImageDetailViewModelSpec.swift
1
3257
// // ImageDetailViewModelSpec.swift // SwinjectMVVMExample // // Created by Yoichi Tagaya on 8/25/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import Quick import Nimble import ReactiveCocoa import ExampleModel @testable import ExampleViewModel class ImageDetailViewModelSpec: QuickSpec { // MARK: Stub class StubNetwork: Networking { func requestJSON(url: String, parameters: [String : AnyObject]?) -> SignalProducer<AnyObject, NetworkError> { return SignalProducer.empty } func requestImage(url: String) -> SignalProducer<UIImage, NetworkError> { return SignalProducer(value: image1x1).observeOn(QueueScheduler()) } } class ErrorStubNetwork: Networking { func requestJSON(url: String, parameters: [String : AnyObject]?) -> SignalProducer<AnyObject, NetworkError> { return SignalProducer.empty } func requestImage(url: String) -> SignalProducer<UIImage, NetworkError> { return SignalProducer(error: .InternationalRoamingOff).observeOn(QueueScheduler()) } } // MARK: - Mock class MockExternalAppChannel: ExternalAppChanneling { var passedURL: String? func openURL(url: String) { passedURL = url } } // MARK: - Spec override func spec() { var externalAppChannel: MockExternalAppChannel! var viewModel: ImageDetailViewModel! beforeEach { externalAppChannel = MockExternalAppChannel() viewModel = ImageDetailViewModel(network: StubNetwork(), externalAppChannel: externalAppChannel) } describe("Constant values") { it("sets id and username.") { viewModel.update(dummyResponse.images, atIndex: 0) expect(viewModel.id.value) == 10000 expect(viewModel.usernameText.value) == "User0" } it("formats tag and page image size texts.") { viewModel.update(dummyResponse.images, atIndex: 1) expect(viewModel.pageImageSizeText.value) == "1500 x 3000" expect(viewModel.tagText.value) == "x, y" } it("formats count values with a specified locale.") { viewModel.locale = NSLocale(localeIdentifier: "de_DE") viewModel.update(dummyResponse.images, atIndex: 1) expect(viewModel.viewCountText.value) == "123.456.789" expect(viewModel.downloadCountText.value) == "12.345.678" expect(viewModel.likeCountText.value) == "1.234.567" } } describe("Image") { it("eventually gets an image.") { viewModel.update(dummyResponse.images, atIndex: 0) expect(viewModel.image.value).toEventuallyNot(beNil()) } } describe("Image page") { it("opens the URL of the current image page.") { viewModel.update(dummyResponse.images, atIndex: 1) viewModel.openImagePage() expect(externalAppChannel.passedURL) == "https://somewhere.com/page1/" } } } }
mit
ced522a97e63966619e91c0f4445be7e
35.58427
117
0.601966
4.896241
false
false
false
false
acalvomartinez/RandomUser
RandomUserTests/AcceptanceTestCase.swift
1
891
// // AcceptanceTestCase.swift // RandomUser // // Created by Toni on 03/07/2017. // Copyright © 2017 Random User Inc. All rights reserved. // import Foundation import KIF class AcceptanceTestCase: KIFTestCase { fileprivate var originalRootViewController: UIViewController? fileprivate var rootViewController: UIViewController? { get { return UIApplication.shared.keyWindow?.rootViewController } set(newRootViewController) { UIApplication.shared.keyWindow?.rootViewController = newRootViewController } } override func tearDown() { super.tearDown() if let originalRootViewController = originalRootViewController { rootViewController = originalRootViewController } } func present(viewController: UIViewController) { originalRootViewController = rootViewController rootViewController = viewController } }
apache-2.0
d60a543c268159533096f7cb9ea6e69a
23.722222
80
0.740449
5.426829
false
true
false
false
younata/RSSClient
TethysKit/Services/FeedService/RealmFeedService.swift
1
7926
import Result import CBGPromise import RealmSwift struct RealmFeedService: FeedService { private let realmProvider: RealmProvider private let updateService: UpdateService private let mainQueue: OperationQueue private let workQueue: OperationQueue init(realmProvider: RealmProvider, updateService: UpdateService, mainQueue: OperationQueue, workQueue: OperationQueue) { self.realmProvider = realmProvider self.updateService = updateService self.mainQueue = mainQueue self.workQueue = workQueue } func feeds() -> Future<Result<AnyCollection<Feed>, TethysError>> { let promise = Promise<Result<AnyCollection<Feed>, TethysError>>() self.workQueue.addOperation { let realmFeeds = self.realmProvider.realm().objects(RealmFeed.self) let feeds = realmFeeds.map { Feed(realmFeed: $0) } guard feeds.isEmpty == false else { self.resolve(promise: promise, with: AnyCollection([])) return } let updatePromises: [Future<Result<Feed, TethysError>>] = feeds.map { return self.updateService.updateFeed($0) } Promise<Result<Feed, TethysError>>.when(updatePromises).map { results in let errors = results.compactMap { $0.error } guard errors.count != results.count else { self.resolve(promise: promise, error: .multiple(errors)) return } let updatedFeeds = results.compactMap { $0.value }.sorted { (lhs, rhs) -> Bool in guard lhs.unreadCount == rhs.unreadCount else { return lhs.unreadCount > rhs.unreadCount } return lhs.title < rhs.title } self.resolve(promise: promise, with: AnyCollection(updatedFeeds)) } } return promise.future } func articles(of feed: Feed) -> Future<Result<AnyCollection<Article>, TethysError>> { let promise = Promise<Result<AnyCollection<Article>, TethysError>>() self.workQueue.addOperation { guard let realmFeed = self.realmFeed(for: feed) else { return self.resolve(promise: promise, error: .database(.entryNotFound)) } let articles = realmFeed.articles.sorted(by: [ SortDescriptor(keyPath: "published", ascending: false) ]) return self.resolve( promise: promise, with: AnyCollection(Array(articles.map { Article(realmArticle: $0)} )) ) } return promise.future } func subscribe(to url: URL) -> Future<Result<Feed, TethysError>> { let promise = Promise<Result<Feed, TethysError>>() self.workQueue.addOperation { let predicate = NSPredicate(format: "url == %@", url.absoluteString) if let realmFeed = self.realmProvider.realm().objects(RealmFeed.self).filter(predicate).first { return self.resolve(promise: promise, with: Feed(realmFeed: realmFeed)) } let realm = self.realmProvider.realm() realm.beginWrite() let feed = RealmFeed() feed.url = url.absoluteString realm.add(feed) do { try realm.commitWrite() } catch let exception { dump(exception) return self.resolve(promise: promise, error: .database(.unknown)) } self.updateService.updateFeed(Feed(realmFeed: feed)).then { result in self.mainQueue.addOperation { promise.resolve(result) } } } return promise.future } func tags() -> Future<Result<AnyCollection<String>, TethysError>> { let promise = Promise<Result<AnyCollection<String>, TethysError>>() self.workQueue.addOperation { let tags = self.realmProvider.realm().objects(RealmFeed.self) .flatMap { feed in return feed.tags.map { $0.string } } return self.resolve(promise: promise, with: AnyCollection(Set(tags))) } return promise.future } func set(tags: [String], of feed: Feed) -> Future<Result<Feed, TethysError>> { return self.write(feed: feed) { realmFeed in let realmTags: [RealmString] = tags.map { tag in if let item = self.realmProvider.realm().object(ofType: RealmString.self, forPrimaryKey: tag) { return item } else { let item = RealmString(string: tag) self.realmProvider.realm().add(item) return item } } for (index, tag) in realmFeed.tags.enumerated() { if !realmTags.contains(tag) { realmFeed.tags.remove(at: index) } } for tag in realmTags { if !realmFeed.tags.contains(tag) { realmFeed.tags.append(tag) } } return Feed(realmFeed: realmFeed) } } func set(url: URL, on feed: Feed) -> Future<Result<Feed, TethysError>> { return self.write(feed: feed) { realmFeed in realmFeed.url = url.absoluteString return Feed(realmFeed: realmFeed) } } func readAll(of feed: Feed) -> Future<Result<Void, TethysError>> { return self.write(feed: feed) { realmFeed in realmFeed.articles.filter("read == false").forEach { $0.read = true } return Void() } } func remove(feed: Feed) -> Future<Result<Void, TethysError>> { return self.write(feed: feed) { realmFeed in self.realmProvider.realm().delete(realmFeed) return Void() }.map { (result: Result<Void, TethysError>) -> Result<Void, TethysError> in switch result { case .success, .failure(.database(.entryNotFound)): return .success(Void()) default: return result } } } private func write<T>(feed: Feed, transaction: @escaping (RealmFeed) -> T) -> Future<Result<T, TethysError>> { let promise = Promise<Result<T, TethysError>>() self.workQueue.addOperation { guard let realmFeed = self.realmFeed(for: feed) else { return self.resolve(promise: promise, error: .database(.entryNotFound)) } let realm = self.realmProvider.realm() realm.beginWrite() let value: T = transaction(realmFeed) do { try realm.commitWrite() } catch let exception { dump(exception) return self.resolve(promise: promise, error: .database(.unknown)) } return self.resolve(promise: promise, with: value) } return promise.future } private func realmFeed(for feed: Feed) -> RealmFeed? { return self.realmProvider.realm().object(ofType: RealmFeed.self, forPrimaryKey: feed.identifier) } private func resolve<T>(promise: Promise<Result<T, TethysError>>, with value: T? = nil, error: TethysError? = nil) { self.mainQueue.addOperation { let result: Result<T, TethysError> if let value = value { result = Result<T, TethysError>.success(value) } else if let error = error { result = Result<T, TethysError>.failure(error) } else { fatalError("Called resolve with two nil arguments") } promise.resolve(result) } } }
mit
1a3c3b575eb7458f524fce460ad42d89
36.742857
120
0.556901
4.926041
false
false
false
false
StephenTurton/RWPickFlavor
RWPickFlavor/PickFlavorViewController.swift
1
2734
// // ViewController.swift // IceCreamShop // // Created by Joshua Greene on 2/8/15. // Copyright (c) 2015 Razeware, LLC. All rights reserved. // import UIKit import Alamofire import MBProgressHUD public class PickFlavorViewController: UIViewController, UICollectionViewDelegate { // MARK: Instance Variables var flavors: [Flavor] = [] { didSet { pickFlavorDataSource?.flavors = flavors } } private var pickFlavorDataSource: PickFlavorDataSource? { return collectionView?.dataSource as! PickFlavorDataSource? } private let flavorFactory = FlavorFactory() // MARK: Outlets @IBOutlet var contentView: UIView! @IBOutlet var collectionView: UICollectionView! @IBOutlet var iceCreamView: IceCreamView! @IBOutlet var label: UILabel! // MARK: View Lifecycle public override func viewDidLoad() { super.viewDidLoad() loadFlavors() } private func loadFlavors() { showLoadingHUD() // 1 Alamofire.request( .GET, "http://www.raywenderlich.com/downloads/Flavors.plist", parameters: nil, encoding: .PropertyList(.XMLFormat_v1_0, 0), headers: nil) .responsePropertyList { [weak self] (_, _, result) -> Void in guard let strongSelf = self else { return } strongSelf.hideLoadingHUD() var flavorsArray: [[String : String]]! = nil switch result { case .Success(let array): if let array = array as? [[String : String]] { flavorsArray = array } case .Failure(_, _): print("Couldn't download flavors!") return } strongSelf.flavors = strongSelf.flavorFactory.flavorsFromDictionaryArray(flavorsArray) strongSelf.collectionView.reloadData() strongSelf.selectFirstFlavor() }; } private func showLoadingHUD() { let hud = MBProgressHUD.showHUDAddedTo(contentView, animated: true) hud.labelText = "Loading..." } private func hideLoadingHUD() { MBProgressHUD.hideAllHUDsForView(contentView, animated: true) } private func selectFirstFlavor() { if let flavor = flavors.first { updateWithFlavor(flavor) } } // MARK: UICollectionViewDelegate public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let flavor = flavors[indexPath.row] updateWithFlavor(flavor) } // MARK: Internal private func updateWithFlavor(flavor: Flavor) { iceCreamView.updateWithFlavor(flavor) label.text = flavor.name } }
mit
0eb4c726e36a01f74d30831a9e24cfd1
23.19469
113
0.629115
5.081784
false
false
false
false
rajeejones/SavingPennies
Pods/IBAnimatable/IBAnimatable/FlipAnimator.swift
5
8864
// // Created by Tom Baranes on 05/05/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class FlipAnimator: NSObject, AnimatedTransitioning { // MARK: - AnimatorProtocol public var transitionAnimationType: TransitionAnimationType public var transitionDuration: Duration = defaultTransitionDuration public var reverseAnimationType: TransitionAnimationType? public var interactiveGestureType: InteractiveGestureType? // MARK: - Private params fileprivate var fromDirection: TransitionAnimationType.Direction // MARK: - Private fold transition fileprivate var transform: CATransform3D = CATransform3DIdentity fileprivate var reverse: Bool = false fileprivate var horizontal: Bool = false // MARK: - Life cycle public init(from direction: TransitionAnimationType.Direction, transitionDuration: Duration) { fromDirection = direction self.transitionDuration = transitionDuration horizontal = fromDirection.isHorizontal switch fromDirection { case .right: self.transitionAnimationType = .flip(from: .right) self.reverseAnimationType = .flip(from: .left) self.interactiveGestureType = .pan(from: .left) reverse = true default: self.transitionAnimationType = .flip(from: .left) self.reverseAnimationType = .flip(from: .right) self.interactiveGestureType = .pan(from: .right) reverse = false } super.init() } } extension FlipAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return retrieveTransitionDuration(transitionContext: transitionContext) } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let (tempfromView, tempToView, tempContainerView) = retrieveViews(transitionContext: transitionContext) guard let fromView = tempfromView, let toView = tempToView, let containerView = tempContainerView else { transitionContext.completeTransition(true) return } containerView.insertSubview(toView, at: 0) transform.m34 = -0.002 containerView.layer.sublayerTransform = transform toView.frame = fromView.frame let flipViews = makeSnapshots(toView: toView, fromView: fromView, containerView: containerView) animateFlipTransition(flippedSectionOfFromView: flipViews.0, flippedSectionOfToView: flipViews.1) { if transitionContext.transitionWasCancelled { self.removeOtherViews(viewToKeep: fromView) } else { self.removeOtherViews(viewToKeep: toView) } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } } // MARK: - Setup flip transition private extension FlipAnimator { func makeSnapshots(toView: UIView, fromView: UIView, containerView: UIView) -> ((UIView, UIView), (UIView, UIView)) { let toViewSnapshots = makeSnapshot(from: toView, afterUpdates: true) var flippedSectionOfToView = toViewSnapshots[reverse ? 0 : 1] let fromViewSnapshots = makeSnapshot(from: fromView, afterUpdates: false) var flippedSectionOfFromView = fromViewSnapshots[reverse ? 1 : 0] flippedSectionOfFromView = addShadow(to: flippedSectionOfFromView, reverse: !reverse) let flippedSectionOfFromViewShadow = flippedSectionOfFromView.subviews[1] flippedSectionOfFromViewShadow.alpha = 0.0 flippedSectionOfToView = addShadow(to: flippedSectionOfToView, reverse:reverse) let flippedSectionOfToViewShadow = flippedSectionOfToView.subviews[1] flippedSectionOfToViewShadow.alpha = 1.0 var axesValues = valuesForAxe(initialValue: reverse ? 0.0 : 1.0, reverseValue: 0.5) updateAnchorPointAndOffset(anchorPoint: CGPoint(x: axesValues.0, y: axesValues.1), view: flippedSectionOfFromView) axesValues = valuesForAxe(initialValue: reverse ? 1.0 : 0.0, reverseValue: 0.5) updateAnchorPointAndOffset(anchorPoint: CGPoint(x: axesValues.0, y: axesValues.1), view: flippedSectionOfToView) flippedSectionOfToView.layer.transform = rotate(angle: reverse ? .pi * 2 : -.pi * 2) return ((flippedSectionOfFromView, flippedSectionOfFromViewShadow), (flippedSectionOfToView, flippedSectionOfToViewShadow)) } func makeSnapshot(from view: UIView, afterUpdates: Bool) -> [UIView] { let containerView = view.superview let width = valuesForAxe(initialValue: view.frame.size.width / 2, reverseValue: view.frame.size.width) let height = valuesForAxe(initialValue: view.frame.size.height, reverseValue: view.frame.size.height / 2) var snapshotRegion = CGRect(x: 0, y: 0, width: width.0, height: height.0) let leftHandView = view.resizableSnapshotView(from: snapshotRegion, afterScreenUpdates: afterUpdates, withCapInsets: .zero) leftHandView?.frame = snapshotRegion containerView?.addSubview(leftHandView!) let x = valuesForAxe(initialValue: view.frame.size.width / 2, reverseValue: 0) let y = valuesForAxe(initialValue: 0, reverseValue: view.frame.size.height / 2) snapshotRegion = CGRect(x: x.0, y: y.0, width: width.0, height: height.0) let rightHandView = view.resizableSnapshotView(from: snapshotRegion, afterScreenUpdates: afterUpdates, withCapInsets: .zero) rightHandView?.frame = snapshotRegion containerView?.addSubview(rightHandView!) containerView?.sendSubview(toBack: view) return [leftHandView!, rightHandView!] } func addShadow(to view: UIView, reverse: Bool) -> UIView { let containerView = view.superview let viewWithShadow = UIView(frame: view.frame) containerView?.insertSubview(viewWithShadow, aboveSubview: view) view.removeFromSuperview() let shadowView = UIView(frame: viewWithShadow.bounds) let gradient = CAGradientLayer() gradient.frame = shadowView.bounds gradient.colors = [UIColor(white: 0.0, alpha: 0.0), UIColor(white: 0.0, alpha: 0.5)] if horizontal { var axesValues = valuesForAxe(initialValue: reverse ? 0.0 : 1.0, reverseValue: reverse ? 0.2 : 0.0) gradient.startPoint = CGPoint(x: axesValues.0, y: axesValues.1) axesValues = valuesForAxe(initialValue: reverse ? 1.0 : 0.0, reverseValue: reverse ? 0.0 : 1.0) gradient.endPoint = CGPoint(x: axesValues.0, y: axesValues.1) } else { var axesValues = valuesForAxe(initialValue: reverse ? 0.2 : 0.0, reverseValue: reverse ? 0.0 : 1.0) gradient.startPoint = CGPoint(x: axesValues.0, y: axesValues.1) axesValues = valuesForAxe(initialValue: reverse ? 0.0 : 1.0, reverseValue: reverse ? 1.0 : 0.0) gradient.endPoint = CGPoint(x: axesValues.0, y: axesValues.1) } shadowView.layer.insertSublayer(gradient, at: 1) view.frame = view.bounds viewWithShadow.addSubview(view) viewWithShadow.addSubview(shadowView) return viewWithShadow } func updateAnchorPointAndOffset(anchorPoint: CGPoint, view: UIView) { view.layer.anchorPoint = anchorPoint if horizontal { let xOffset = anchorPoint.x - 0.5 view.frame = view.frame.offsetBy(dx: xOffset * view.frame.size.width, dy: 0) } else { let yOffset = anchorPoint.y - 0.5 view.frame = view.frame.offsetBy(dx: 0, dy: yOffset * view.frame.size.height) } } func rotate(angle: Double) -> CATransform3D { let axesValues = valuesForAxe(initialValue: 0.0, reverseValue: 1.0) return CATransform3DMakeRotation(CGFloat(angle), axesValues.0, axesValues.1, 0.0) } } // MARK: - Animates private extension FlipAnimator { func animateFlipTransition(flippedSectionOfFromView: (UIView, UIView), flippedSectionOfToView: (UIView, UIView), completion: @escaping AnimatableCompletion) { UIView.animateKeyframes(withDuration: transitionDuration, delay: 0, options: .layoutSubviews, animations: { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.5, animations: { flippedSectionOfFromView.0.layer.transform = self.rotate(angle: self.reverse ? -.pi * 2 : .pi * 2) flippedSectionOfFromView.1.alpha = 1.0 }) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations: { flippedSectionOfToView.0.layer.transform = self.rotate(angle: self.reverse ? 0.001 : -0.001) flippedSectionOfToView.1.alpha = 0.0 }) }) { _ in completion() } } } // MARK: - Helpers private extension FlipAnimator { func removeOtherViews(viewToKeep: UIView) { let containerView = viewToKeep.superview containerView?.subviews.forEach { if $0 != viewToKeep { $0.removeFromSuperview() } } } func valuesForAxe(initialValue: CGFloat, reverseValue: CGFloat) -> (CGFloat, CGFloat) { return horizontal ? (initialValue, reverseValue) : (reverseValue, initialValue) } }
gpl-3.0
505f2f1910156a0a224feb79ae883441
40.806604
160
0.727068
4.244732
false
false
false
false
bigxodus/candlelight
candlelight/screen/main/controller/ConfigController.swift
1
5073
// // ConfigureController.swift // candlelight // // Created by Lawrence on 2017. 1. 2.. // Copyright © 2017년 Waynlaw. All rights reserved. // import UIKit class ConfigController: UIViewController { static let collectionReuseIdentifier = "collectionCell" let pieMenuLocManager: PieMenuLocationManager = PieMenuLocationManager() let bottomMenuController: BottomMenuController? var collectionSource: SiteConfigDelegate? var valueLable: UILabel? required init?(coder aDecoder: NSCoder) { self.bottomMenuController = nil super.init(coder: aDecoder) } init(bottomMenuController: BottomMenuController) { self.bottomMenuController = bottomMenuController super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() } override func loadView() { super.loadView() let root = UIView() let mainRect = UIScreen.main.bounds root.frame = CGRect(x: 0, y: 0, width: mainRect.width, height: mainRect.height) let statusBarView = UIView() statusBarView.frame = UIApplication.shared.statusBarFrame statusBarView.backgroundColor = UIColor.black root.addSubview(statusBarView) root.backgroundColor = UIColor(red: 0.15, green: 0.15, blue: 0.15, alpha: 1.0) setupCommunityCollectionView(parent: root) bottomMenuController?.setupBottomButtons(parent: root, type: .config) setupPieMenuCollectionView(parent: root) self.view = root } func setupCommunityCollectionView(parent: UIView) { let parentFrame = parent.frame let statusBarHeight = UIApplication.shared.statusBarFrame.size.height let frame = CGRect( x: parentFrame.origin.x, y: parentFrame.origin.y + statusBarHeight, width: parentFrame.size.width, height: CGFloat(50 * Community.TOTAL_COUNT.rawValue) ) let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: frame.size.width, height: 50) layout.sectionInset = UIEdgeInsets.zero layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 1 let source = SiteConfigDelegate(self) let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout) collectionView.register(SiteCollectionViewCell.self, forCellWithReuseIdentifier: CommunityController.collectionReuseIdentifier) collectionView.backgroundColor = UIColor(red: 0.15, green: 0.15, blue: 0.15, alpha: 1.0) collectionView.dataSource = source collectionView.delegate = source // collectionView.contentInset = UIEdgeInsetsMake(-statusBarHeight, 0, 0, 0) parent.addSubview(collectionView) collectionSource = source } func setupPieMenuCollectionView(parent: UIView) { let parentFrame = parent.frame let statusBarHeight = UIApplication.shared.statusBarFrame.size.height let communityOptionsHeight = CGFloat(50 * Community.TOTAL_COUNT.rawValue) let margin = CGFloat(20) let locationY = parentFrame.origin.y + statusBarHeight + communityOptionsHeight + margin let frame = CGRect( x: parentFrame.origin.x, y: locationY, width: parentFrame.size.width, height: 50 ) let view = UIView() view.backgroundColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1.0) view.frame = frame let titelLabel = UILabel(frame: CGRect(x: 10, y: 0, width: frame.size.width, height: frame.size.height)) titelLabel.textAlignment = .left titelLabel.text = "파이메뉴 위치" titelLabel.textColor = UIColor(red: 0.75, green: 0.75, blue: 0.75, alpha: 1.0) view.addSubview(titelLabel) valueLable = UILabel(frame: CGRect(x: -10, y: 0, width: frame.size.width, height: frame.size.height)) valueLable!.textAlignment = .right valueLable!.text = pieMenuLocManager.select() ? "오른쪽" : "왼쪽" valueLable!.textColor = UIColor(red: 0.75, green: 0.75, blue: 0.75, alpha: 1.0) view.addSubview(valueLable!) let gesture = UITapGestureRecognizer(target: self, action: #selector(ConfigController.toggleLocationOfPieMenu)) view.addGestureRecognizer(gesture) parent.addSubview(view) } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } func toggleLocationOfPieMenu(sender: UITapGestureRecognizer) { pieMenuLocManager.toggle() valueLable?.text = pieMenuLocManager.select() ? "오른쪽" : "왼쪽" } }
apache-2.0
c71e0abf618ed77f66807be07d38a2f5
34.230769
135
0.6447
4.630515
false
false
false
false
hironytic/Moltonf-iOS
Moltonf/ViewModel/TalkViewModel.swift
1
3942
// // TalkViewModel.swift // Moltonf // // Copyright (c) 2016 Hironori Ichimiya <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import RxSwift import UIKit fileprivate typealias R = Resource public protocol ITalkViewModel: IStoryElementViewModel { var numberLine: Observable<String?> { get } var numberHiddenLine: Observable<Bool> { get } var speakerNameLine: Observable<String?> { get } var speakerIconLine: Observable<UIImage?> { get } var timeLine: Observable<String?> { get } var messageTextLine: Observable<NSAttributedString?> { get } var balloonColorLine: Observable<UIColor> { get } } public class TalkViewModel: ViewModel, ITalkViewModel { public private(set) var numberLine: Observable<String?> public private(set) var numberHiddenLine: Observable<Bool> public private(set) var speakerNameLine: Observable<String?> public private(set) var speakerIconLine: Observable<UIImage?> public private(set) var timeLine: Observable<String?> public private(set) var messageTextLine: Observable<NSAttributedString?> public private(set) var balloonColorLine: Observable<UIColor> public init(talk: Talk) { numberLine = Observable .just(talk.publicTalkNo.flatMap({ "\($0)." })) numberHiddenLine = Observable .just(talk.publicTalkNo == nil) speakerNameLine = Observable .just(talk.speaker.fullName) speakerIconLine = { () -> Observable<UIImage> in switch talk.talkType { case .grave: return talk.story?.graveIconImageLine ?? Observable.never() default: return talk.speaker.faceIconImageLine } }() .map { image -> UIImage? in return image } .asDriver(onErrorJustReturn: nil).asObservable() timeLine = Observable .just(ResourceUtils.getString(format: R.String.timeFormat, talk.time.hourPart, talk.time.minutePart)) messageTextLine = Observable .just(TalkViewModel.makeMessageText(talk.messageLines)) let color: UIColor = { () in switch talk.talkType { case .public: return R.Color.balloonPublic case .wolf: return R.Color.balloonWolf case .grave: return R.Color.balloonGrave case .private: return R.Color.balloonPrivate } }() balloonColorLine = Observable .just(color) super.init() } static func makeMessageText(_ messageLines: [String]) -> NSAttributedString { let lines = (messageLines.isEmpty || messageLines.last != "") ? messageLines : Array(messageLines.dropLast()) return NSAttributedString(string: lines.joined(separator: "\n")) } }
mit
8721839ae300b0f19c8e91cba3bce618
40.93617
117
0.669457
4.648585
false
false
false
false
Otbivnoe/Framezilla
Tests/ContainerTests.swift
1
12660
// // ContainerTests.swift // FramezillaTests // // Created by Nikita Ermolenko on 26/12/2017. // import XCTest import Framezilla class ContainerTests: BaseTest { func testContainerConfigurationFromTopToBottom() { let content1 = UIView() let content2 = UIView() let content3 = UIView() let content4 = UIView() let container = [content1, content2, content3, content4].container(in: mainView) { content1.configureFrame { maker in maker.centerX() maker.top() maker.size(width: 50, height: 50) } content2.configureFrame { maker in maker.top(to: content1.nui_bottom, inset: 5) maker.left() maker.size(width: 80, height: 80) } content3.configureFrame { maker in maker.top(to: content1.nui_bottom, inset: 15) maker.left(to: content2.nui_right, inset: 5) maker.size(width: 80, height: 80) } content4.configureFrame { maker in maker.top(to: content3.nui_bottom, inset: 5) maker.right() maker.size(width: 20, height: 20) } } XCTAssertEqual(container.frame, CGRect(x: 0, y: 0, width: 165, height: 170)) XCTAssertEqual(content1.frame, CGRect(x: 57.5, y: 0, width: 50, height: 50)) XCTAssertEqual(content2.frame, CGRect(x: 0, y: 55, width: 80, height: 80)) XCTAssertEqual(content3.frame, CGRect(x: 85, y: 65, width: 80, height: 80)) XCTAssertEqual(content4.frame, CGRect(x: 145, y: 150, width: 20, height: 20)) } func testContainerConfigurationFromLeftToRight() { let content1 = UIView() let content2 = UIView() let content3 = UIView() let container = [content1, content2, content3].container(in: mainView) { content1.configureFrame { maker in maker.left() maker.centerY() maker.size(width: 50, height: 50) } content2.configureFrame { maker in maker.left(to: content1.nui_right, inset: 5) maker.centerY() maker.size(width: 30, height: 140) } content3.configureFrame { maker in maker.left(to: content2.nui_right, inset: 15) maker.centerY() maker.size(width: 80, height: 80) } } XCTAssertEqual(container.frame, CGRect(x: 0, y: 0, width: 180, height: 140)) XCTAssertEqual(content1.frame, CGRect(x: 0, y: 45, width: 50, height: 50)) XCTAssertEqual(content2.frame, CGRect(x: 55, y: 0, width: 30, height: 140)) XCTAssertEqual(content3.frame, CGRect(x: 100, y: 30, width: 80, height: 80)) } func testContainerConfigurationWithCenterYRelation() { let content1 = UIView() let content2 = UIView() let container = [content1, content2].container(in: mainView) { content1.configureFrame { maker in maker.top(inset: 10) maker.centerX() maker.size(width: 180, height: 50) } content2.configureFrame { maker in maker.top(to: content1.nui_bottom, inset: 10) maker.left() maker.size(width: 250, height: 200) } } XCTAssertEqual(container.frame, CGRect(x: 0, y: 0, width: 250, height: 270)) XCTAssertEqual(content1.frame, CGRect(x: 35, y: 10, width: 180, height: 50)) XCTAssertEqual(content2.frame, CGRect(x: 0, y: 70, width: 250, height: 200)) } func testContainerConfigurationWithCenterXRelation() { let content1 = UIView() let content2 = UIView() let container = [content1, content2].container(in: mainView) { content2.configureFrame { maker in maker.top().left(inset: 10) maker.size(width: 200, height: 250) } content1.configureFrame { maker in maker.left(to: content2.nui_right, inset: 10) maker.centerY() maker.size(width: 50, height: 180) } } XCTAssertEqual(container.frame, CGRect(x: 0, y: 0, width: 270, height: 250)) XCTAssertEqual(content1.frame, CGRect(x: 220, y: 35, width: 50, height: 180)) XCTAssertEqual(content2.frame, CGRect(x: 10, y: 0, width: 200, height: 250)) } func testContainerConfigurationWithStaticWidth() { let content1 = UIView() let content2 = UIView() let content3 = UIView() let content4 = UIView() let container = [content1, content2, content3, content4].container(in: mainView, relation: .width(200)) { content1.configureFrame { maker in maker.top(inset: 10) maker.size(width: 100, height: 60) maker.centerX() } content2.configureFrame { maker in maker.left().right().top(to: content1.nui_bottom, inset: 10) maker.height(50) } content3.configureFrame { maker in maker.left().right().top(to: content2.nui_bottom, inset: 10) maker.height(70) } content4.configureFrame { maker in maker.top(to: content3.nui_bottom, inset: 20) maker.size(width: 30, height: 30) maker.centerX() } } XCTAssertEqual(container.frame, CGRect(x: 0, y: 0, width: 200, height: 260)) XCTAssertEqual(content1.frame, CGRect(x: 50, y: 10, width: 100, height: 60)) XCTAssertEqual(content2.frame, CGRect(x: 0, y: 80, width: 200, height: 50)) XCTAssertEqual(content3.frame, CGRect(x: 0, y: 140, width: 200, height: 70)) XCTAssertEqual(content4.frame, CGRect(x: 85, y: 230, width: 30, height: 30)) } func testContainerConfigurationWithStaticHeight() { let content1 = UIView() let content2 = UIView() let content3 = UIView() let content4 = UIView() let container = [content1, content2, content3, content4].container(in: mainView, relation: .height(200)) { content1.configureFrame { maker in maker.left(inset: 10) maker.size(width: 60, height: 100) maker.centerY() } content2.configureFrame { maker in maker.top().bottom().left(to: content1.nui_right, inset: 10) maker.width(50) } content3.configureFrame { maker in maker.top().bottom().left(to: content2.nui_right, inset: 10) maker.width(70) } content4.configureFrame { maker in maker.left(to: content3.nui_right, inset: 20) maker.size(width: 30, height: 30) maker.centerY() } } XCTAssertEqual(container.frame, CGRect(x: 0, y: 0, width: 260, height: 200)) XCTAssertEqual(content1.frame, CGRect(x: 10, y: 50, width: 60, height: 100)) XCTAssertEqual(content2.frame, CGRect(x: 80, y: 0, width: 50, height: 200)) XCTAssertEqual(content3.frame, CGRect(x: 140, y: 0, width: 70, height: 200)) XCTAssertEqual(content4.frame, CGRect(x: 230, y: 85, width: 30, height: 30)) } func testContainerConfigurationWithLeftAndRightRelations() { let content1 = UIView() let content2 = UIView() let content3 = UIView() let content4 = UIView() let container = [content1, content2, content3, content4].container(in: mainView, relation: .horizontal(left: 150, right: 150)) { content1.configureFrame { maker in maker.top(inset: 10) maker.size(width: 100, height: 60) maker.centerX() } content2.configureFrame { maker in maker.left().right().top(to: content1.nui_bottom, inset: 10) maker.height(50) } content3.configureFrame { maker in maker.left().right().top(to: content2.nui_bottom, inset: 10) maker.height(70) } content4.configureFrame { maker in maker.top(to: content3.nui_bottom, inset: 20) maker.size(width: 30, height: 30) maker.centerX() } } XCTAssertEqual(container.frame, CGRect(x: 0, y: 0, width: 200, height: 260)) XCTAssertEqual(content1.frame, CGRect(x: 50, y: 10, width: 100, height: 60)) XCTAssertEqual(content2.frame, CGRect(x: 0, y: 80, width: 200, height: 50)) XCTAssertEqual(content3.frame, CGRect(x: 0, y: 140, width: 200, height: 70)) XCTAssertEqual(content4.frame, CGRect(x: 85, y: 230, width: 30, height: 30)) } func testContainerConfigurationWithTopAndBottomRelations() { let content1 = UIView() let content2 = UIView() let content3 = UIView() let content4 = UIView() let container = [content1, content2, content3, content4].container(in: mainView, relation: .vertical(top: 150, bottom: 150)) { content1.configureFrame { maker in maker.left(inset: 10) maker.size(width: 60, height: 100) maker.centerY() } content2.configureFrame { maker in maker.top().bottom().left(to: content1.nui_right, inset: 10) maker.width(50) } content3.configureFrame { maker in maker.top().bottom().left(to: content2.nui_right, inset: 10) maker.width(70) } content4.configureFrame { maker in maker.left(to: content3.nui_right, inset: 20) maker.size(width: 30, height: 30) maker.centerY() } } XCTAssertEqual(container.frame, CGRect(x: 0, y: 0, width: 260, height: 200)) XCTAssertEqual(content1.frame, CGRect(x: 10, y: 50, width: 60, height: 100)) XCTAssertEqual(content2.frame, CGRect(x: 80, y: 0, width: 50, height: 200)) XCTAssertEqual(content3.frame, CGRect(x: 140, y: 0, width: 70, height: 200)) XCTAssertEqual(content4.frame, CGRect(x: 230, y: 85, width: 30, height: 30)) } func testContainerHaveConstantWidthWithLeftAndRightRelations() { let content1 = UIView() let container = [content1].container(in: mainView, relation: .horizontal(left: 50, right: 50)) { content1.configureFrame { maker in maker.top() maker.size(width: 500, height: 100) } } XCTAssertEqual(container.frame, CGRect(x: 0, y: 0, width: 400, height: 100)) XCTAssertEqual(content1.frame, CGRect(x: 0, y: 0, width: 500, height: 100)) } func testContainerHaveConstantWidthWithWidthRelation() { let content1 = UIView() let container = [content1].container(in: mainView, relation: .width(400)) { content1.configureFrame { maker in maker.top() maker.size(width: 500, height: 100) } } XCTAssertEqual(container.frame, CGRect(x: 0, y: 0, width: 400, height: 100)) XCTAssertEqual(content1.frame, CGRect(x: 0, y: 0, width: 500, height: 100)) } func testContainerHaveConstantHeightWithTopAndBottomRelations() { let content1 = UIView() let container = [content1].container(in: mainView, relation: .vertical(top: 50, bottom: 50)) { content1.configureFrame { maker in maker.top() maker.size(width: 100, height: 500) } } XCTAssertEqual(container.frame, CGRect(x: 0, y: 0, width: 100, height: 400)) XCTAssertEqual(content1.frame, CGRect(x: 0, y: 0, width: 100, height: 500)) } func testContainerHaveConstantHeightWithHeightRelation() { let content1 = UIView() let container = [content1].container(in: mainView, relation: .height(400)) { content1.configureFrame { maker in maker.top() maker.size(width: 100, height: 500) } } XCTAssertEqual(container.frame, CGRect(x: 0, y: 0, width: 100, height: 400)) XCTAssertEqual(content1.frame, CGRect(x: 0, y: 0, width: 100, height: 500)) } }
mit
16ad574012541f19c7ec866c22c118da
37.247734
136
0.559479
4.093113
false
true
false
false
marty-suzuki/QiitaApiClient
QiitaApiClient/Extension/NSHTTPURLResponse+QiitaApiClient.swift
1
695
// // NSHTTPURLResponse+QiitaApiClient.swift // QiitaApiClient // // Created by Taiki Suzuki on 2016/08/21. // // import Foundation extension NSHTTPURLResponse { enum StatusCodeType: Int { case Unknown = 0 case OK = 200 case Created = 201 case NoContent = 204 case BadRequest = 400 case Unauthorized = 401 case Forbidden = 403 case NotFound = 404 case InternalServerError = 500 } var statusCodeType: StatusCodeType { return StatusCodeType(rawValue: statusCode) ?? .Unknown } public var totalCount: Int? { return Int(allHeaderFields["Total-Count"] as? String ?? "") } }
mit
4b8a49b4f1be2e45a12ba43b9bc53c55
21.451613
67
0.614388
4.633333
false
false
false
false
dbgrandi/EulerKit
euler/EulerKit/BigNum.swift
1
1599
enum BigNumSign { case Negative case Positive } struct BigNum : CustomDebugStringConvertible { let sign:BigNumSign let digits:[Int] init(sign:BigNumSign, digits:[Int]) { self.sign = sign self.digits = digits } init(i:Int) { if i==0 { self.init(sign:BigNumSign.Positive, digits:[0]) } else { var tmpI = i var tmpDigits = [Int]() var sign:BigNumSign if i>0 { sign = BigNumSign.Positive } else { sign = BigNumSign.Negative tmpI = -i } while tmpI > 0 { let remainder = tmpI % 10 tmpDigits.append(remainder) tmpI = tmpI/10 } self.init(sign:sign, digits:Array(tmpDigits.reverse())) } } init(sign:BigNumSign, digitString:String) { var tmpDigits = [Int]() for i in 0...digitString.length-1 { if let digit = Int(digitString[i]) { tmpDigits.append(digit) } } self.init(sign:sign, digits:tmpDigits) } var debugDescription:String { get { return (self.sign == BigNumSign.Negative ? "-" : "") + digits.reduce("") { $0 + String($1) } } } } func + (lhs: BigNum, rhs: BigNum) -> BigNum { return lhs // TODO: implement this } func * (lhs: BigNum, rhs: Int) -> BigNum { return lhs // TODO: implement this } func * (lhs: BigNum, rhs: BigNum) -> BigNum { return lhs // TODO: implement this }
mit
23c274b855930d184a9208e6ab029fd9
22.514706
104
0.50469
3.967742
false
false
false
false
silt-lang/silt
Sources/Drill/Invocation.swift
1
6786
/// Invocation.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Foundation import Rainbow import Lithosphere import Crust import Moho import Mantle import Seismography import OuterCore import InnerCore extension Diagnostic.Message { static let noInputFiles = Diagnostic.Message(.error, "no input files provided") } extension Passes { // Create passes that perform the whole readFile->...->finalPass pipeline. static let lexFile = Passes.readFile |> Passes.lex static let shineFile = lexFile |> Passes.shine static let parseFile = shineFile |> Passes.parse static let scopeCheckFile = parseFile |> Passes.scopeCheck static let scopeCheckAsImport = parseFile |> Passes.scopeCheckImport static let typeCheckFile = scopeCheckFile |> Passes.typeCheck static let parseGIRFile = Passes.lexFile |> Passes.parseGIR static let girGenModule = typeCheckFile |> Passes.girGen static let girOptimize = girGenModule |> Passes.optimize static let irGenModule = girOptimize |> Passes.irGen } public struct Invocation { public let options: Options public init(options: Options) { self.options = options } /// Clearly denotes a function as returning `true` if errors occurred. public typealias HadErrors = Bool /// Makes a pass that runs a provided pass and then performs diagnostic /// verification after it. /// - parameters: /// - url: The URL of the file to read. /// - pass: The pass to run before verifying. /// - context: The context in which to run the pass. /// - note: The pass this function returns will never return `nil`, it will /// return `true` if the verifier produced errors and `false` /// otherwise. It is safe to force-unwrap. private func makeVerifyPass<PassTy: PassProtocol>( url: URL, pass: PassTy, context: PassContext, converter: @escaping () -> SourceLocationConverter ) -> Pass<PassTy.Input, HadErrors> { return Pass(name: "Diagnostic Verification") { input, ctx in _ = pass.run(input, in: ctx) let verifier = DiagnosticVerifier(url: url, converter: converter(), producedDiagnostics: ctx.engine.diagnostics) verifier.verify() return verifier.engine.hasErrors() } } public func run() -> HadErrors { let context = PassContext(options: options) Rainbow.enabled = options.colorsEnabled // Force Rainbow to use ANSI colors even when not in a TTY. if Rainbow.outputTarget == .unknown { Rainbow.outputTarget = .console } if options.inputURLs.isEmpty { context.engine.diagnose(.noInputFiles) return true } defer { if options.shouldPrintTiming { context.timer.dump(to: &stdoutStreamHandle) } } for url in options.inputURLs { func run<PassTy: PassProtocol>(_ pass: PassTy) -> PassTy.Output? where PassTy.Input == URL { return pass.run(url, in: context) } let consumer = DelayedPrintingDiagnosticConsumer(stream: &stderrStreamHandle) context.engine.register(consumer) switch options.mode { case .compile: fatalError("only Parse is implemented") case .dump(.tokens): run(Passes.lexFile |> Pass(name: "Describe Tokens") { tokens, _ in TokenDescriber.describe(tokens, to: &stdoutStreamHandle, converter: consumer.converter!) }) case .dump(.file): run(Passes.lexFile |> Pass(name: "Reprint File") { tokens, _ -> Void in for token in tokens { token.writeSourceText(to: &stdoutStreamHandle, includeImplicit: false) } }) case .dump(.shined): run(Passes.shineFile |> Pass(name: "Dump Shined") { tokens, _ in for token in tokens { token.writeSourceText(to: &stdoutStreamHandle, includeImplicit: true) } }) case .dump(.parse): run(Passes.parseFile |> Pass(name: "Dump Parsed") { module, _ in SyntaxDumper(stream: &stderrStreamHandle, converter: consumer.converter!).dump(module) }) case .dump(.scopes): run(Passes.scopeCheckFile |> Pass(name: "Dump Scopes") { module, _ in print(module) }) case .dump(.typecheck): run(Passes.typeCheckFile |> Pass(name: "Type Check") { module, _ in print(module) }) case .dump(.girGen): run(Passes.girGenModule |> Pass(name: "Dump Generated GIR") { mod, _ in mod.dump() }) case .dump(.parseGIR): run(Passes.parseGIRFile |> Pass(name: "Dump Parsed GIR") { module, _ in module.dump() }) case .dump(.irGen): run(Passes.irGenModule |> Pass(name: "Dump LLVM IR") { module, _ in module.dump() }) case .verify(let verification): switch verification { case .parse: return run(makeVerifyPass(url: url, pass: Passes.parseFile, context: context, converter: { consumer.converter! }))! case .scopes: return run(makeVerifyPass(url: url, pass: Passes.scopeCheckFile, context: context, converter: { consumer.converter! }))! case .typecheck: return run(makeVerifyPass(url: url, pass: Passes.typeCheckFile, context: context, converter: { consumer.converter! }))! } } } return context.engine.hasErrors() } } extension Invocation { public func runToGIRGen(_ f: @escaping (GIRModule) -> Void) -> HadErrors { let context = PassContext(options: options) Rainbow.enabled = options.colorsEnabled // Force Rainbow to use ANSI colors even when not in a TTY. if Rainbow.outputTarget == .unknown { Rainbow.outputTarget = .console } if options.inputURLs.isEmpty { context.engine.diagnose(.noInputFiles) return true } defer { if options.shouldPrintTiming { context.timer.dump(to: &stdoutStreamHandle) } } for url in options.inputURLs { func run<PassTy: PassProtocol>(_ pass: PassTy) -> PassTy.Output? where PassTy.Input == URL { return pass.run(url, in: context) } run(Passes.girGenModule |> Pass(name: "Transform Generated GIR") { m, _ in f(m) }) } return context.engine.hasErrors() } }
mit
df03ee7e142d2186635627acd89df224
32.594059
80
0.607427
4.35279
false
false
false
false
yangyueguang/MyCocoaPods
CarryOn/SwiftNotice.swift
1
15570
import UIKit import Foundation private let sn_topBar: Int = 1001 public enum NoticeType{ case success case error case info } public extension UIResponder { @discardableResult func pleaseWaitWithImages(_ imageNames: Array<UIImage>, timeInterval: Int) -> UIWindow{ return SwiftNotice.wait(imageNames, timeInterval: timeInterval) } @discardableResult func noticeTop(_ text: String, autoClear: Bool = true, autoClearTime: Int = 1) -> UIWindow{ return SwiftNotice.noticeOnStatusBar(text, autoClear: autoClear, autoClearTime: autoClearTime) } @discardableResult func noticeSuccess(_ text: String, autoClear: Bool = false, autoClearTime: Int = 3) -> UIWindow{ return SwiftNotice.showNoticeWithText(NoticeType.success, text: text, autoClear: autoClear, autoClearTime: autoClearTime) } @discardableResult func noticeError(_ text: String, autoClear: Bool = false, autoClearTime: Int = 3) -> UIWindow{ return SwiftNotice.showNoticeWithText(NoticeType.error, text: text, autoClear: autoClear, autoClearTime: autoClearTime) } @discardableResult func noticeInfo(_ text: String, autoClear: Bool = false, autoClearTime: Int = 3) -> UIWindow{ return SwiftNotice.showNoticeWithText(NoticeType.info, text: text, autoClear: autoClear, autoClearTime: autoClearTime) } @discardableResult func successNotice(_ text: String, autoClear: Bool = true) -> UIWindow{ return SwiftNotice.showNoticeWithText(NoticeType.success, text: text, autoClear: autoClear, autoClearTime: 3) } @discardableResult func errorNotice(_ text: String, autoClear: Bool = true) -> UIWindow{ return SwiftNotice.showNoticeWithText(NoticeType.error, text: text, autoClear: autoClear, autoClearTime: 3) } @discardableResult func infoNotice(_ text: String, autoClear: Bool = true) -> UIWindow{ return SwiftNotice.showNoticeWithText(NoticeType.info, text: text, autoClear: autoClear, autoClearTime: 3) } @discardableResult func notice(_ text: String, type: NoticeType, autoClear: Bool, autoClearTime: Int = 3) -> UIWindow{ return SwiftNotice.showNoticeWithText(type, text: text, autoClear: autoClear, autoClearTime: autoClearTime) } @discardableResult func pleaseWait() -> UIWindow{ return SwiftNotice.wait() } @discardableResult func noticeOnlyText(_ text: String) -> UIWindow{ return SwiftNotice.showText(text) } func clearAllNotice() { SwiftNotice.clear() } } public class SwiftNotice: NSObject { static var windows = Array<UIWindow?>() static let rv: UIView = UIApplication.shared.keyWindow?.subviews.first as UIView? ?? UIView() static var timer: DispatchSource? static var timerTimes = 0 static var degree: Double { get { return [0, 0, 180, 270, 90][UIApplication.shared.statusBarOrientation.hashValue] as Double } } static func clear() { self.cancelPreviousPerformRequests(withTarget: self) if let timer = timer { timer.cancel() self.timer = nil timerTimes = 0 } windows.removeAll(keepingCapacity: false) } @discardableResult static func noticeOnStatusBar(_ text: String, autoClear: Bool, autoClearTime: Int) -> UIWindow{ let frame = UIApplication.shared.statusBarFrame let window = UIWindow() window.backgroundColor = UIColor.clear let view = UIView() view.backgroundColor = UIColor(red: 0x6a/0x100, green: 0xb4/0x100, blue: 0x9f/0x100, alpha: 1) let label = UILabel(frame: frame) label.textAlignment = NSTextAlignment.center label.font = UIFont.systemFont(ofSize: 12) label.textColor = UIColor.white label.text = text view.addSubview(label) window.frame = frame view.frame = frame if let version = Double(UIDevice.current.systemVersion), version < 9.0 { var array = [UIScreen.main.bounds.width, UIScreen.main.bounds.height] array = array.sorted(by: <) let screenWidth = array[0] let screenHeight = array[1] let x = [0, screenWidth/2, screenWidth/2, 10, screenWidth-10][UIApplication.shared.statusBarOrientation.hashValue] as CGFloat let y = [0, 10, screenHeight-10, screenHeight/2, screenHeight/2][UIApplication.shared.statusBarOrientation.hashValue] as CGFloat window.center = CGPoint(x: x, y: y) window.transform = CGAffineTransform(rotationAngle: CGFloat(degree * Double.pi / 180)) } window.windowLevel = UIWindow.Level.statusBar window.isHidden = false window.addSubview(view) windows.append(window) var origPoint = view.frame.origin origPoint.y = -(view.frame.size.height) let destPoint = view.frame.origin view.tag = sn_topBar view.frame = CGRect(origin: origPoint, size: view.frame.size) UIView.animate(withDuration: 0.3, animations: { view.frame = CGRect(origin: destPoint, size: view.frame.size) }, completion: { b in if autoClear { let selector = #selector(SwiftNotice.hideNotice(_:)) self.perform(selector, with: window, afterDelay: TimeInterval(autoClearTime)) } }) return window } @discardableResult static func wait(_ imageNames: Array<UIImage> = Array<UIImage>(), timeInterval: Int = 0) -> UIWindow { let frame = CGRect(x: 0, y: 0, width: 78, height: 78) let window = UIWindow() window.backgroundColor = UIColor.clear let mainView = UIView() mainView.layer.cornerRadius = 12 mainView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.8) if imageNames.count > 0 { if imageNames.count > timerTimes { let iv = UIImageView(frame: frame) iv.image = imageNames.first iv.contentMode = UIView.ContentMode.scaleAspectFit mainView.addSubview(iv) timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: DispatchQueue.main) as? DispatchSource timer?.schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.milliseconds(timeInterval)) timer?.setEventHandler(handler: { () -> Void in let name = imageNames[timerTimes % imageNames.count] iv.image = name timerTimes += 1 }) timer?.resume() } } else { let ai = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.whiteLarge) ai.frame = CGRect(x: 21, y: 21, width: 36, height: 36) ai.startAnimating() mainView.addSubview(ai) } window.frame = frame mainView.frame = frame window.center = rv.center if let version = Double(UIDevice.current.systemVersion), version < 9.0 { window.center = getRealCenter() window.transform = CGAffineTransform(rotationAngle: CGFloat(degree * Double.pi / 180)) } window.windowLevel = UIWindow.Level.alert window.isHidden = false window.addSubview(mainView) windows.append(window) mainView.alpha = 0.0 UIView.animate(withDuration: 0.2, animations: { mainView.alpha = 1 }) return window } @discardableResult static func showText(_ text: String, autoClear: Bool=true, autoClearTime: Int=2) -> UIWindow { let window = UIWindow() window.backgroundColor = UIColor.clear let mainView = UIView() mainView.layer.cornerRadius = 12 mainView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.8) let label = UILabel() label.text = text label.numberOfLines = 0 label.font = UIFont.systemFont(ofSize: 13) label.textAlignment = NSTextAlignment.center label.textColor = UIColor.white let size = label.sizeThatFits(CGSize(width: UIScreen.main.bounds.width-82, height: CGFloat.greatestFiniteMagnitude)) label.bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height) mainView.addSubview(label) let superFrame = CGRect(x: 0, y: 0, width: label.frame.width + 50 , height: label.frame.height + 30) window.frame = superFrame mainView.frame = superFrame label.center = mainView.center window.center = rv.center if let version = Double(UIDevice.current.systemVersion), version < 9.0 { window.center = getRealCenter() window.transform = CGAffineTransform(rotationAngle: CGFloat(degree * Double.pi / 180)) } window.windowLevel = UIWindow.Level.alert window.isHidden = false window.addSubview(mainView) windows.append(window) if autoClear { let selector = #selector(SwiftNotice.hideNotice(_:)) self.perform(selector, with: window, afterDelay: TimeInterval(autoClearTime)) } return window } @discardableResult static func showNoticeWithText(_ type: NoticeType,text: String, autoClear: Bool, autoClearTime: Int) -> UIWindow { let frame = CGRect(x: 0, y: 0, width: 90, height: 90) let window = UIWindow() window.backgroundColor = UIColor.clear let mainView = UIView() mainView.layer.cornerRadius = 10 mainView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.7) var image = UIImage() switch type { case .success: image = SwiftNoticeSDK.imageOfCheckmark case .error: image = SwiftNoticeSDK.imageOfCross case .info: image = SwiftNoticeSDK.imageOfInfo } let checkmarkView = UIImageView(image: image) checkmarkView.frame = CGRect(x: 27, y: 15, width: 36, height: 36) mainView.addSubview(checkmarkView) let label = UILabel(frame: CGRect(x: 0, y: 60, width: 90, height: 16)) label.font = UIFont.systemFont(ofSize: 13) label.textColor = UIColor.white label.text = text label.textAlignment = NSTextAlignment.center mainView.addSubview(label) window.frame = frame mainView.frame = frame window.center = rv.center if let version = Double(UIDevice.current.systemVersion), version < 9.0 { window.center = getRealCenter() window.transform = CGAffineTransform(rotationAngle: CGFloat(degree * Double.pi / 180)) } window.windowLevel = UIWindow.Level.alert window.center = rv.center window.isHidden = false window.addSubview(mainView) windows.append(window) mainView.alpha = 0.0 UIView.animate(withDuration: 0.2, animations: { mainView.alpha = 1 }) if autoClear { let selector = #selector(SwiftNotice.hideNotice(_:)) self.perform(selector, with: window, afterDelay: TimeInterval(autoClearTime)) } return window } @objc static func hideNotice(_ sender: AnyObject) { if let window = sender as? UIWindow { if let v = window.subviews.first { UIView.animate(withDuration: 0.2, animations: { if v.tag == sn_topBar { v.frame = CGRect(x: 0, y: -v.frame.height, width: v.frame.width, height: v.frame.height) } v.alpha = 0 }, completion: { b in if let index = windows.index(where: { (item) -> Bool in return item == window }) { windows.remove(at: index) } }) } } } static func getRealCenter() -> CGPoint { if UIApplication.shared.statusBarOrientation.hashValue >= 3 { return CGPoint(x: rv.center.y, y: rv.center.x) } else { return rv.center } } } class SwiftNoticeSDK { struct Cache { static var imageOfCheckmark: UIImage? static var imageOfCross: UIImage? static var imageOfInfo: UIImage? } class func draw(_ type: NoticeType) { let checkmarkShapePath = UIBezierPath() // draw circle checkmarkShapePath.move(to: CGPoint(x: 36, y: 18)) checkmarkShapePath.addArc(withCenter: CGPoint(x: 18, y: 18), radius: 17.5, startAngle: 0, endAngle: CGFloat(Double.pi*2), clockwise: true) checkmarkShapePath.close() switch type { case .success: // draw checkmark checkmarkShapePath.move(to: CGPoint(x: 10, y: 18)) checkmarkShapePath.addLine(to: CGPoint(x: 16, y: 24)) checkmarkShapePath.addLine(to: CGPoint(x: 27, y: 13)) checkmarkShapePath.move(to: CGPoint(x: 10, y: 18)) checkmarkShapePath.close() case .error: // draw X checkmarkShapePath.move(to: CGPoint(x: 10, y: 10)) checkmarkShapePath.addLine(to: CGPoint(x: 26, y: 26)) checkmarkShapePath.move(to: CGPoint(x: 10, y: 26)) checkmarkShapePath.addLine(to: CGPoint(x: 26, y: 10)) checkmarkShapePath.move(to: CGPoint(x: 10, y: 10)) checkmarkShapePath.close() case .info: checkmarkShapePath.move(to: CGPoint(x: 18, y: 6)) checkmarkShapePath.addLine(to: CGPoint(x: 18, y: 22)) checkmarkShapePath.move(to: CGPoint(x: 18, y: 6)) checkmarkShapePath.close() UIColor.white.setStroke() checkmarkShapePath.stroke() let checkmarkShapePath = UIBezierPath() checkmarkShapePath.move(to: CGPoint(x: 18, y: 27)) checkmarkShapePath.addArc(withCenter: CGPoint(x: 18, y: 27), radius: 1, startAngle: 0, endAngle: CGFloat(Double.pi*2), clockwise: true) checkmarkShapePath.close() UIColor.white.setFill() checkmarkShapePath.fill() } UIColor.white.setStroke() checkmarkShapePath.stroke() } class var imageOfCheckmark: UIImage { if let img = Cache.imageOfCheckmark { return img } UIGraphicsBeginImageContextWithOptions(CGSize(width: 36, height: 36), false, 0) SwiftNoticeSDK.draw(NoticeType.success) Cache.imageOfCheckmark = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return Cache.imageOfCheckmark! } class var imageOfCross: UIImage { if let img = Cache.imageOfCross { return img } UIGraphicsBeginImageContextWithOptions(CGSize(width: 36, height: 36), false, 0) SwiftNoticeSDK.draw(NoticeType.error) Cache.imageOfCross = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return Cache.imageOfCross! } class var imageOfInfo: UIImage { if let img = Cache.imageOfInfo { return img } UIGraphicsBeginImageContextWithOptions(CGSize(width: 36, height: 36), false, 0) SwiftNoticeSDK.draw(NoticeType.info) Cache.imageOfInfo = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return Cache.imageOfInfo! } } public extension UIWindow{ func hide(){ SwiftNotice.hideNotice(self) } }
mit
b54510717eb9ee60a079ca7647f01092
40.631016
153
0.626654
4.636689
false
false
false
false
bizz84/MVCoreDataStack
MVCoreDataStackDemo/Classes/ViewController.swift
1
2871
// // ViewController.swift // MVCoreDataStack // // Created by Andrea Bizzotto on 19/10/2015. // Copyright © 2015 musevisions. All rights reserved. // import UIKit import CoreData import MVCoreDataStack class ViewController: UIViewController { @IBOutlet var tableView: UITableView! @IBOutlet var segmentedControl: UISegmentedControl! var fetchedResultsController: NSFetchedResultsController! lazy var coreDataStack: CoreDataStack = { return CoreDataStack(storeType: NSSQLiteStoreType, modelName: "MVCoreDataStack") }() lazy var dataWriter: DataWriter = { return DataWriter(coreDataStack: self.coreDataStack) }() var itemsToInsert: Int { switch segmentedControl.selectedSegmentIndex { case 0: return 500 case 1: return 5000 case 2: return 50000 default: return 0 } } override func viewDidLoad() { super.viewDidLoad() setup() fetch() } @IBAction func write() { dataWriter.write(self.itemsToInsert) { error in self.fetch() } } @IBAction func clear() { dataWriter.deleteAll() { error in self.fetch() } } func setup() { let fetchRequest = NSFetchRequest(entityName: "Note") fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "uid", ascending: false)] self.fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: coreDataStack.mainManagedObjectContext, sectionNameKeyPath: nil, cacheName: nil) } func fetch() { do { try fetchedResultsController.performFetch() } catch { let nserror = error as NSError print("Unable to perform fetch: \(nserror)") } self.tableView.reloadData() } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fetchedResultsController.sections?.first?.numberOfObjects ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! configureCell(cell, indexPath: indexPath) return cell } func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) { if let note = fetchedResultsController.objectAtIndexPath(indexPath) as? Note { if let uid = note.uid, let title = note.title { cell.textLabel?.text = "\(uid) - \(title)" } } } }
mit
03a478d19a680cde0a2ee57874117d49
26.075472
197
0.609756
5.717131
false
false
false
false
Pyroh/CoreGeometry
Sources/CoreGeometry/Extensions/CGSizeExtension.swift
1
19599
// // CGSizeExtension.swift // // CoreGeometry // // MIT License // // Copyright (c) 2020 Pierre Tacchi // // 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 CoreGraphics import SwiftUI import SwizzleIMD import simd public extension CGSize { /// The largest size that result from converting the source size values to integers. @inlinable var integral: Self { .init(simd2: simd2.rounded(.up)) } /// `true` if `width` == `height`. `false` otherwise. @inlinable var isSquare: Bool { width == height } /// `true` if `width` and `height` both equal 0. `false` otherwise. @inlinable var isZero: Bool { width.isZero && height.isZero } /// The receiver's aspect ratio. Equals to `width / height`. @inlinable var aspectRatio: CGFloat { if isZero { return 1 } else if height.isZero { return 0 } else { return abs(width) / abs(height) } } /// The minimum value of the size. Can be either the width or the height. @inlinable var min: CGFloat { width < height ? width : height } /// The maximum value of the size. Can be either the width or the height. @inlinable var max: CGFloat { width < height ? height : width } /// The largest square size the receiver can fit. @inlinable var minSize: CGSize { .init(square: min) } /// The smallest square that can contain the receiver. @inlinable var maxSize: CGSize { .init(square: max) } /// The area of the size. @inlinable var area: CGFloat { width * height } /// The width, halved. @inlinable var halfWidth: CGFloat { width / 2 } /// The height, halved. @inlinable var halfHeight: CGFloat { height / 2 } } public extension CGSize { /// The width rounded to the upper integer. @inlinable var integralWidth: Int { Int(width.rounded(.up)) } /// The height rounded to the upper integer. @inlinable var integralHeight: Int { Int(height.rounded(.up)) } /// Same as `integral` but with a given rounding rule. @inlinable func integral(_ rule: FloatingPointRoundingRule) -> Self { .init(simd2: simd2.rounded(rule)) } } public extension CGSize { /// Inits a size of `(amount, amount)`. @inlinable init(square amount: CGFloat) { self.init(width: amount, height: amount) } /// Inits a size of `(amount, amount)`. @inlinable init<I: BinaryInteger>(square amount: I) { self.init(width: amount.cgFloat, height: amount.cgFloat) } /// Inits a size of `(amount, amount)`. @inlinable init<F: BinaryFloatingPoint>(square amount: F) { self.init(width: amount.cgFloat, height: amount.cgFloat) } /// Inits a size of `(amount, amount)`. @inlinable init(_ square: CGFloat) { self.init(width: square.cgFloat, height: square.cgFloat) } /// Inits a size of `(amount, amount)`. @inlinable init<I: BinaryInteger>(_ square: I) { self.init(width: square.cgFloat, height: square.cgFloat) } /// Inits a size of `(amount, amount)`. @inlinable init<F: BinaryFloatingPoint>(_ square: F) { self.init(width: square.cgFloat, height: square.cgFloat) } /// Inits a size of `(width, height)`. @inlinable init(_ width: CGFloat, _ height: CGFloat) { self.init(width: width, height: height) } /// Inits a size of `(width, height)`. @inlinable init<I: BinaryInteger>(_ width: I, _ height: I) { self.init(width: width.cgFloat, height: height.cgFloat) } /// Inits a size of `(width, height)`. @inlinable init<F: BinaryFloatingPoint>(_ width: F, _ height: F) { self.init(width: width.cgFloat, height: height.cgFloat) } } public extension CGSize { /// The size with an height equal to zero. @inlinable var horizontal: CGSize { .init(width: width, height: .zero) } /// The size with a width equal to zero. @inlinable var vertical: CGSize { .init(width: .zero, height: height) } /// Inits a size of `(amount, 0)`. @inlinable init(horizontal amount: CGFloat) { self.init(width: amount, height: .zero) } /// Inits a size of `(amount, 0)`. @inlinable init<I: BinaryInteger>(horizontal amount: I) { self.init(width: amount.cgFloat, height: .zero) } /// Inits a size of `(amount, 0)`. @inlinable init<F: BinaryFloatingPoint>(horizontal amount: F) { self.init(width: amount.cgFloat, height: .zero) } /// Inits a size of `(0, amount)`. @inlinable init(vertical amount: CGFloat) { self.init(width: .zero, height: amount) } /// Inits a size of `(0, amount)`. @inlinable init<I: BinaryInteger>(vertical amount: I) { self.init(width: .zero, height: amount.cgFloat) } /// Inits a size of `(0, amount)`. @inlinable init<F: BinaryFloatingPoint>(vertical amount: F) { self.init(width: .zero, height: amount.cgFloat) } } public extension CGSize { @inlinable init(aspectRatio: CGFloat, maxEdge: CGFloat) { guard aspectRatio > 0 else { self = .init(maxEdge); return } guard aspectRatio.isFinite else { self = .init(.infinity, .infinity); return } if aspectRatio > 1 { self.init(width: maxEdge, height: maxEdge / aspectRatio) } else if aspectRatio < 1 { self.init(width: maxEdge * aspectRatio, height: maxEdge) } else { self.init(width: maxEdge, height: maxEdge) } } @inlinable init<E: BinaryInteger>(aspectRatio: CGFloat, maxEdge: E) { self.init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat) } @inlinable init<E: BinaryFloatingPoint>(aspectRatio: CGFloat, maxEdge: E) { self.init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat) } @inlinable init<A: BinaryFloatingPoint, E: BinaryInteger>(aspectRatio: A, maxEdge: E) { self.init(aspectRatio: aspectRatio.cgFloat, maxEdge: maxEdge.cgFloat) } @inlinable init<A: BinaryFloatingPoint, E: BinaryFloatingPoint>(aspectRatio: A, maxEdge: E) { self.init(aspectRatio: aspectRatio.cgFloat, maxEdge: maxEdge.cgFloat) } } public extension CGSize { @inlinable init(aspectRatio: CGFloat, minEdge: CGFloat) { guard aspectRatio > 0 else { self = .init(minEdge); return } guard aspectRatio.isFinite else { self = .init(.infinity, .infinity); return } if aspectRatio > 1 { self.init(width: minEdge * aspectRatio, height: minEdge) } else if aspectRatio < 1 { self.init(width: minEdge, height: minEdge / aspectRatio) } else { self.init(width: minEdge, height: minEdge) } } @inlinable init<E: BinaryInteger>(aspectRatio: CGFloat, minEdge: E) { self.init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat) } @inlinable init<E: BinaryFloatingPoint>(aspectRatio: CGFloat, minEdge: E) { self.init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat) } @inlinable init<A: BinaryFloatingPoint, E: BinaryInteger>(aspectRatio: A, minEdge: E) { self.init(aspectRatio: aspectRatio.cgFloat, minEdge: minEdge.cgFloat) } @inlinable init<A: BinaryFloatingPoint, E: BinaryFloatingPoint>(aspectRatio: A, minEdge: E) { self.init(aspectRatio: aspectRatio.cgFloat, minEdge: minEdge.cgFloat) } } public extension CGSize { /// The receiver's SIMD representation. @inlinable var simd2: SIMD2<CGFloat.NativeType> { get { .init(width.native, height.native) } set { (width, height) = (newValue.x.cgFloat, newValue.y.cgFloat) } } /// Inits a size from its SIMD representation. @inlinable init(simd2: SIMD2<CGFloat.NativeType>) { self.init(width: simd2.x, height: simd2.y) } } public extension CGSize { /// Multiplies `width` and `height` by the given value and returns the resulting `CGSize`. /// - Parameters: /// - lhs: The point to multiply components. /// - rhs: The value to multiply. @inlinable static func * (lhs: CGSize, rhs: CGFloat.NativeType) -> CGSize { .init(simd2: lhs.simd2 * rhs) } /// Multiplies `width` and `height` by the given value and returns the resulting `CGSize`. /// - Parameters: /// - lhs: The point to multiply components. /// - rhs: The value to multiply. @inlinable static func * <I: BinaryInteger>(lhs: CGSize, rhs: I) -> CGSize { .init(simd2: lhs.simd2 * rhs.native) } /// Multiplies `width` and `height` by the given value and returns the resulting `CGSize`. /// - Parameters: /// - lhs: The point to multiply components. /// - rhs: The value to multiply. @inlinable static func * <F: BinaryFloatingPoint>(lhs: CGSize, rhs: F) -> CGSize { .init(simd2: lhs.simd2 * rhs.native) } /// Multiplies `width` and `height` by the given value and returns the resulting `CGSize`. /// - Parameters: /// - lhs: The point to multiply components. /// - rhs: The value to multiply. @inlinable static func * (lhs: CGSize, rhs: (x: CGFloat.NativeType, y: CGFloat.NativeType)) -> CGSize { .init(simd2: lhs.simd2 * .init(rhs.x, rhs.y)) } /// Multiplies `width` and `height` by the given value and returns the resulting `CGSize`. /// - Parameters: /// - lhs: The point to multiply components. /// - rhs: The value to multiply. @inlinable static func * <I: BinaryInteger>(lhs: CGSize, rhs: (x: I, y: I)) -> CGSize { .init(simd2: lhs.simd2 * .init(rhs.x.native, rhs.y.native)) } /// Multiplies `width` and `height` by the given value and returns the resulting `CGSize`. /// - Parameters: /// - lhs: The point to multiply components. /// - rhs: The value to multiply. @inlinable static func * <F: BinaryFloatingPoint>(lhs: CGSize, rhs: (x: F, y: F)) -> CGSize { .init(simd2: lhs.simd2 * .init(rhs.x.native, rhs.y.native)) } @inlinable static func * (lhs: CGSize, rhs: CGSize) -> CGSize { .init(simd2: lhs.simd2 * rhs.simd2) } /// Divides `width` and `height` by the given value and returns the resulting `CGSize`. /// - Parameters: /// - lhs: The point to devide components. /// - rhs: The value to devide. @inlinable static func / (lhs: CGSize, rhs: CGFloat.NativeType) -> CGSize { .init(simd2: lhs.simd2 / rhs) } /// Divides `width` and `height` by the given value and returns the resulting `CGSize`. /// - Parameters: /// - lhs: The point to devide components. /// - rhs: The value to devide. @inlinable static func / <I: BinaryInteger>(lhs: CGSize, rhs: I) -> CGSize { .init(simd2: lhs.simd2 / rhs.native) } /// Divides `width` and `height` by the given value and returns the resulting `CGSize`. /// - Parameters: /// - lhs: The point to devide components. /// - rhs: The value to devide. @inlinable static func / <F: BinaryFloatingPoint>(lhs: CGSize, rhs: F) -> CGSize { .init(simd2: lhs.simd2 / rhs.native) } @inlinable static func / (lhs: CGSize, rhs: CGSize) -> CGSize { .init(simd2: lhs.simd2 / rhs.simd2) } } public extension CGSize { @inlinable static func + (lhs: CGSize, rhs: CGFloat.NativeType) -> CGSize { .init(simd2: lhs.simd2 + rhs) } @inlinable static func + <I: BinaryInteger>(lhs: CGSize, rhs: I) -> CGSize { .init(simd2: lhs.simd2 + rhs.native) } @inlinable static func + <F: BinaryFloatingPoint>(lhs: CGSize, rhs: F) -> CGSize { .init(simd2: lhs.simd2 + rhs.native) } @inlinable static func + (lhs: CGSize, rhs: (width: CGFloat.NativeType, height: CGFloat.NativeType)) -> CGSize { .init(simd2: lhs.simd2 + .init(rhs.width, rhs.height)) } @inlinable static func + <I: BinaryInteger>(lhs: CGSize, rhs: (width: I, height: I)) -> CGSize { .init(simd2: lhs.simd2 + .init(rhs.width.native, rhs.height.native)) } @inlinable static func + <F: BinaryFloatingPoint>(lhs: CGSize, rhs: (width: F, height: F)) -> CGSize { .init(simd2: lhs.simd2 + .init(rhs.width.native, rhs.height.native)) } @inlinable static func - (lhs: CGSize, rhs: CGFloat.NativeType) -> CGSize { .init(simd2: lhs.simd2 - rhs) } @inlinable static func - <I: BinaryInteger>(lhs: CGSize, rhs: I) -> CGSize { .init(simd2: lhs.simd2 - rhs.native) } @inlinable static func - <F: BinaryFloatingPoint>(lhs: CGSize, rhs: F) -> CGSize { .init(simd2: lhs.simd2 - rhs.native) } @inlinable static func - (lhs: CGSize, rhs: (width: CGFloat.NativeType, height: CGFloat.NativeType)) -> CGSize { .init(simd2: lhs.simd2 - .init(rhs.width, rhs.height)) } @inlinable static func - <I: BinaryInteger>(lhs: CGSize, rhs: (width: I, height: I)) -> CGSize { .init(simd2: lhs.simd2 - .init(rhs.width.native, rhs.height.native)) } @inlinable static func - <F: BinaryFloatingPoint>(lhs: CGSize, rhs: (width: F, height: F)) -> CGSize { .init(simd2: lhs.simd2 - .init(rhs.width.native, rhs.height.native)) } @inlinable static func + (lhs: CGSize, rhs: CGSize) -> CGSize { .init(simd2: lhs.simd2 + rhs.simd2) } @inlinable static func - (lhs: CGSize, rhs: CGSize) -> CGSize { .init(simd2: lhs.simd2 - rhs.simd2) } @inlinable static prefix func - (rhs: CGSize) -> CGSize { .init(simd2: -rhs.simd2) } } public extension CGSize { /// Contrains `self` to the given size. /// - Parameter size: The size to contrain to. @inlinable mutating func constrain(to size: CGSize) { simd2 = simd.min(simd2, size.simd2) } /// Return `self` constrained to the given size. /// - Parameter size: The size to contrain to. @inlinable func constrained(to size: CGSize) -> CGSize { .init(simd2: simd.min(simd2, size.simd2)) } } public extension CGSize { /// Returns a copy of `self` with the given width. /// - Parameter origin: The new width. @inlinable func with(width: CGFloat) -> CGSize { .init(width, height) } /// Returns a copy of `self` with the given width. /// - Parameter origin: The new width. @inlinable func with<I: BinaryInteger>(width: I) -> CGSize { .init(CGFloat(width), height) } /// Returns a copy of `self` with the given width. /// - Parameter origin: The new width. @inlinable func with<F: BinaryFloatingPoint>(width: F) -> CGSize { .init(CGFloat(width), height) } /// Returns a copy of `self` with the given height. /// - Parameter origin: The new height. @inlinable func with(height: CGFloat) -> CGSize { .init(width, height) } /// Returns a copy of `self` with the given height. /// - Parameter origin: The new height. @inlinable func with<I: BinaryInteger>(height: I) -> CGSize { .init(width, CGFloat(height)) } /// Returns a copy of `self` with the given height. /// - Parameter origin: The new height. @inlinable func with<F: BinaryFloatingPoint>(height: F) -> CGSize { .init(width, CGFloat(height)) } } public extension CGSize { @inlinable func transformWidth(_ transform: (CGFloat) throws -> CGFloat) rethrows -> CGSize { with(width: try transform(width)) } @inlinable func transformHeight(_ transform: (CGFloat) throws -> CGFloat) rethrows -> CGSize { with(height: try transform(height)) } } public extension CGSize { /// Creates a new `CGRect` with the receiver for its size and its origin set to the given point. /// - Parameter origin: The origin of the `CGRect`. /// - Returns: The resulting `CGRect`. @inlinable func makeRect(withOrigin origin: CGPoint = .zero) -> CGRect { .init(origin: origin, size: self) } /// Creates a new `CGRect` with the receiver for its size and its center set to the given point. /// - Parameter origin: The center of the `CGRect`. /// - Returns: The resulting `CGRect`. @inlinable func makeRect(withCenter center: CGPoint) -> CGRect { .init(center: center, size: self) } } public extension CGSize { /// Fits the receiver to the reference size. /// - Parameter reference: The reference size. /// - Note: The receiver and the reference size elements must be greater of equal than zero. @inlinable mutating func fit(to reference: CGSize) { let mask = Array((simd2 .> reference.simd2).elements) let maxEdge: CGFloat switch mask { case [true, false]: maxEdge = reference.width case [false, true]: maxEdge = reference.height default: maxEdge = reference.width < reference.height ? reference.width : reference.height } self = .init(aspectRatio: aspectRatio, maxEdge: maxEdge) } /// Returns the size scaled to fit the reference size. /// - Parameter reference: The reference size. /// - Note: The receiver and the reference size elements must be greater of equal than zero. @inlinable func fitted(to reference: CGSize) -> CGSize { let mask = Array((simd2 .> reference.simd2).elements) let maxEdge: CGFloat switch mask { case [true, false]: maxEdge = reference.width case [false, true]: maxEdge = reference.height default: maxEdge = reference.width < reference.height ? reference.width : reference.height } return .init(aspectRatio: aspectRatio, maxEdge: maxEdge) } /// Returns `true` if the given size's elements are both lesser that or equel to the receiver's one, respectivelty. `false` otherwise. @inlinable func contains(_ other: CGSize) -> Bool { all(other.simd2 .<= simd2) } @inlinable func clamped(min: CGSize, max: CGSize) -> CGSize { .init(simd2: simd.clamp(simd2, min: min.simd2, max: max.simd2)) } @inlinable mutating func clamp(min: CGSize, max: CGSize) { self = clamped(min: min, max: max) } } @available(OSX 10.15, iOS 13, watchOS 6.0, tvOS 13.0, *) public extension CGSize { @inlinable static func * (lhs: Self, rhs: UnitPoint) -> Self { .init(simd2: lhs.simd2 * rhs.simd2) } }
mit
08be40c69489f07d723f6f1e978c5cc3
35.979245
138
0.624216
3.932384
false
false
false
false
icanzilb/EventBlankApp
EventBlank/EventBlank/ViewControllers/Schedule/SessionDetails/SessionDetailsViewController.swift
2
3808
// // SessionDetailsViewController.swift // EventBlank // // Created by Marin Todorov on 6/25/15. // Copyright (c) 2015 Underplot ltd. All rights reserved. // import UIKit import SQLite class SessionDetailsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var session: Row! //set from previous view controller var favorites = [Int]() @IBOutlet weak var tableView: UITableView! var event: Row { return (UIApplication.sharedApplication().delegate as! AppDelegate).event } override func viewDidLoad() { super.viewDidLoad() //load favorites favorites = Favorite.allSessionFavoritesIDs() tableView.estimatedRowHeight = 100.0 tableView.rowHeight = UITableViewAutomaticDimension } //MARK: - table view methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { //speaker details let cell = tableView.dequeueReusableCellWithIdentifier("SessionDetailsCell") as! SessionDetailsCell //configure the cell cell.dateFormatter = shortStyleDateFormatter cell.isFavoriteSession = (find(favorites, session[Session.idColumn]) != nil) cell.indexPath = indexPath cell.mainColor = UIColor(hexString: event[Event.mainColor]) //populate from the session cell.populateFromSession(session) //tap handlers if let twitter = session[Speaker.twitter] where count(twitter) > 0 { cell.didTapTwitter = { let twitterUrl = NSURL(string: "https://twitter.com/" + twitter)! let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController webVC.initialURL = twitterUrl self.navigationController!.pushViewController(webVC, animated: true) } } else { cell.didTapTwitter = nil } if session[Speaker.photo]?.imageValue != nil { cell.didTapPhoto = { PhotoPopupView.showImage(self.session[Speaker.photo]!.imageValue!, inView: self.view) } } cell.didSetIsFavoriteTo = {setIsFavorite, indexPath in //TODO: update all this to Swift 2.0 let id = self.session[Session.idColumn] let isInFavorites = find(self.favorites, id) != nil if setIsFavorite && !isInFavorites { self.favorites.append(id) Favorite.saveSessionId(id) } else if !setIsFavorite && isInFavorites { self.favorites.removeAtIndex(find(self.favorites, id)!) Favorite.removeSessionId(id) } self.notification(kFavoritesChangedNotification, object: nil) } cell.didTapURL = {tappedUrl in let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController webVC.initialURL = tappedUrl self.navigationController!.pushViewController(webVC, animated: true) } return cell } fatalError("out of section bounds") } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } }
mit
d25c6f10b29af037d763816a27bb191f
36.712871
131
0.589023
5.760968
false
false
false
false
PSSWD/psswd-ios
psswd/AuthSigninConfirmVC.swift
1
2844
// // AuthSigninConfirmVC.swift // psswd // // Created by Daniil on 09.01.15. // Copyright (c) 2015 kirick. All rights reserved. // import UIKit class AuthSigninConfirmVC: UITableViewController { @IBOutlet weak var confirmCode_field: UITextField! var masterpass = "" override func viewDidLoad() { super.viewDidLoad() } @IBAction func nextPressed(sender: AnyObject) { var confirm_code = confirmCode_field.text! var masterpass_getCodes_public = Crypto.Bytes(fromString: masterpass).append(API.constants.salt_masterpass_getcodes_public).getSHA1() println("masterpass_getCodes_public \(masterpass_getCodes_public)") var params = [ "device_id": Storage.getString("device_id")!, "masterpass_getcodes_public": masterpass_getCodes_public, "confirm_code": confirm_code ] as [String: AnyObject] API.call("device.confirm", params: params, callback: { rdata in let code = rdata["code"] as! Int switch code { case 0: Storage.remove("email") var masterpass_getCodes_private = Crypto.Bytes(fromString: self.masterpass).append(API.constants.salt_masterpass_getcodes_private).getSHA1() println("masterpass_getCodes_private \(masterpass_getCodes_private)") var clientCodes = Schemas.utils.schemaBytesToData( Crypto.Cryptoblender.decrypt(rdata["data"] as! Crypto.Bytes, withKey: masterpass_getCodes_private) ) as! [Crypto.Bytes] Storage.setBytes(clientCodes[1], forKey: "code_client") Storage.setBytes(clientCodes[2], forKey: "code_client_pass") Storage.setBytes(clientCodes[3], forKey: "code_client_getdata") var pass = clientCodes[0] .concat( Storage.getBytes("code_client")! ) .concat( Storage.getBytes("code_client_pass")! ) .concat( API.constants.salt_pass ) .getSHA1() var params2 = [ "device_id": Storage.getString("device_id")!, "pass": pass ] as [String: AnyObject] API.call("device.auth", params: params2, callback: { rdata2 in let code2 = rdata2["code"] as! Int switch code2 { case 0: API.code_user = clientCodes[0].toSymbols() var vc = self.storyboard?.instantiateViewControllerWithIdentifier("MainPassListVC") as! UITableViewController self.navigationController!.setViewControllers([ vc ], animated: false) default: API.unknownCode(rdata2) } }) case 601: var attempts = rdata["data"] as! Int Funcs.message("Неверный код активации. Осталось попыток: \(attempts)") self.confirmCode_field.text = "" case 602: Funcs.message("Ошибка подтверждения. Пройдите процедуру входа заново.") Storage.clear() self.confirmCode_field.text = "" default: API.unknownCode(rdata) } }) } }
gpl-2.0
f14b30f7c2ae6d54c9d559b677bc87b1
31.494118
175
0.679218
3.388957
false
false
false
false