repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
StefanKruger/WiLibrary
|
Pod/Classes/DataLayer/JSONJoy.swift
|
1
|
5792
|
import Foundation
public class JSONDecoder {
var value: AnyObject?
///return the value raw
public var rawValue: AnyObject? {
return value
}
///print the description of the JSONDecoder
public var description: String {
return self.print()
}
///convert the value to a String
public var string: String? {
return value as? String
}
///convert the value to an Int
public var integer: Int? {
return value as? Int
}
///convert the value to an UInt
public var unsigned: UInt? {
return value as? UInt
}
///convert the value to a Double
public var double: Double? {
return value as? Double
}
///convert the value to a float
public var float: Float? {
return value as? Float
}
///convert the value to an NSNumber
public var number: NSNumber? {
return value as? NSNumber
}
///treat the value as a bool
public var bool: Bool {
if let str = self.string {
let lower = str.lowercaseString
if lower == "true" || Int(lower) > 0 {
return true
}
} else if let num = self.integer {
return num > 0
} else if let num = self.double {
return num > 0.99
} else if let num = self.float {
return num > 0.99
}
return false
}
//get the value if it is an error
public var error: NSError? {
return value as? NSError
}
//get the value if it is a dictionary
public var dictionary: Dictionary<String,JSONDecoder>? {
return value as? Dictionary<String,JSONDecoder>
}
//get the value if it is an array
public var array: Array<JSONDecoder>? {
return value as? Array<JSONDecoder>
}
//pull the raw values out of an array
public func getArray<T>(inout collect: Array<T>?) {
if let array = value as? Array<JSONDecoder> {
if collect == nil {
collect = Array<T>()
}
for decoder in array {
if let obj = decoder.value as? T {
collect?.append(obj)
}
}
}
}
///pull the raw values out of a dictionary.
public func getDictionary<T>(inout collect: Dictionary<String,T>?) {
if let dictionary = value as? Dictionary<String,JSONDecoder> {
if collect == nil {
collect = Dictionary<String,T>()
}
for (key,decoder) in dictionary {
if let obj = decoder.value as? T {
collect?[key] = obj
}
}
}
}
///the init that converts everything to something nice
public init(_ raw: AnyObject) {
var rawObject: AnyObject = raw
if let data = rawObject as? NSData {
var response: AnyObject?
do {
try response = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
rawObject = response!
}
catch let error as NSError {
value = error
return
}
}
if let array = rawObject as? NSArray {
var collect = [JSONDecoder]()
for val: AnyObject in array {
collect.append(JSONDecoder(val))
}
value = collect
} else if let dict = rawObject as? NSDictionary {
var collect = Dictionary<String,JSONDecoder>()
for (key,val) in dict {
collect[key as! String] = JSONDecoder(val)
}
value = collect
} else {
value = rawObject
}
}
///Array access support
public subscript(index: Int) -> JSONDecoder {
get {
if let array = self.value as? NSArray {
if array.count > index {
return array[index] as! JSONDecoder
}
}
return JSONDecoder(createError("index: \(index) is greater than array or this is not an Array type."))
}
}
///Dictionary access support
public subscript(key: String) -> JSONDecoder {
get {
if let dict = self.value as? NSDictionary {
if let value: AnyObject = dict[key] {
return value as! JSONDecoder
}
}
return JSONDecoder(createError("key: \(key) does not exist or this is not a Dictionary type"))
}
}
///private method to create an error
func createError(text: String) -> NSError {
return NSError(domain: "JSONJoy", code: 1002, userInfo: [NSLocalizedDescriptionKey: text]);
}
///print the decoder in a JSON format. Helpful for debugging.
public func print() -> String {
if let arr = self.array {
var str = "["
for decoder in arr {
str += decoder.print() + ","
}
str.removeAtIndex(str.endIndex.advancedBy(-1))
return str + "]"
} else if let dict = self.dictionary {
var str = "{"
for (key, decoder) in dict {
str += "\"\(key)\": \(decoder.print()),"
}
str.removeAtIndex(str.endIndex.advancedBy(-1))
return str + "}"
}
if value != nil {
if let _ = self.string {
return "\"\(value!)\""
} else if let _ = value as? NSNull {
return "null"
}
return "\(value!)"
}
return ""
}
}
///Implement this protocol on all objects you want to use JSONJoy with
public protocol JSONJoy {
init(_ decoder: JSONDecoder)
}
|
mit
|
fa9be584a852ce8af106cbdbf7a529e2
| 31 | 114 | 0.519682 | 4.867227 | false | false | false | false |
OscarSwanros/swift
|
test/stdlib/Casts.swift
|
25
|
2588
|
// Casts.swift - Tests for conversion between types.
//
// 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
//
// -----------------------------------------------------------------------------
///
/// Contains tests for conversions between types which shouldn't trap.
///
// -----------------------------------------------------------------------------
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
#if _runtime(_ObjC)
import Foundation
#endif
let CastsTests = TestSuite("Casts")
// Test for SR-426: missing release for some types after failed conversion
CastsTests.test("No leak for failed tuple casts") {
let t: Any = (1, LifetimeTracked(0))
expectFalse(t is Any.Type)
}
protocol P {}
class ErrClass : Error { }
CastsTests.test("No overrelease of existential boxes in failed casts") {
// Test for crash from SR-392
// We fail casts of an existential box repeatedly
// to ensure it does not get over-released.
func bar<T>(_ t: T) {
for _ in 0..<10 {
if case let a as P = t {
_ = a
}
}
}
let err: Error = ErrClass()
bar(err)
}
extension Int : P {}
#if _runtime(_ObjC)
extension CFBitVector : P {
static func makeImmutable(from values: Array<UInt8>) -> CFBitVector {
return CFBitVectorCreate(/*allocator:*/ nil, values, values.count * 8)
}
}
extension CFMutableBitVector {
static func makeMutable(from values: Array<UInt8>) -> CFMutableBitVector {
return CFBitVectorCreateMutableCopy(
/*allocator:*/ nil,
/*capacity:*/ 0,
CFBitVector.makeImmutable(from: values))
}
}
func isP<T>(_ t: T) -> Bool {
return t is P
}
CastsTests.test("Dynamic casts of CF types to protocol existentials")
.skip(.custom(
{ !_isDebugAssertConfiguration() },
reason: "This test behaves unpredictably in optimized mode."))
.code {
expectTrue(isP(10 as Int))
// FIXME: SR-2289: dynamic casting of CF types to protocol existentials
// should work, but there is a bug in the runtime that prevents them from
// working.
expectFailure {
expectTrue(isP(CFBitVector.makeImmutable(from: [10, 20])))
}
expectFailure {
expectTrue(isP(CFMutableBitVector.makeMutable(from: [10, 20])))
}
}
#endif
runAllTests()
|
apache-2.0
|
86662c17d51abb2355c120bba3680651
| 27.130435 | 80 | 0.63408 | 4.101426 | false | true | false | false |
Ashok28/Kingfisher
|
Sources/Views/AnimatedImageView.swift
|
1
|
23454
|
//
// AnimatableImageView.swift
// Kingfisher
//
// Created by bl4ckra1sond3tre on 4/22/16.
//
// The AnimatableImageView, AnimatedFrame and Animator is a modified version of
// some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu)
//
// The MIT License (MIT)
//
// Copyright (c) 2019 Reda Lemeden.
//
// 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.
//
// The name and characters used in the demo of this software are property of their
// respective owners.
#if !os(watchOS)
#if canImport(UIKit)
import UIKit
import ImageIO
/// Protocol of `AnimatedImageView`.
public protocol AnimatedImageViewDelegate: AnyObject {
/// Called after the animatedImageView has finished each animation loop.
///
/// - Parameters:
/// - imageView: The `AnimatedImageView` that is being animated.
/// - count: The looped count.
func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt)
/// Called after the `AnimatedImageView` has reached the max repeat count.
///
/// - Parameter imageView: The `AnimatedImageView` that is being animated.
func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView)
}
extension AnimatedImageViewDelegate {
public func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) {}
public func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) {}
}
let KFRunLoopModeCommon = RunLoop.Mode.common
/// Represents a subclass of `UIImageView` for displaying animated image.
/// Different from showing animated image in a normal `UIImageView` (which load all frames at one time),
/// `AnimatedImageView` only tries to load several frames (defined by `framePreloadCount`) to reduce memory usage.
/// It provides a tradeoff between memory usage and CPU time. If you have a memory issue when using a normal image
/// view to load GIF data, you could give this class a try.
///
/// Kingfisher supports setting GIF animated data to either `UIImageView` and `AnimatedImageView` out of box. So
/// it would be fairly easy to switch between them.
open class AnimatedImageView: UIImageView {
/// Proxy object for preventing a reference cycle between the `CADDisplayLink` and `AnimatedImageView`.
class TargetProxy {
private weak var target: AnimatedImageView?
init(target: AnimatedImageView) {
self.target = target
}
@objc func onScreenUpdate() {
target?.updateFrameIfNeeded()
}
}
/// Enumeration that specifies repeat count of GIF
public enum RepeatCount: Equatable {
case once
case finite(count: UInt)
case infinite
public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool {
switch (lhs, rhs) {
case let (.finite(l), .finite(r)):
return l == r
case (.once, .once),
(.infinite, .infinite):
return true
case (.once, .finite(let count)),
(.finite(let count), .once):
return count == 1
case (.once, _),
(.infinite, _),
(.finite, _):
return false
}
}
}
// MARK: - Public property
/// Whether automatically play the animation when the view become visible. Default is `true`.
public var autoPlayAnimatedImage = true
/// The count of the frames should be preloaded before shown.
public var framePreloadCount = 10
/// Specifies whether the GIF frames should be pre-scaled to the image view's size or not.
/// If the downloaded image is larger than the image view's size, it will help to reduce some memory use.
/// Default is `true`.
public var needsPrescaling = true
/// Decode the GIF frames in background thread before using. It will decode frames data and do a off-screen
/// rendering to extract pixel information in background. This can reduce the main thread CPU usage.
public var backgroundDecode = true
/// The animation timer's run loop mode. Default is `RunLoop.Mode.common`.
/// Set this property to `RunLoop.Mode.default` will make the animation pause during UIScrollView scrolling.
public var runLoopMode = KFRunLoopModeCommon {
willSet {
guard runLoopMode != newValue else { return }
stopAnimating()
displayLink.remove(from: .main, forMode: runLoopMode)
displayLink.add(to: .main, forMode: newValue)
startAnimating()
}
}
/// The repeat count. The animated image will keep animate until it the loop count reaches this value.
/// Setting this value to another one will reset current animation.
///
/// Default is `.infinite`, which means the animation will last forever.
public var repeatCount = RepeatCount.infinite {
didSet {
if oldValue != repeatCount {
reset()
setNeedsDisplay()
layer.setNeedsDisplay()
}
}
}
/// Delegate of this `AnimatedImageView` object. See `AnimatedImageViewDelegate` protocol for more.
public weak var delegate: AnimatedImageViewDelegate?
/// The `Animator` instance that holds the frames of a specific image in memory.
public private(set) var animator: Animator?
// MARK: - Private property
// Dispatch queue used for preloading images.
private lazy var preloadQueue: DispatchQueue = {
return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
}()
// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy.
private var isDisplayLinkInitialized: Bool = false
// A display link that keeps calling the `updateFrame` method on every screen refresh.
private lazy var displayLink: CADisplayLink = {
isDisplayLinkInitialized = true
let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
displayLink.add(to: .main, forMode: runLoopMode)
displayLink.isPaused = true
return displayLink
}()
// MARK: - Override
override open var image: KFCrossPlatformImage? {
didSet {
if image != oldValue {
reset()
}
setNeedsDisplay()
layer.setNeedsDisplay()
}
}
open override var isHighlighted: Bool {
get {
super.isHighlighted
}
set {
// Highlighted image is unsupported for animated images.
// See https://github.com/onevcat/Kingfisher/issues/1679
if displayLink.isPaused {
super.isHighlighted = newValue
}
}
}
deinit {
if isDisplayLinkInitialized {
displayLink.invalidate()
}
}
override open var isAnimating: Bool {
if isDisplayLinkInitialized {
return !displayLink.isPaused
} else {
return super.isAnimating
}
}
/// Starts the animation.
override open func startAnimating() {
guard !isAnimating else { return }
guard let animator = animator else { return }
guard !animator.isReachMaxRepeatCount else { return }
displayLink.isPaused = false
}
/// Stops the animation.
override open func stopAnimating() {
super.stopAnimating()
if isDisplayLinkInitialized {
displayLink.isPaused = true
}
}
override open func display(_ layer: CALayer) {
if let currentFrame = animator?.currentFrameImage {
layer.contents = currentFrame.cgImage
} else {
if #available(iOS 15.0, *) {
super.display(layer)
} else {
layer.contents = image?.cgImage
}
}
}
override open func didMoveToWindow() {
super.didMoveToWindow()
didMove()
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
didMove()
}
// This is for back compatibility that using regular `UIImageView` to show animated image.
override func shouldPreloadAllAnimation() -> Bool {
return false
}
// Reset the animator.
private func reset() {
animator = nil
if let image = image, let imageSource = image.kf.imageSource {
let targetSize = bounds.scaled(UIScreen.main.scale).size
let animator = Animator(
imageSource: imageSource,
contentMode: contentMode,
size: targetSize,
imageSize: image.kf.size,
imageScale: image.kf.scale,
framePreloadCount: framePreloadCount,
repeatCount: repeatCount,
preloadQueue: preloadQueue)
animator.delegate = self
animator.needsPrescaling = needsPrescaling
animator.backgroundDecode = backgroundDecode
animator.prepareFramesAsynchronously()
self.animator = animator
}
didMove()
}
private func didMove() {
if autoPlayAnimatedImage && animator != nil {
if let _ = superview, let _ = window {
startAnimating()
} else {
stopAnimating()
}
}
}
/// Update the current frame with the displayLink duration.
private func updateFrameIfNeeded() {
guard let animator = animator else {
return
}
guard !animator.isFinished else {
stopAnimating()
delegate?.animatedImageViewDidFinishAnimating(self)
return
}
let duration: CFTimeInterval
// CA based display link is opt-out from ProMotion by default.
// So the duration and its FPS might not match.
// See [#718](https://github.com/onevcat/Kingfisher/issues/718)
// By setting CADisableMinimumFrameDuration to YES in Info.plist may
// cause the preferredFramesPerSecond being 0
let preferredFramesPerSecond = displayLink.preferredFramesPerSecond
if preferredFramesPerSecond == 0 {
duration = displayLink.duration
} else {
// Some devices (like iPad Pro 10.5) will have a different FPS.
duration = 1.0 / TimeInterval(preferredFramesPerSecond)
}
animator.shouldChangeFrame(with: duration) { [weak self] hasNewFrame in
if hasNewFrame {
self?.layer.setNeedsDisplay()
}
}
}
}
protocol AnimatorDelegate: AnyObject {
func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
}
extension AnimatedImageView: AnimatorDelegate {
func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
delegate?.animatedImageView(self, didPlayAnimationLoops: count)
}
}
extension AnimatedImageView {
// Represents a single frame in a GIF.
struct AnimatedFrame {
// The image to display for this frame. Its value is nil when the frame is removed from the buffer.
let image: UIImage?
// The duration that this frame should remain active.
let duration: TimeInterval
// A placeholder frame with no image assigned.
// Used to replace frames that are no longer needed in the animation.
var placeholderFrame: AnimatedFrame {
return AnimatedFrame(image: nil, duration: duration)
}
// Whether this frame instance contains an image or not.
var isPlaceholder: Bool {
return image == nil
}
// Returns a new instance from an optional image.
//
// - parameter image: An optional `UIImage` instance to be assigned to the new frame.
// - returns: An `AnimatedFrame` instance.
func makeAnimatedFrame(image: UIImage?) -> AnimatedFrame {
return AnimatedFrame(image: image, duration: duration)
}
}
}
extension AnimatedImageView {
// MARK: - Animator
/// An animator which used to drive the data behind `AnimatedImageView`.
public class Animator {
private let size: CGSize
private let imageSize: CGSize
private let imageScale: CGFloat
/// The maximum count of image frames that needs preload.
public let maxFrameCount: Int
private let imageSource: CGImageSource
private let maxRepeatCount: RepeatCount
private let maxTimeStep: TimeInterval = 1.0
private let animatedFrames = SafeArray<AnimatedFrame>()
private var frameCount = 0
private var timeSinceLastFrameChange: TimeInterval = 0.0
private var currentRepeatCount: UInt = 0
var isFinished: Bool = false
var needsPrescaling = true
var backgroundDecode = true
weak var delegate: AnimatorDelegate?
// Total duration of one animation loop
var loopDuration: TimeInterval = 0
/// The image of the current frame.
public var currentFrameImage: UIImage? {
return frame(at: currentFrameIndex)
}
/// The duration of the current active frame duration.
public var currentFrameDuration: TimeInterval {
return duration(at: currentFrameIndex)
}
/// The index of the current animation frame.
public internal(set) var currentFrameIndex = 0 {
didSet {
previousFrameIndex = oldValue
}
}
var previousFrameIndex = 0 {
didSet {
preloadQueue.async {
self.updatePreloadedFrames()
}
}
}
var isReachMaxRepeatCount: Bool {
switch maxRepeatCount {
case .once:
return currentRepeatCount >= 1
case .finite(let maxCount):
return currentRepeatCount >= maxCount
case .infinite:
return false
}
}
/// Whether the current frame is the last frame or not in the animation sequence.
public var isLastFrame: Bool {
return currentFrameIndex == frameCount - 1
}
var preloadingIsNeeded: Bool {
return maxFrameCount < frameCount - 1
}
var contentMode = UIView.ContentMode.scaleToFill
private lazy var preloadQueue: DispatchQueue = {
return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
}()
/// Creates an animator with image source reference.
///
/// - Parameters:
/// - source: The reference of animated image.
/// - mode: Content mode of the `AnimatedImageView`.
/// - size: Size of the `AnimatedImageView`.
/// - imageSize: Size of the `KingfisherWrapper`.
/// - imageScale: Scale of the `KingfisherWrapper`.
/// - count: Count of frames needed to be preloaded.
/// - repeatCount: The repeat count should this animator uses.
/// - preloadQueue: Dispatch queue used for preloading images.
init(imageSource source: CGImageSource,
contentMode mode: UIView.ContentMode,
size: CGSize,
imageSize: CGSize,
imageScale: CGFloat,
framePreloadCount count: Int,
repeatCount: RepeatCount,
preloadQueue: DispatchQueue) {
self.imageSource = source
self.contentMode = mode
self.size = size
self.imageSize = imageSize
self.imageScale = imageScale
self.maxFrameCount = count
self.maxRepeatCount = repeatCount
self.preloadQueue = preloadQueue
GraphicsContext.begin(size: imageSize, scale: imageScale)
}
deinit {
GraphicsContext.end()
}
/// Gets the image frame of a given index.
/// - Parameter index: The index of desired image.
/// - Returns: The decoded image at the frame. `nil` if the index is out of bound or the image is not yet loaded.
public func frame(at index: Int) -> KFCrossPlatformImage? {
return animatedFrames[index]?.image
}
public func duration(at index: Int) -> TimeInterval {
return animatedFrames[index]?.duration ?? .infinity
}
func prepareFramesAsynchronously() {
frameCount = Int(CGImageSourceGetCount(imageSource))
animatedFrames.reserveCapacity(frameCount)
preloadQueue.async { [weak self] in
self?.setupAnimatedFrames()
}
}
func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) {
incrementTimeSinceLastFrameChange(with: duration)
if currentFrameDuration > timeSinceLastFrameChange {
handler(false)
} else {
resetTimeSinceLastFrameChange()
incrementCurrentFrameIndex()
handler(true)
}
}
private func setupAnimatedFrames() {
resetAnimatedFrames()
var duration: TimeInterval = 0
(0..<frameCount).forEach { index in
let frameDuration = GIFAnimatedImage.getFrameDuration(from: imageSource, at: index)
duration += min(frameDuration, maxTimeStep)
animatedFrames.append(AnimatedFrame(image: nil, duration: frameDuration))
if index > maxFrameCount { return }
animatedFrames[index] = animatedFrames[index]?.makeAnimatedFrame(image: loadFrame(at: index))
}
self.loopDuration = duration
}
private func resetAnimatedFrames() {
animatedFrames.removeAll()
}
private func loadFrame(at index: Int) -> UIImage? {
let resize = needsPrescaling && size != .zero
let options: [CFString: Any]?
if resize {
options = [
kCGImageSourceCreateThumbnailFromImageIfAbsent: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height)
]
} else {
options = nil
}
guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, index, options as CFDictionary?) else {
return nil
}
let image = KFCrossPlatformImage(cgImage: cgImage)
guard let context = GraphicsContext.current(size: imageSize, scale: imageScale, inverting: true, cgImage: cgImage) else {
return image
}
return backgroundDecode ? image.kf.decoded(on: context) : image
}
private func updatePreloadedFrames() {
guard preloadingIsNeeded else {
return
}
animatedFrames[previousFrameIndex] = animatedFrames[previousFrameIndex]?.placeholderFrame
preloadIndexes(start: currentFrameIndex).forEach { index in
guard let currentAnimatedFrame = animatedFrames[index] else { return }
if !currentAnimatedFrame.isPlaceholder { return }
animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index))
}
}
private func incrementCurrentFrameIndex() {
let wasLastFrame = isLastFrame
currentFrameIndex = increment(frameIndex: currentFrameIndex)
if isLastFrame {
currentRepeatCount += 1
if isReachMaxRepeatCount {
isFinished = true
// Notify the delegate here because the animation is stopping.
delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
}
} else if wasLastFrame {
// Notify the delegate that the loop completed
delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
}
}
private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
timeSinceLastFrameChange += min(maxTimeStep, duration)
}
private func resetTimeSinceLastFrameChange() {
timeSinceLastFrameChange -= currentFrameDuration
}
private func increment(frameIndex: Int, by value: Int = 1) -> Int {
return (frameIndex + value) % frameCount
}
private func preloadIndexes(start index: Int) -> [Int] {
let nextIndex = increment(frameIndex: index)
let lastIndex = increment(frameIndex: index, by: maxFrameCount)
if lastIndex >= nextIndex {
return [Int](nextIndex...lastIndex)
} else {
return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
}
}
}
}
class SafeArray<Element> {
private var array: Array<Element> = []
private let lock = NSLock()
subscript(index: Int) -> Element? {
get {
lock.lock()
defer { lock.unlock() }
return array.indices ~= index ? array[index] : nil
}
set {
lock.lock()
defer { lock.unlock() }
if let newValue = newValue, array.indices ~= index {
array[index] = newValue
}
}
}
var count : Int {
lock.lock()
defer { lock.unlock() }
return array.count
}
func reserveCapacity(_ count: Int) {
lock.lock()
defer { lock.unlock() }
array.reserveCapacity(count)
}
func append(_ element: Element) {
lock.lock()
defer { lock.unlock() }
array += [element]
}
func removeAll() {
lock.lock()
defer { lock.unlock() }
array = []
}
}
#endif
#endif
|
mit
|
5bd3bc071af1472adea1400c85cfb45f
| 34.163418 | 133 | 0.608723 | 5.5803 | false | false | false | false |
breadwallet/breadwallet
|
BreadWallet/BRWebViewController.swift
|
2
|
13551
|
//
// BRWebViewController.swift
// BreadWallet
//
// Created by Samuel Sutch on 12/10/15.
// Copyright (c) 2016 breadwallet LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
import WebKit
@available(iOS 8.0, *)
@objc open class BRWebViewController : UIViewController, WKNavigationDelegate, BRWebSocketClient {
var wkProcessPool: WKProcessPool
var webView: WKWebView?
var bundleName: String
var server = BRHTTPServer()
var debugEndpoint: String? // = "http://localhost:8080"
var mountPoint: String
// bonjour debug endpoint establishment - this will configure the debugEndpoint
// over bonjour if debugOverBonjour is set to true. this MUST be set to false
// for production deploy targets
let debugOverBonjour = false
let bonjourBrowser = Bonjour()
var debugNetService: NetService?
// didLoad should be set to true within didLoadTimeout otherwise a view will be shown which
// indicates some error. this is to prevent the white-screen-of-death where there is some
// javascript exception (or other error) that prevents the content from loading
var didLoad = false
var didAppear = false
var didLoadTimeout = 2500
// we are also a socket server which sends didview/didload events to the listening client(s)
var sockets = [String: BRWebSocket]()
// this is the data that occasionally gets sent to the above connected sockets
var webViewInfo: [String: Any] {
return [
"visible": didAppear,
"loaded": didLoad,
]
}
var indexUrl: URL {
return URL(string: "http://127.0.0.1:\(server.port)\(mountPoint)")!
}
init(bundleName name: String, mountPoint mp: String = "/") {
wkProcessPool = WKProcessPool()
bundleName = name
mountPoint = mp
super.init(nibName: nil, bundle: nil)
if debugOverBonjour {
setupBonjour()
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func loadView() {
didLoad = false
let config = WKWebViewConfiguration()
config.processPool = wkProcessPool
config.allowsInlineMediaPlayback = false
if #available(iOS 9.0, *) {
config.allowsAirPlayForMediaPlayback = false
config.requiresUserActionForMediaPlayback = true
config.allowsPictureInPictureMediaPlayback = false
}
let request = URLRequest(url: indexUrl)
view = UIView(frame: CGRect.zero)
view.backgroundColor = UIColor(red:0.98, green:0.98, blue:0.98, alpha:1.0)
webView = WKWebView(frame: CGRect.zero, configuration: config)
webView?.navigationDelegate = self
webView?.backgroundColor = UIColor(red:0.98, green:0.98, blue:0.98, alpha:1.0)
_ = webView?.load(request)
webView?.autoresizingMask = [.flexibleHeight, .flexibleWidth]
view.addSubview(webView!)
NotificationCenter.default.addObserver(forName: .UIApplicationDidBecomeActive, object: nil, queue: OperationQueue.main) { (_) in
self.didAppear = true
self.sendToAllSockets(data: self.webViewInfo)
}
NotificationCenter.default.addObserver(forName: .UIApplicationWillResignActive, object: nil, queue: OperationQueue.main) { (_) in
self.didAppear = false
self.sendToAllSockets(data: self.webViewInfo)
}
}
override open func viewWillAppear(_ animated: Bool) {
edgesForExtendedLayout = .all
self.beginDidLoadCountdown()
}
override open func viewDidAppear(_ animated: Bool) {
didAppear = true
sendToAllSockets(data: webViewInfo)
}
override open func viewDidDisappear(_ animated: Bool) {
didAppear = false
sendToAllSockets(data: webViewInfo)
}
fileprivate func closeNow() {
dismiss(animated: true, completion: nil)
}
// this should be called when the webview is expected to load content. if the content has not signaled
// that is has loaded by didLoadTimeout then an alert will be shown allowing the user to back out
// of the faulty webview
fileprivate func beginDidLoadCountdown() {
let timeout = DispatchTime.now() + .milliseconds(self.didLoadTimeout)
DispatchQueue.main.asyncAfter(deadline: timeout) {
if self.didAppear && !self.didLoad {
// if the webview did not load the first time lets refresh the bundle. occasionally the bundle
// update can fail, so this update should fetch an entirely new copy
let activity = BRActivityViewController(message: NSLocalizedString("Updating...", comment: ""))
self.present(activity, animated: true, completion: nil)
BRAPIClient.sharedClient.updateBundle(self.bundleName) { (err) in
if err != nil {
print("[BRWebViewController] error updating bundle: \(String(describing: err))")
}
// give the webview another chance to load
self.refresh()
// XXX(sam): log this event so we know how frequently it happens
DispatchQueue.main.asyncAfter(deadline: timeout) {
self.dismiss(animated: true) {
self.notifyUserOfLoadFailure()
}
}
}
}
}
}
fileprivate func notifyUserOfLoadFailure() {
if self.didAppear && !self.didLoad {
let alert = UIAlertController.init(
title: NSLocalizedString("Error", comment: ""),
message: NSLocalizedString("There was an error loading the content. Please try again", comment: ""),
preferredStyle: .alert
)
let action = UIAlertAction(title: NSLocalizedString("Dismiss", comment: ""), style: .default) { _ in
self.closeNow()
}
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
// signal to the presenter that the webview content successfully loaded
fileprivate func webviewDidLoad() {
didLoad = true
sendToAllSockets(data: webViewInfo)
}
open func startServer() {
do {
if !server.isStarted {
try server.start()
setupIntegrations()
}
} catch let e {
print("\n\n\nSERVER ERROR! \(e)\n\n\n")
}
}
// this will look on the network for any _http._tcp bonjour services whose name
// contains th string "webpack" and will set our debugEndpoint to whatever that
// resolves to. this allows us to debug bundles over the network without complicated setup
fileprivate func setupBonjour() {
let _ = bonjourBrowser.findService("_http._tcp") { (services) in
for svc in services {
if !svc.name.lowercased().contains("webpack") {
continue
}
self.debugNetService = svc
svc.resolve(withTimeout: 1.0)
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
guard let netService = self.debugNetService else {
return
}
self.debugEndpoint = "http://\(netService.hostName ?? ""):\(netService.port)"
print("[BRWebViewController] discovered bonjour debugging service \(String(describing: self.debugEndpoint))")
self.server.resetMiddleware()
self.setupIntegrations()
self.refresh()
}
break
}
}
}
fileprivate func setupIntegrations() {
// proxy api for signing and verification
let apiProxy = BRAPIProxy(mountAt: "/_api", client: BRAPIClient.sharedClient)
server.prependMiddleware(middleware: apiProxy)
// http router for native functionality
let router = BRHTTPRouter()
server.prependMiddleware(middleware: router)
// basic file server for static assets
let fileMw = BRHTTPFileMiddleware(baseURL: BRAPIClient.bundleURL(bundleName))
server.prependMiddleware(middleware: fileMw)
// middleware to always return index.html for any unknown GET request (facilitates window.history style SPAs)
let indexMw = BRHTTPIndexMiddleware(baseURL: fileMw.baseURL)
server.prependMiddleware(middleware: indexMw)
// geo plugin provides access to onboard geo location functionality
router.plugin(BRGeoLocationPlugin())
// camera plugin
router.plugin(BRCameraPlugin(fromViewController: self))
// wallet plugin provides access to the wallet
router.plugin(BRWalletPlugin())
// link plugin which allows opening links to other apps
router.plugin(BRLinkPlugin(fromViewController: self))
// kvstore plugin provides access to the shared replicated kv store
router.plugin(BRKVStorePlugin(client: BRAPIClient.sharedClient))
// GET /_close closes the browser modal
router.get("/_close") { (request, _) -> BRHTTPResponse in
DispatchQueue.main.async {
self.closeNow()
}
return BRHTTPResponse(request: request, code: 204)
}
// GET /_didload signals to the presenter that the content successfully loaded
router.get("/_didload") { (request, _) -> BRHTTPResponse in
DispatchQueue.main.async {
self.webviewDidLoad()
}
return BRHTTPResponse(request: request, code: 204)
}
// socket /_webviewinfo will send info about the webview state to client
router.websocket("/_webviewinfo", client: self)
router.printDebug()
// enable debug if it is turned on
if let debugUrl = debugEndpoint {
let url = URL(string: debugUrl)
fileMw.debugURL = url
indexMw.debugURL = url
}
}
open func preload() {
_ = self.view // force webview loading
}
open func refresh() {
let request = URLRequest(url: indexUrl)
_ = webView?.load(request)
}
// MARK: - navigation delegate
open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.url, let host = url.host, let port = (url as NSURL).port {
if host == server.listenAddress || port.int32Value == Int32(server.port) {
return decisionHandler(.allow)
}
}
print("[BRWebViewController disallowing navigation: \(navigationAction)")
decisionHandler(.cancel)
}
// MARK: - socket delegate
func sendTo(socket: BRWebSocket, data: [String: Any]) {
do {
let j = try JSONSerialization.data(withJSONObject: data, options: [])
if let s = String(data: j, encoding: .utf8) {
socket.request.queue.async {
socket.send(s)
}
}
} catch let e {
print("LOCATION SOCKET FAILED ENCODE JSON: \(e)")
}
}
func sendToAllSockets(data: [String: Any]) {
for (_, s) in sockets {
sendTo(socket: s, data: data)
}
}
public func socketDidConnect(_ socket: BRWebSocket) {
print("WEBVIEW SOCKET CONNECT \(socket.id)")
sockets[socket.id] = socket
sendTo(socket: socket, data: webViewInfo)
}
public func socketDidDisconnect(_ socket: BRWebSocket) {
print("WEBVIEW SOCKET DISCONNECT \(socket.id)")
sockets.removeValue(forKey: socket.id)
}
public func socket(_ socket: BRWebSocket, didReceiveText text: String) {
print("WEBVIEW SOCKET RECV \(text)")
// this is unused here but just in case just echo received text back
socket.send(text)
}
}
|
mit
|
2fb6f4b6a7312d15925f486f66e3c7a0
| 39.330357 | 137 | 0.613608 | 5.045048 | false | false | false | false |
rahul-apple/XMPP-Zom_iOS
|
Zom/Zom/Classes/Views/ZomBuddyInfoCell.swift
|
1
|
1653
|
//
// ZomBuddyInfoCell.swift
// Zom
//
// Created by N-Pex on 2016-05-17.
//
//
import UIKit
public class ZomBuddyInfoCell: OTRBuddyInfoCell {
override public func updateConstraints() {
let firstTime:Bool = !self.addedConstraints
super.updateConstraints()
if (firstTime) {
// If we only have the name, remove all extra constraints and align that in the center Y position
//
if ((self.identifierLabel.text == "" || self.identifierLabel.text == nil) &&
(self.accountLabel.text == "" || self.accountLabel.text == nil)) {
var removeThese:[NSLayoutConstraint] = [NSLayoutConstraint]()
for constraint:NSLayoutConstraint in self.constraints {
if ((constraint.firstItem as? NSObject != nil && constraint.firstItem as! NSObject == self.nameLabel) || (constraint.secondItem as? NSObject != nil && constraint.secondItem as! NSObject == self.nameLabel)) {
if (constraint.active && (constraint.firstAttribute == NSLayoutAttribute.Top || constraint.firstAttribute == NSLayoutAttribute.Bottom)) {
removeThese.append(constraint)
}
}
}
self.removeConstraints(removeThese)
let c:NSLayoutConstraint = NSLayoutConstraint(item: self.nameLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.nameLabel.superview, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
self.addConstraint(c);
}
}
}
}
|
mpl-2.0
|
8f8f884f31f9743d49826537b91423c0
| 46.228571 | 256 | 0.61222 | 5.13354 | false | false | false | false |
mercadopago/px-ios
|
MercadoPagoSDK/MercadoPagoSDK/PaymentMethodPlugins/PXPluginNavigationHandler.swift
|
1
|
1531
|
import Foundation
/** :nodoc: */
@objcMembers
open class PXPluginNavigationHandler: NSObject {
private var checkout: MercadoPagoCheckout?
public init(withCheckout: MercadoPagoCheckout) {
self.checkout = withCheckout
}
open func showFailure(message: String, errorDetails: String, retryButtonCallback: (() -> Void)?) {
MercadoPagoCheckoutViewModel.error = MPSDKError(message: message, errorDetail: errorDetails, retry: retryButtonCallback != nil)
checkout?.viewModel.errorCallback = retryButtonCallback
checkout?.executeNextStep()
}
open func next() {
checkout?.executeNextStep()
}
open func nextAndRemoveCurrentScreenFromStack() {
guard let currentViewController = self.checkout?.viewModel.pxNavigationHandler.navigationController.viewControllers.last else {
checkout?.executeNextStep()
return
}
checkout?.executeNextStep()
if let indexOfLastViewController = self.checkout?.viewModel.pxNavigationHandler.navigationController.viewControllers.index(of: currentViewController) {
self.checkout?.viewModel.pxNavigationHandler.navigationController.viewControllers.remove(at: indexOfLastViewController)
}
}
open func cancel() {
checkout?.cancelCheckout()
}
open func showLoading() {
checkout?.viewModel.pxNavigationHandler.presentLoading()
}
open func hideLoading() {
checkout?.viewModel.pxNavigationHandler.dismissLoading()
}
}
|
mit
|
615b3df506d2790781e55797ebb7b6a9
| 32.282609 | 159 | 0.708687 | 5.297578 | false | false | false | false |
butterproject/butter-ios
|
Butter/UI/ViewControllers/TVShowDetailViewController.swift
|
1
|
13720
|
//
// TVShowDetailViewController.swift
// Butter
//
// Created by DjinnGA on 30/09/2015.
// Copyright © 2015 Butter Project. All rights reserved.
//
import UIKit
import FloatRatingView
class TVShowDetailViewController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var seasonsScroller: UIScrollView!
private var seasonTitles: [String]! = [String]()
private var seasonLabels:[Int:UILabel]! = [Int:UILabel]()
private var selectedSeason: Int = 0;
private var indicatorView:UIView!
@IBOutlet weak var fanartImageHeight: NSLayoutConstraint!
@IBOutlet var fanartTopImageView: UIImageView!
@IBOutlet var fanartBottomImageView: UIImageView!
@IBOutlet var itemDetailsLabelView: UILabel!
@IBOutlet var itemSynopsisTextView: UITextView!
@IBOutlet var itemRatingView: FloatRatingView!
@IBOutlet var qualityBtn: UIButton!
@IBOutlet var episodesTable: UITableView!
var showSeasons : [Int:[ButterItem]] = [Int:[ButterItem]]()
var seasonEpisodes : [ButterItem] = [ButterItem]()
var favouriteBtn : UIBarButtonItem!
var watchedBtn : UIBarButtonItem!
var currentItem: ButterItem?
override func viewDidLoad() {
super.viewDidLoad()
episodesTable.tableFooterView = UIView()
seasonsScroller.backgroundColor = UIColor.clearColor()
seasonsScroller.translatesAutoresizingMaskIntoConstraints = false
indicatorView = UIView(frame: CGRectZero)
//Load data onto the view
seasonTitles.append(currentItem!.getProperty("title") as! String)
self.fanartTopImageView.alpha = 0.0
self.fanartBottomImageView.alpha = 0.0
self.itemSynopsisTextView.alpha = 0.0
fillView()
if ((currentItem!.getProperty("description")) == nil) {
TVAPI.sharedInstance.requestShowInfo(currentItem!.getProperty("imdb") as! String!, onCompletion: {
self.fillView()
})
}
// Add Watched and Favourites Buttons
favouriteBtn = UIBarButtonItem(image: getFavoriteButtonImage(), style: .Plain, target: self, action: Selector("toggleFavorite"))
watchedBtn = UIBarButtonItem(image: getWatchedButtonImage(), style: .Plain, target: self, action: Selector("toggleWatched"))
self.navigationItem.setRightBarButtonItems([favouriteBtn, watchedBtn], animated:false)
// Set Paralax Effect on Fanart
let verticalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y",
type: .TiltAlongVerticalAxis)
verticalMotionEffect.minimumRelativeValue = -15
verticalMotionEffect.maximumRelativeValue = 15
let horizontalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x",
type: .TiltAlongHorizontalAxis)
horizontalMotionEffect.minimumRelativeValue = -15
horizontalMotionEffect.maximumRelativeValue = 15
let group = UIMotionEffectGroup()
group.motionEffects = [horizontalMotionEffect, verticalMotionEffect]
fanartTopImageView.addMotionEffect(group)
fanartBottomImageView.addMotionEffect(group)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: Selector("swipeSeason:"))
swipeLeft.direction = .Left
view.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action: Selector("swipeSeason:"))
swipeRight.direction = .Right
view.addGestureRecognizer(swipeRight)
}
override func viewWillAppear(animated: Bool) {
self.navigationController!.navigationBar.setBackgroundImage(UIImage(), forBarMetrics:UIBarMetrics.Default)
self.navigationController!.navigationBar.shadowImage = UIImage()
self.navigationController!.navigationBar.translucent = true
self.navigationController!.view.backgroundColor = UIColor.clearColor()
self.navigationController!.navigationBar.backgroundColor = UIColor.clearColor()
self.navigationController!.navigationBar.tintColor = UIColor.whiteColor()
}
override func viewWillDisappear(animated: Bool) {
self.navigationController!.navigationBar.setBackgroundImage(nil, forBarMetrics:UIBarMetrics.Default)
}
func fillView() {
if let fanArt = currentItem!.getProperty("fanart") as? UIImage {
setFanArt(fanArt)
}
if let description = currentItem!.getProperty("description") as? String {
self.itemSynopsisTextView.text = description
UIView.animateWithDuration(0.2, animations: { () in
self.itemSynopsisTextView.alpha = 1
})
} else {
self.itemSynopsisTextView.text = ""
}
if let rating = currentItem!.getProperty("rating") as? Float {
itemRatingView.rating = rating
}
if let showSeasons = currentItem!.getProperty("seasons") as? [Int:[ButterItem]] {
if self.showSeasons.count == 0 {
self.showSeasons = showSeasons
let sortedSeasons = showSeasons.sort { $0.0 < $1.0 }
for season in sortedSeasons {
let seasonNum: Int = season.0
self.seasonTitles.append("Season \(seasonNum)")
}
}
}
if seasonsScroller.subviews.count <= 3 {
createSeasonsScroller()
}
if(indicatorView.frame == CGRectZero) {
indicatorView.frame = CGRectMake(seasonLabels[-1]!.frame.origin.x-5, 61, seasonLabels[-1]!.intrinsicContentSize().width+10, 3)
indicatorView.backgroundColor = UIColor.whiteColor()
seasonsScroller.addSubview(indicatorView)
}
if let seas = currentItem!.getProperty("seasons") as? Int {
if let yr = currentItem!.getProperty("year") as? String {
if let run = currentItem!.getProperty("runtime") as? Int {
if (seas > 1) {
itemDetailsLabelView.text = "\(seas) Seasons ● \(yr) ● \(run) min."
} else {
itemDetailsLabelView.text = "\(seas) Season ● \(yr) ● \(run) min."
}
}
}
}
}
func setFanArt(image : UIImage) {
self.fanartTopImageView.image = image
let flippedImage: UIImage = UIImage(CGImage: image.CGImage!, scale: image.scale, orientation:UIImageOrientation.DownMirrored)
self.fanartBottomImageView.image = flippedImage
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.fanartTopImageView.alpha = 1
self.fanartBottomImageView.alpha = 1
})
}
func createSeasonsScroller(){
var x , y ,buffer:CGFloat
x=0;y=0;buffer=10
let sortedSeasons = showSeasons.sort { $0.0 < $1.0 }
for var i=0; i < seasonTitles.count; i++ {
var titleLabel:UILabel!
titleLabel=UILabel();
//Label
if (i == 0) {
titleLabel.font = UIFont.boldSystemFontOfSize(22.0)
} else {
titleLabel.font = UIFont.systemFontOfSize(18.0)
}
titleLabel.text = seasonTitles[i] as String //.uppercaseString as String
titleLabel.userInteractionEnabled = true
let lblWidth:CGFloat
lblWidth = titleLabel.intrinsicContentSize().width + 32
titleLabel.frame = CGRectMake(x, 16, lblWidth, 34)
titleLabel.textAlignment = .Left
if (i > 0) {
let season = sortedSeasons[i-1]
titleLabel.tag = season.0//i+1
} else {
titleLabel.tag = -1
}
titleLabel.textColor = UIColor.whiteColor()
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
tap.delegate = self
titleLabel.addGestureRecognizer(tap)
seasonsScroller.addSubview(titleLabel)
seasonLabels[titleLabel.tag] = titleLabel
x+=lblWidth+buffer
}
seasonsScroller.showsHorizontalScrollIndicator=false;
seasonsScroller.backgroundColor = UIColor.clearColor();
seasonsScroller.contentSize = CGSizeMake(x,64)
seasonsScroller.contentInset = UIEdgeInsetsMake(0, 15, 0, 0.0);
seasonsScroller.contentOffset = CGPointMake(-15, y)
seasonsScroller.translatesAutoresizingMaskIntoConstraints = false
}
func handleTap(sender:UIGestureRecognizer){
showSeason(sender.view!.tag)
}
func swipeSeason(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right:
let seasonLeft = findPreviousSeason(selectedSeason)
if seasonLeft != -1 {
if let _ = self.view.viewWithTag(seasonLeft) as? UILabel {
showSeason(seasonLeft)
}
} else {
showSeason(-1)
}
case UISwipeGestureRecognizerDirection.Left:
let seasonRight = findNextSeason(selectedSeason)
if seasonRight != -1 {
if let _ = self.view.viewWithTag(seasonRight) as? UILabel {
showSeason(seasonRight)
}
}
default:
break
}
}
}
func findNextSeason(currentSeasonNr : Int) -> Int {
let orderedSeasons = showSeasons.keys.sort()
for nr in orderedSeasons {
if nr > currentSeasonNr {
return nr
}
}
return -1
}
func findPreviousSeason(currentSeasonNr : Int) -> Int {
let orderedSeasons = showSeasons.keys.sort(>)
for nr in orderedSeasons {
if nr < currentSeasonNr {
return nr
}
}
return -1
}
func showSeason(nr : Int) {
selectedSeason = nr
seasonsScroller.scrollRectToVisible(self.seasonLabels[nr]!.frame, animated: true)
if (selectedSeason > -1) {
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.fanartImageHeight.constant = 120
self.view.layoutIfNeeded()
}, completion: nil)
seasonEpisodes = showSeasons[selectedSeason]!
episodesTable.reloadData()
episodesTable.alpha = 1.0
itemDetailsLabelView.alpha = 0.0
itemSynopsisTextView.alpha = 0.0
itemRatingView.alpha = 0.0
} else {
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.fanartImageHeight.constant = 232
self.view.layoutIfNeeded()
}, completion: nil)
seasonEpisodes = [ButterItem]()
episodesTable.alpha = 0.0
episodesTable.reloadData()
itemDetailsLabelView.alpha = 1.0
itemSynopsisTextView.alpha = 1.0
itemRatingView.alpha = 1.0
}
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.indicatorView.frame = CGRectMake(self.seasonLabels[self.selectedSeason]!.frame.origin.x-5, 61, self.seasonLabels[self.selectedSeason]!.intrinsicContentSize().width+10, 3)
self.indicatorView.backgroundColor = UIColor.whiteColor()
self.seasonsScroller.scrollRectToVisible(self.seasonLabels[self.selectedSeason]!.frame, animated: true)
})
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return seasonEpisodes.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = episodesTable.dequeueReusableCellWithIdentifier("episodeCell") as! PTEpisodeTableViewCell
let num = seasonEpisodes[indexPath.row].getProperty("episode") as! Int
cell.numberLabel!.text = "\(num)"
cell.titleLabel!.text = seasonEpisodes[indexPath.row].getProperty("title") as? String
cell.backgroundColor = UIColor.clearColor()
let blurEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
cell.selectedBackgroundView = blurEffectView
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let episode = seasonEpisodes[indexPath.row]
print(episode.torrents["480p"]!.url)
// Start playing episode
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func getFavoriteButtonImage() -> UIImage? {
var favImage = UIImage(named: "favoritesOff")?.imageWithRenderingMode(.AlwaysOriginal)
if let currentItem = currentItem {
if ShowFavorites.isFavorite(currentItem.getProperty("imdb") as! String) {
favImage = UIImage(named: "favoritesOn")?.imageWithRenderingMode(.AlwaysOriginal)
}
}
return favImage
}
func getWatchedButtonImage() -> UIImage? {
var watchedImage = UIImage(named: "watchedOff")?.imageWithRenderingMode(.AlwaysOriginal)
if let currentItem = currentItem {
if WatchedShows.isWatched(currentItem.getProperty("imdb") as! String) {
watchedImage = UIImage(named: "watchedOn")?.imageWithRenderingMode(.AlwaysOriginal)
}
}
return watchedImage
}
func toggleFavorite() {
if let currentItem = currentItem {
ShowFavorites.toggleFavorite(currentItem.getProperty("imdb") as! String)
favouriteBtn.image = getFavoriteButtonImage()
}
}
func toggleWatched() {
if let currentItem = currentItem {
WatchedShows.toggleWatched(currentItem.getProperty("imdb") as! String)
watchedBtn.image = getWatchedButtonImage()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
gpl-3.0
|
9b0315d5f62e6ad645c6c1312eb614a5
| 34.705729 | 178 | 0.680767 | 4.529567 | false | false | false | false |
hfutrell/BezierKit
|
BezierKit/Library/Path+Projection.swift
|
1
|
5427
|
//
// Path+Project.swift
// BezierKit
//
// Created by Holmes Futrell on 11/23/20.
// Copyright © 2020 Holmes Futrell. All rights reserved.
//
#if canImport(CoreGraphics)
import CoreGraphics
#endif
import Foundation
public extension Path {
private typealias ComponentTuple = (component: PathComponent, index: Int, upperBound: CGFloat)
private typealias Candidate = (point: CGPoint, location: IndexedPathLocation)
private func searchForClosestLocation(to point: CGPoint, maximumDistance: CGFloat, requireBest: Bool) -> (point: CGPoint, location: IndexedPathLocation)? {
// sort the components by proximity to avoid searching distant components later on
let tuples: [ComponentTuple] = self.components.enumerated().map { i, component in
let boundingBox = component.boundingBox
let upper = boundingBox.upperBoundOfDistance(to: point)
return (component: component, index: i, upperBound: upper)
}.sorted(by: { $0.upperBound < $1.upperBound })
// iterate through each component and search for closest point
var bestSoFar: Candidate?
var maximumDistance = maximumDistance
for next in tuples {
guard let projection = next.component.searchForClosestLocation(to: point,
maximumDistance: maximumDistance,
requireBest: requireBest) else {
continue
}
let projectionDistance = distance(point, projection.point)
assert(projectionDistance <= maximumDistance)
let candidate = (point: projection.point,
location: IndexedPathLocation(componentIndex: next.index,
locationInComponent: projection.location))
maximumDistance = projectionDistance
bestSoFar = candidate
}
// return the best answer
if let best = bestSoFar {
return (point: best.point, location: best.location)
}
return nil
}
func project(_ point: CGPoint) -> (point: CGPoint, location: IndexedPathLocation)? {
return self.searchForClosestLocation(to: point, maximumDistance: .infinity, requireBest: true)
}
func pointIsWithinDistanceOfBoundary(_ point: CGPoint, distance: CGFloat) -> Bool {
return self.searchForClosestLocation(to: point, maximumDistance: distance, requireBest: false) != nil
}
}
public extension PathComponent {
private func anyLocation(in node: BoundingBoxHierarchy.Node) -> IndexedPathComponentLocation {
switch node.type {
case .leaf(let elementIndex):
return IndexedPathComponentLocation(elementIndex: elementIndex, t: 0)
case .internal(let startingElementIndex, _):
return IndexedPathComponentLocation(elementIndex: startingElementIndex, t: 0)
}
}
fileprivate func searchForClosestLocation(to point: CGPoint, maximumDistance: CGFloat, requireBest: Bool) -> (point: CGPoint, location: IndexedPathComponentLocation)? {
var bestSoFar: IndexedPathComponentLocation?
var maximumDistance: CGFloat = maximumDistance
self.bvh.visit { node, _ in
guard requireBest == true || bestSoFar == nil else {
return false // we're done already
}
let boundingBox = node.boundingBox
let lowerBound = boundingBox.lowerBoundOfDistance(to: point)
guard lowerBound <= maximumDistance else {
return false // nothing in this node can be within maximum distance
}
if requireBest == false {
let upperBound = boundingBox.upperBoundOfDistance(to: point)
if upperBound <= maximumDistance {
maximumDistance = upperBound // restrict the search to this new upper bound
bestSoFar = self.anyLocation(in: node)
return false
}
}
if case .leaf(let elementIndex) = node.type {
let curve = self.element(at: elementIndex)
let projection = curve.project(point)
let distanceToCurve = distance(point, projection.point)
if distanceToCurve <= maximumDistance {
maximumDistance = distanceToCurve
bestSoFar = IndexedPathComponentLocation(elementIndex: elementIndex, t: projection.t)
}
}
return true // visit children (if they exist)
}
if let bestSoFar = bestSoFar {
return (point: self.point(at: bestSoFar), location: bestSoFar)
}
return nil
}
func project(_ point: CGPoint) -> (point: CGPoint, location: IndexedPathComponentLocation) {
guard let result = self.searchForClosestLocation(to: point, maximumDistance: .infinity, requireBest: true) else {
assertionFailure("expected non-empty result")
return (point: self.startingPoint, self.startingIndexedLocation)
}
return result
}
func pointIsWithinDistanceOfBoundary(_ point: CGPoint, distance: CGFloat) -> Bool {
return self.searchForClosestLocation(to: point, maximumDistance: distance, requireBest: false) != nil
}
}
|
mit
|
faa98c93af9c868f567974b54a81b3a5
| 47.446429 | 172 | 0.624585 | 5.232401 | false | false | false | false |
dehesa/apple-utilites
|
Sources/common/swift/Optional.swift
|
2
|
2109
|
public extension Optional {
/// Executes the side-effect given as a parameter.
/// - parameter transform: Closure executing a side-effect (it will not modify the value wrapped in the optional). This closure will get executed *if* the optional is not `nil`.
/// - parameter wrapped: Value wrapped within the optional.
public func on(_ transform: (_ wrapped: Wrapped)->Void) {
guard case .some(let value) = self else { return }
transform(value)
}
}
public extension Optional where Wrapped: MutableCollection & RandomAccessCollection & RangeReplaceableCollection, Wrapped.Iterator.Element: Comparable {
/// Appends an element to an optional collection. If the optional is `nil`, a collection is created holding the given element.
///
/// Before addition, the array is checked for element existance. If it already exists, no operation is performed.
/// - parameter newElement: Element to be added to the collection wrapped within the optional.
public mutating func append(_ newElement: Wrapped.Iterator.Element) {
guard case .some(var result) = self else {
self = .some(Wrapped([newElement]))
return
}
guard !result.contains(newElement) else { return }
result.append(newElement)
self = .some(result)
}
/// Appends the elements of an optional collection to another optional collection. If the optional is `nil` and the given collection is not `nil`, a collection is created holding the given elements.
///
/// Before addition the array is checked for element existance. If it already exists, no operation is performed.
/// - parameter newElements: Collection to be added to the collection wrapped within the optional.
public mutating func append(_ newElements: Wrapped) {
guard case .some(var result) = self else {
return self = newElements
}
for element in newElements {
guard !result.contains(element) else { continue }
result.append(element)
}
self = result
}
}
|
mit
|
26234bc45e05aaa099767df669077d5c
| 48.046512 | 202 | 0.673779 | 5.009501 | false | false | false | false |
algoliareadmebot/algoliasearch-client-swift
|
Source/Offline/MirrorSettings.swift
|
1
|
2886
|
//
// Copyright (c) 2016 Algolia
// http://www.algolia.com/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
internal class MirrorSettings {
var lastSyncDate: Date?
var queries : [DataSelectionQuery] = []
var queriesModificationDate: Date?
/// Serialize the settings to a plist and save them to disk.
func save(_ filePath: String) {
var queriesJson: [JSONObject] = []
for query in queries {
queriesJson.append([
"query": query.query.build(),
"maxObjects": query.maxObjects
])
}
var settings: [String: Any] = [
"queries": queriesJson
]
settings["lastSyncDate"] = lastSyncDate
settings["queriesModificationDate"] = queriesModificationDate
(settings as NSDictionary).write(toFile: filePath, atomically: true)
}
/// Read a plist from the disk and parse the settings from it.
func load(_ filePath: String) {
self.queries.removeAll()
if let settings = NSDictionary(contentsOfFile: filePath) {
if let lastSyncDate = settings["lastSyncDate"] as? Date {
self.lastSyncDate = lastSyncDate
}
if let queriesJson = settings["queries"] as? [JSONObject] {
for queryJson in queriesJson {
if let queryString = queryJson["query"] as? String, let maxObjects = queryJson["maxObjects"] as? Int {
self.queries.append(DataSelectionQuery(query: Query.parse(queryString), maxObjects: maxObjects))
}
}
}
if let queriesModificationDate = settings["queriesModificationDate"] as? Date {
self.queriesModificationDate = queriesModificationDate
}
}
}
}
|
mit
|
682b2b85d5c8b41aadd965cc0eb1abf0
| 40.826087 | 122 | 0.650728 | 4.770248 | false | false | false | false |
malcommac/SwiftDate
|
Sources/SwiftDate/DateInRegion/DateInRegion.swift
|
2
|
7356
|
//
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import Foundation
public struct DateInRegion: DateRepresentable, Decodable, Encodable, CustomStringConvertible, Comparable, Hashable {
/// Absolute date represented. This date is not associated with any timezone or calendar
/// but represent the absolute number of seconds since Jan 1, 2001 at 00:00:00 UTC.
public internal(set) var date: Date
/// Associated region which define where the date is represented into the world.
public let region: Region
/// Formatter used to transform this object in a string. By default is `nil` because SwiftDate
/// uses the thread shared formatter in order to avoid expensive init of the `DateFormatter` object.
/// However, if you need of a custom behaviour you can set a valid value.
public var customFormatter: DateFormatter?
/// Extract date components by taking care of the region in which the date is expressed.
public var dateComponents: DateComponents {
return region.calendar.dateComponents(DateComponents.allComponentsSet, from: date)
}
/// Description of the date
public var description: String {
let absISODate = DateFormatter.sharedFormatter(forRegion: Region.UTC).string(from: date)
let representedDate = formatter(format: DateFormats.iso8601).string(from: date)
return "{abs_date='\(absISODate)', rep_date='\(representedDate)', region=\(region.description)"
}
/// The interval between the date value and 00:00:00 UTC on 1 January 1970.
public var timeIntervalSince1970: TimeInterval {
return date.timeIntervalSince1970
}
/// Initialize with an absolute date and represent it into given geographic region.
///
/// - Parameters:
/// - date: absolute date to represent.
/// - region: region in which the date is represented. If ignored `defaultRegion` is used instead.
public init(_ date: Date = Date(), region: Region = SwiftDate.defaultRegion) {
self.date = date
self.region = region
}
/// Initialize a new `DateInRegion` by parsing given string.
/// If you know the format of the string you should pass it in order to speed up the parsing process.
/// If you don't know the format leave it `nil` and parse is done between all formats in `DateFormats.builtInAutoFormats`
/// and the ordered list you can provide in `SwiftDate.autoParseFormats` (with attempt priority set on your list).
///
/// - Parameters:
/// - string: string with the date.
/// - format: format of the date.
/// - region: region in which the date is expressed.
public init?(_ string: String, format: String? = nil, region: Region = SwiftDate.defaultRegion) {
guard let date = DateFormats.parse(string: string,
format: format,
region: region) else {
return nil // failed to parse date
}
self.date = date
self.region = region
}
/// Initialize a new `DateInRegion` by parsing given string with the ordered list of passed formats.
/// If you know the format of the string you should pass it in order to speed up the parsing process.
/// If you don't know the format leave it `nil` and parse is done between all formats in `DateFormats.builtInAutoFormats`
/// and the ordered list you can provide in `SwiftDate.autoParseFormats` (with attempt priority set on your list).
///
/// - Parameters:
/// - string: string with the date.
/// - formats: ordered list of formats to use.
/// - region: region in which the date is expressed.
public init?(_ string: String, formats: [String]?, region: Region = SwiftDate.defaultRegion) {
guard let date = DateFormats.parse(string: string,
formats: (formats ?? SwiftDate.autoFormats),
region: region) else {
return nil // failed to parse date
}
self.date = date
self.region = region
}
/// Initialize a new date from the number of seconds passed since Unix Epoch.
///
/// - Parameters:
/// - interval: seconds since Unix Epoch.
/// - region: the region in which the date must be expressed, `nil` uses the default region at UTC timezone
public init(seconds interval: TimeInterval, region: Region = Region.UTC) {
self.date = Date(timeIntervalSince1970: interval)
self.region = region
}
/// Initialize a new date corresponding to the number of milliseconds since the Unix Epoch.
///
/// - Parameters:
/// - interval: seconds since the Unix Epoch timestamp.
/// - region: region in which the date must be expressed, `nil` uses the default region at UTC timezone
public init(milliseconds interval: Int, region: Region = Region.UTC) {
self.date = Date(timeIntervalSince1970: TimeInterval(interval) / 1000)
self.region = region
}
/// Initialize a new date with the opportunity to configure single date components via builder pattern.
/// Date is therfore expressed in passed region (`DateComponents`'s `timezone`,`calendar` and `locale` are ignored
/// and overwritten by the region if not `nil`).
///
/// - Parameters:
/// - configuration: configuration callback
/// - region: region in which the date is expressed.
/// Ignore to use `SwiftDate.defaultRegion`, `nil` to use `DateComponents` data.
public init?(components configuration: ((inout DateComponents) -> Void), region: Region? = SwiftDate.defaultRegion) {
var components = DateComponents()
configuration(&components)
let r = (region ?? Region(fromDateComponents: components))
guard let date = r.calendar.date(from: components) else {
return nil
}
self.date = date
self.region = r
}
/// Initialize a new date with given components.
///
/// - Parameters:
/// - components: components of the date.
/// - region: region in which the date is expressed.
/// Ignore to use `SwiftDate.defaultRegion`, `nil` to use `DateComponents` data.
public init?(components: DateComponents, region: Region?) {
let r = (region ?? Region(fromDateComponents: components))
guard let date = r.calendar.date(from: components) else {
return nil
}
self.date = date
self.region = r
}
/// Initialize a new date with given components.
public init(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0, nanosecond: Int = 0, region: Region = SwiftDate.defaultRegion) {
var components = DateComponents()
components.year = year
components.month = month
components.day = day
components.hour = hour
components.minute = minute
components.second = second
components.nanosecond = nanosecond
components.timeZone = region.timeZone
components.calendar = region.calendar
self.date = region.calendar.date(from: components)!
self.region = region
}
/// Return a date in the distant past.
///
/// - Returns: Date instance.
public static func past() -> DateInRegion {
DateInRegion(Date.distantPast, region: SwiftDate.defaultRegion)
}
/// Return a date in the distant future.
///
/// - Returns: Date instance.
public static func future() -> DateInRegion {
DateInRegion(Date.distantFuture, region: SwiftDate.defaultRegion)
}
// MARK: - Codable Support
enum CodingKeys: String, CodingKey {
case date
case region
}
}
|
mit
|
dd3aed67434af9a1433a418938d83837
| 38.756757 | 159 | 0.712984 | 3.967098 | false | false | false | false |
artursDerkintis/YouTube
|
YouTube/SubscriptionsController.swift
|
1
|
6062
|
//
// SubscriptionsController.swift
// YouTube
//
// Created by Arturs Derkintis on 1/25/16.
// Copyright © 2016 Starfly. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
class SubscriptionsController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var subscriptions : [Subscription]? {
didSet{
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.collectionView.reloadData()
}
}
}
var browserDelegate : BrowserDelegate?
var collectionView : UICollectionView!
var bigCollectionViewLayout = UICollectionViewFlowLayout()
var smallCollectionViewLayout = UICollectionViewFlowLayout()
var activityInd: NVActivityIndicatorView!
let subs = SubscriptionsProvider()
override func viewDidLoad() {
super.viewDidLoad()
bigCollectionViewLayout.itemSize = CGSize(width: 100, height: 100)
bigCollectionViewLayout.minimumLineSpacing = 40
smallCollectionViewLayout.itemSize = CGSize(width: 60, height: 60)
smallCollectionViewLayout.minimumLineSpacing = 40
collectionView = UICollectionView(frame: .zero, collectionViewLayout: bigCollectionViewLayout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(SubscriptionsCell.self, forCellWithReuseIdentifier: "Subs")
collectionView.backgroundColor = .clearColor()
collectionView.showsVerticalScrollIndicator = false
view.addSubview(collectionView)
collectionView.snp_makeConstraints { (make) -> Void in
make.top.left.right.bottom.equalTo(0)
}
collectionView.contentInset = UIEdgeInsetsMake(75, 25, 64, 25)
UserHandler.sharedInstance.addObserver(self, forKeyPath: "loaded", options: .New, context: nil)
activityInd = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), type: .BallSpinFadeLoader, color: .whiteColor(), size: CGSize(width: 30, height: 30))
view.addSubview(activityInd)
activityInd.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(self.view.snp_centerX)
make.centerY.equalTo(self.view.snp_centerY)
}
activityInd.hidesWhenStopped = true
loading = true
NSNotificationCenter.defaultCenter().addObserverForName(subUpdate, object: nil, queue: nil) { (not) -> Void in
delay(6, closure: { () -> () in
self.getChannelsInitially()
})
}
getChannelsInitially()
delay(0.4) { () -> () in
self.browserDelegate?.setOwnInfo()
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
UIView.animateWithDuration(0.3) { () -> Void in
self.collectionView.contentInset = UIEdgeInsetsMake(75, self.view.frame.width * 0.07, 64, self.view.frame.width * 0.07)
}
}
private var loading : Bool = false{
didSet{
loading ? activityInd.startAnimation() : activityInd.stopAnimation()
UIView.animateWithDuration(0.3) { () -> Void in
self.collectionView.alpha = self.loading ? 0.0 : 1.0
}
}
}
func setSmallLayout(){
self.collectionView.performBatchUpdates({ () -> Void in
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.setCollectionViewLayout(self.smallCollectionViewLayout, animated: true)
}) { (i) -> Void in
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func getChannelsInitially(){
if let token = UserHandler.sharedInstance.user?.token{
subs.getMySubscribedChannels(token, completion: { (subscriptions) -> Void in
self.subscriptions = subscriptions
self.loading = false
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let sub = subscriptions?[indexPath.row]{
browserDelegate?.loadSubscription(sub.channelId!)
collectionView.cellForItemAtIndexPath(indexPath)?.performFadeAnimation()
delay(0.3, closure: { () -> () in
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
})
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Subs", forIndexPath: indexPath) as! SubscriptionsCell
if let sub = subscriptions?[indexPath.row]{
cell.channelTitleLabel.text = sub.title
ImageDownloader.sharedInstance.getImageAtURL(sub.thumbnail, completion: { (image) -> Void in
cell.thumbnailImage.image = image
})
if let newCount = sub.newItemCount where Int(newCount) > 0{
cell.newItemsWarningView.hidden = false
cell.circleView.hidden = false
cell.newItemsWarningLabel.text = Int(newCount) < 100 ? newCount : "99+"
}else{
cell.circleView.hidden = true
cell.newItemsWarningView.hidden = true
}
}else{
cell.channelTitleLabel.text = ""
cell.newItemsWarningView.hidden = true
cell.circleView.hidden = true
cell.thumbnailImage.image = nil
}
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return subscriptions?.count ?? 0
}
}
|
mit
|
89325d9786c3343501748c2dcefd3d44
| 38.875 | 179 | 0.637684 | 5.330695 | false | false | false | false |
LipliStyle/Liplis-iOS
|
Liplis/CtvCellMenuSite.swift
|
1
|
3003
|
//
// CtvCellMenuSite.swift
// Liplis
//
//設定メニュー画面 要素 サイト
//
//アップデート履歴
// 2015/05/04 ver0.1.0 作成
// 2015/05/09 ver1.0.0 リリース
// 2015/05/16 ver1.4.0 リファクタリング
//
// Created by sachin on 2015/05/04.
// Copyright (c) 2015年 sachin. All rights reserved.
//
import UIKit
class CtvCellMenuSite : UITableViewCell
{
///=============================
///カスタムセル要素
internal var parView : ViewSettingMenu!
///=============================
///カスタムセル要素
internal var lblTitle = UILabel();
internal var btnHelp = UIButton();
///=============================
///レイアウト情報
internal var viewWidth : CGFloat! = 0
//============================================================
//
//初期化処理
//
//============================================================
internal override init(style: UITableViewCellStyle, reuseIdentifier: String!)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.lblTitle = UILabel(frame: CGRectMake(10, 23, 300, 15));
self.lblTitle.text = "LipliStyleのサイトを内部ブラウザで開きます。";
self.lblTitle.font = UIFont.systemFontOfSize(15)
self.lblTitle.numberOfLines = 2
self.addSubview(lblTitle);
//ボタン
self.btnHelp = UIButton()
self.btnHelp.titleLabel?.font = UIFont.systemFontOfSize(16)
self.btnHelp.frame = CGRectMake(0,5,40,48)
self.btnHelp.layer.masksToBounds = true
self.btnHelp.setTitle("Liplis サイト", forState: UIControlState.Normal)
self.btnHelp.addTarget(self, action: "onClick:", forControlEvents: .TouchDown)
self.btnHelp.layer.cornerRadius = 3.0
self.btnHelp.backgroundColor = UIColor.hexStr("DF7401", alpha: 255)
self.addSubview(btnHelp)
}
/*
ビューを設定する
*/
internal func setView(parView : ViewSettingMenu)
{
self.parView = parView
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
/*
要素の位置を調整する
*/
internal func setSize(viewWidth : CGFloat)
{
self.viewWidth = viewWidth
let locationX : CGFloat = CGFloat(viewWidth - viewWidth/4 - 5)
self.btnHelp.frame = CGRectMake(locationX, 5,viewWidth/4,60)
self.lblTitle.frame = CGRectMake(10, 5,viewWidth * 3/4 - 20,50)
}
//============================================================
//
//イベントハンドラ
//
//============================================================
/*
スイッチ選択
*/
internal func onClick(sender: UIButton) {
self.parView.app.activityWeb.url = NSURL(string: LiplisDefine.SITE_LIPLISTYLE)!
self.parView.tabBarController?.selectedIndex=4
}
}
|
mit
|
4cf84db9084d41426f8c319dc5e9a03b
| 27.204082 | 87 | 0.535288 | 4.087278 | false | false | false | false |
argon/mas
|
MasKit/Commands/Purchase.swift
|
1
|
1884
|
//
// Purchase.swift
// mas-cli
//
// Created by Jakob Rieck on 24/10/2017.
// Copyright (c) 2017 Jakob Rieck. All rights reserved.
//
import Commandant
import CommerceKit
public struct PurchaseCommand: CommandProtocol {
public typealias Options = PurchaseOptions
public let verb = "purchase"
public let function = "Purchase and download free apps from the Mac App Store"
private let appLibrary: AppLibrary
/// Public initializer.
public init() {
self.init(appLibrary: MasAppLibrary())
}
/// Internal initializer.
/// - Parameter appLibrary: AppLibrary manager.
init(appLibrary: AppLibrary = MasAppLibrary()) {
self.appLibrary = appLibrary
}
/// Runs the command.
public func run(_ options: Options) -> Result<(), MASError> {
// Try to download applications with given identifiers and collect results
let downloadResults = options.appIds.compactMap { (appId) -> MASError? in
if let product = appLibrary.installedApp(forId: appId) {
printWarning("\(product.appName) has already been purchased.")
return nil
}
return download(appId, purchase: true)
}
switch downloadResults.count {
case 0:
return .success(())
case 1:
return .failure(downloadResults[0])
default:
return .failure(.downloadFailed(error: nil))
}
}
}
public struct PurchaseOptions: OptionsProtocol {
let appIds: [UInt64]
public static func create(_ appIds: [Int]) -> PurchaseOptions {
return PurchaseOptions(appIds: appIds.map { UInt64($0) })
}
public static func evaluate(_ mode: CommandMode) -> Result<PurchaseOptions, CommandantError<MASError>> {
return create
<*> mode <| Argument(usage: "app ID(s) to install")
}
}
|
mit
|
92fd30d1e14b2d5dc14333af146a495c
| 28.4375 | 108 | 0.630042 | 4.453901 | false | false | false | false |
allting/TwitterPIP
|
TwitterPIP/TweetStringTransformer.swift
|
1
|
2404
|
//
// TweetStringTransformer.swift
// TwitterPIP
//
// Created by kkr on 24/06/2017.
// Copyright © 2017 allting. All rights reserved.
//
import Cocoa
class TweetStringTransformer: ValueTransformer {
override class func transformedValueClass() -> AnyClass {
return NSAttributedString.self
}
override class func allowsReverseTransformation() -> Bool {
return true
}
override func transformedValue(_ value: Any?) -> Any? {
guard let string = value as? String else { return nil }
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .left
paragraphStyle.lineHeightMultiple = 0
paragraphStyle.lineSpacing = 3
let attributes: [String: Any] = [NSFontAttributeName: NSFont.systemFont(ofSize: 13.0),
NSForegroundColorAttributeName: NSColor.darkGray,
NSParagraphStyleAttributeName: paragraphStyle]
let attributedString = NSMutableAttributedString.init(string: string, attributes: attributes)
let detector = try! NSDataDetector.init(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: string, options: [], range: NSRange(location:0, length:string.utf16.count))
for match in matches {
let url = (string as NSString).substring(with: match.range)
let attributes : [String : Any] = ["CUSTOM": url,
NSFontAttributeName: NSFont.systemFont(ofSize: 13.0),
NSForegroundColorAttributeName: NSColor.darkGray,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
NSParagraphStyleAttributeName: paragraphStyle,
NSCursorAttributeName: NSCursor.pointingHand()]
attributedString.setAttributes(attributes, range:match.range)
}
return attributedString
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let attr = value as? NSAttributedString else { return nil }
return attr.string
}
}
|
mit
|
119b728d02bdccfc2f50c6fc12de52a1
| 41.157895 | 118 | 0.600916 | 6.193299 | false | false | false | false |
VanHack/binners-project-ios
|
ios-binners-project/BPLoginManager.swift
|
1
|
7168
|
//
// BPLoginManager.swift
// ios-binners-project
//
// Created by Matheus Ruschel on 1/29/16.
// Copyright © 2016 Rodrigo de Souza Reis. All rights reserved.
import Foundation
import TwitterKit
import AFNetworking
import FBSDKLoginKit
import FBSDKCoreKit
import FBSDKShareKit
typealias OnSucessUserBlock = (BPUser) -> Void
class BPLoginManager {
var authBinners:String?
var authGoogle:String?
var authTwitter:String?
var authSecretTwitter:String?
let facebookPermissions = ["public_profile", "email"]
static let sharedInstance = BPLoginManager()
func authenticateFBUserOnBinnersServer(
_ fbToken:String,
onSuccess:@escaping OnSucessUserBlock,
onFailure:OnFailureBlock?) {
if let finalUrl = URL(binnersPath: .facebook(accessToken: fbToken)) {
BPServerRequestManager.sharedInstance.execute(
.get,
url: finalUrl,
manager: AFHTTPSessionManager(),
param: nil,
onSuccess: {
object in
do {
try BPUser.sharedInstance.initialize(object)
onSuccess(BPUser.sharedInstance)
} catch let error {
onFailure?(error as! BPError)
}
},onFailure: onFailure)
}
}
func authenticateUserOnFBAndBinnersServer(
_ onSuccess: @escaping OnSucessUserBlock, onFailure: OnFailureBlock?) {
let fbloginManager = FBSDKLoginManager()
fbloginManager.logIn(
withReadPermissions: facebookPermissions,
handler: { (result: FBSDKLoginManagerLoginResult?, error: Error?) -> Void in
if error != nil {
// Process error
self.removeFbData()
onFailure?(BPError.serverError(error!))
} else if result!.isCancelled {
self.removeFbData()
} else {
//Success
if result!.grantedPermissions.contains("email") &&
result!.grantedPermissions.contains("public_profile") {
if let fbToken = FBSDKAccessToken.current().tokenString {
self.authenticateFBUserOnBinnersServer(fbToken,onSuccess: onSuccess,onFailure: onFailure)
}
} else {
onFailure?(BPError.fbPublicProfileNotProvided)
}
}
})
}
func removeFbData() {
let fbManager = FBSDKLoginManager()
fbManager.logOut()
FBSDKAccessToken.setCurrent(nil)
}
func authenticateGoogleUserOnBinnersServer(
_ onSuccess:@escaping OnSucessUserBlock,onFailure:OnFailureBlock?) throws {
guard let auth = authGoogle else {
throw BPError.googleAuthMissing
}
if let finalUrl = URL(binnersPath: .google(accessToken: auth)) {
BPServerRequestManager.sharedInstance.execute(
.get,
url: finalUrl,
manager: AFHTTPSessionManager(),
param: nil,
onSuccess: {
object in
do {
try BPUser.sharedInstance.initialize(object)
onSuccess(BPUser.sharedInstance)
} catch let error {
onFailure?(error as! BPError)
}
}, onFailure: onFailure)
}
}
func authenticateUserOnTwitterAndBinnersServer(_ onSuccess:@escaping OnSucessUserBlock,onFailure:OnFailureBlock?) {
Twitter.sharedInstance().logIn(completion: {
session, error in
if let unwrappedSession = session {
self.authTwitter = unwrappedSession.authToken
self.authSecretTwitter = unwrappedSession.authTokenSecret
do {
try self.authenticateTwitterUserOnBinnersServer(onSuccess,onFailure: onFailure)
} catch {
onFailure?(BPError.twitterAuthMissing)
}
}
})
}
func authenticateTwitterUserOnBinnersServer(_ onSuccess:@escaping OnSucessUserBlock,onFailure:OnFailureBlock?) throws {
guard let auth = authTwitter else {
throw BPError.twitterAuthMissing
}
guard let authSecret = authSecretTwitter else {
throw BPError.twitterAuthMissing
}
if let finalUrl = URL(binnersPath: .twitter(accessToken: auth, accessSecret: authSecret)) {
//TODO: Waiting for the API endpoint for twitter auth
BPServerRequestManager.sharedInstance.execute(
.get,
url: finalUrl,
manager: AFHTTPSessionManager(),
param: nil,
onSuccess: {
object in
do {
try BPUser.sharedInstance.initialize(object)
onSuccess(BPUser.sharedInstance)
} catch let error {
onFailure?(error as! BPError)
}
}, onFailure: onFailure)
print("loggin out for test purposes")
if let session = Twitter.sharedInstance().sessionStore.session() {
Twitter.sharedInstance().sessionStore.logOutUserID(session.userID)
print("logged out")
}
}
}
func makeResidentStandardLogin(
_ email:String,
password:String,
onSuccess:@escaping OnSucessUserBlock,
onFailure:OnFailureBlock?) {
if let finalUrl = URL(binnersPath: .standardLogin) {
let param = ["email":email,"password":password] as AnyObject
BPServerRequestManager.sharedInstance.execute(
.post,
url: finalUrl,
manager: AFHTTPSessionManager(),
param: param,
onSuccess: {
object in
do {
try BPUser.sharedInstance.initialize(object)
onSuccess(BPUser.sharedInstance)
} catch let error {
onFailure?(error as! BPError)
}
}, onFailure: {
error in
onFailure?(error)
})
}
}
}
|
mit
|
84dd362e404513c045a5f9e4878d7d75
| 31.283784 | 123 | 0.493791 | 6.205195 | false | false | false | false |
adrfer/swift
|
test/DebugInfo/if-branchlocations.swift
|
14
|
1060
|
// RUN: %target-swift-frontend %s -emit-sil -emit-verbose-sil -g -o - | FileCheck %s
class NSURL {}
class NSPathControlItem {
var URL: NSURL?
}
class NSPathControl {
var clickedPathItem: NSPathControlItem?;
}
class AppDelegate {
func LogStr(message: String) {
}
func componentClicked(sender: AnyObject)
{
if let control = sender as? NSPathControl
{
LogStr( "Got a path control" )
if let item = control.clickedPathItem
{
LogStr( "Got an NSPathControlItem" )
// Verify that the branch's location is >= the cleanup's location.
// ( The implicit false block of the conditional
// below inherits the location from the condition. )
// CHECK: br{{.*}}line:[[@LINE+1]]
if let url = item.URL
{
LogStr( "There is a url" )
}
// Verify that the branch's location is >= the cleanup's location.
// CHECK: strong_release{{.*}}$NSPathControlItem{{.*}}line:[[@LINE+2]]
// CHECK-NEXT: br{{.*}}line:[[@LINE+1]]
}
}
}
}
|
apache-2.0
|
adcb7dd3287f11b1fc036f07a5e8d28c
| 25.5 | 84 | 0.590566 | 3.882784 | false | false | false | false |
mrdepth/Neocom
|
Legacy/Neocom/Neocom/Image.swift
|
2
|
641
|
//
// Image.swift
// Neocom
//
// Created by Artem Shimanski on 9/28/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
struct Image: Hashable {
var value: UIImage
var identifier: AnyHashable
var hashValue: Int {
return identifier.hashValue
}
static func == (lhs: Image, rhs: Image) -> Bool {
return lhs.identifier == rhs.identifier
}
init?(_ icon: SDEEveIcon?) {
guard let icon = icon else {return nil}
guard let image = icon.image?.image else {return nil}
self.value = image
identifier = icon.objectID
}
init(_ image: UIImage) {
value = image
identifier = image
}
}
|
lgpl-2.1
|
f7da3c8ba5c42072eb6156b4bb285968
| 17.823529 | 58 | 0.671875 | 3.333333 | false | false | false | false |
machelix/Cheetah
|
Cheetah/Calculations.swift
|
1
|
2120
|
//
// CalculateFunctions.swift
// Cheetah
//
// Created by Suguru Namura on 2015/08/19.
// Copyright © 2015年 Suguru Namura.
//
import UIKit
func calculateCGRect(from from: CGRect, to: CGRect, rate: CGFloat, easing: Easing) -> CGRect {
return CGRect(
origin: calculateCGPoint(from: from.origin, to: to.origin, rate: rate, easing: easing),
size: calculateCGSize(from: from.size, to: to.size, rate: rate, easing: easing)
)
}
func calculateCGPoint(from from: CGPoint, to: CGPoint, rate: CGFloat, easing: Easing) -> CGPoint {
return CGPoint(
x: calculateCGFloat(from: from.x, to: to.x, rate: rate, easing: easing),
y: calculateCGFloat(from: from.y, to: to.y, rate: rate, easing: easing)
)
}
func calculateCGSize(from from: CGSize, to: CGSize, rate: CGFloat, easing: Easing) -> CGSize {
return CGSize(
width: calculateCGFloat(from: from.width, to: to.width, rate: rate, easing: easing),
height: calculateCGFloat(from: from.height, to: to.height, rate: rate, easing: easing)
)
}
func calculateCGFloat(from from: CGFloat, to: CGFloat, rate: CGFloat, easing: Easing) -> CGFloat {
return easing(t: rate, b: from, c: to-from)
}
struct RGBA {
var red:CGFloat = 0
var green:CGFloat = 0
var blue:CGFloat = 0
var alpha:CGFloat = 0
static func fromUIColor(color:UIColor) -> RGBA {
var rgba = RGBA()
color.getRed(&rgba.red, green: &rgba.green, blue: &rgba.blue, alpha: &rgba.alpha)
return rgba
}
}
func calculateUIColor(from from: UIColor, to: UIColor, rate: CGFloat, easing: Easing) -> UIColor {
let fromRGBA = RGBA.fromUIColor(from)
let toRGBA = RGBA.fromUIColor(to)
return UIColor(
red: calculateCGFloat(from: fromRGBA.red, to: toRGBA.red, rate: rate, easing: easing),
green: calculateCGFloat(from: fromRGBA.green, to: toRGBA.green, rate: rate, easing: easing),
blue: calculateCGFloat(from: fromRGBA.blue, to: toRGBA.blue, rate: rate, easing: easing),
alpha: calculateCGFloat(from: fromRGBA.alpha, to: toRGBA.alpha, rate: rate, easing: easing)
)
}
|
mit
|
b17d06324c181ef58c40ea25a1c1e8b6
| 36.140351 | 100 | 0.667454 | 3.470492 | false | false | false | false |
honishi/Hakumai
|
Hakumai/Parameter.swift
|
1
|
1789
|
//
// Parameter.swift
// Hakumai
//
// Created by Hiroyuki Onishi on 12/9/14.
// Copyright (c) 2014 Hiroyuki Onishi. All rights reserved.
//
import Foundation
// top level parameters
// http://stackoverflow.com/a/26252377
struct Parameters {
// general
static let browserInUse = "BrowserInUse"
// speech
static let commentSpeechVolume = "CommentSpeechVolume"
static let commentSpeechEnableName = "CommentSpeechEnableName"
static let commentSpeechEnableGift = "CommentSpeechEnableGift"
static let commentSpeechEnableAd = "CommentSpeechEnableAd"
static let commentSpeechVoicevoxSpeaker = "CommentSpeechVoicevoxSpeaker"
// mute
static let enableMuteUserIds = "EnableMuteUserIds"
static let enableMuteWords = "EnableMuteWords"
static let muteUserIds = "MuteUserIds"
static let muteWords = "MuteWords"
// misc
static let lastLaunchedApplicationVersion = "LastLaunchedApplicationVersion"
static let alwaysOnTop = "AlwaysOnTop"
static let commentAnonymously = "CommentAnonymously"
static let fontSize = "FontSize"
static let enableBrowserUrlObservation = "EnableBrowserUrlObservation"
static let enableBrowserTabSelectionSync = "EnableBrowserTabSelectionSync"
static let enableLiveNotification = "EnableLiveNotification"
static let enableEmotionMessage = "EnableEmotionMessage"
static let enableDebugMessage = "EnableDebugMessage"
}
// session management
enum BrowserInUseType: Int {
case chrome = 1001
case safari = 1002
}
// dictionary keys in MuteUserIds array objects
struct MuteUserIdKey {
static let userId = "UserId"
}
// dictionary keys in MuteUserWords array objects
struct MuteUserWordKey {
static let word = "Word"
// static let EnableRegexp = "EnableRegexp"
}
|
mit
|
e47d5837f3ceca266f4d2d1b2605bc66
| 30.385965 | 80 | 0.753494 | 4.321256 | false | false | false | false |
qds-hoi/suracare
|
suracare/suracare/Core/Library/SwiftValidator/Rules/ConfirmRule.swift
|
1
|
1672
|
//
// ConfirmRule.swift
// Validator
//
// Created by Jeff Potter on 3/6/15.
// Copyright (c) 2015 jpotts18. All rights reserved.
//
import Foundation
import UIKit
/**
`ConfirmationRule` is a subclass of Rule that defines how a field that has to be equal
to another field is validated.
*/
public class ConfirmationRule: Rule {
/// parameter confirmField: field to which original text field will be compared to.
private let confirmField: ValidatableField
/// parameter message: String of error message.
private var message : String
/**
Initializes a `ConfirmationRule` object to validate the text of a field that should equal the text of another field.
- parameter confirmField: field to which original field will be compared to.
- parameter message: String of error message.
- returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception.
*/
public init(confirmField: ValidatableField, message : String = "This field does not match"){
self.confirmField = confirmField
self.message = message
}
/**
Used to validate a field.
- parameter value: String to checked for validation.
- returns: A boolean value. True if validation is successful; False if validation fails.
*/
public func validate(value: String) -> Bool {
return confirmField.validationText == value
}
/**
Displays an error message when text field fails validation.
- returns: String of error message.
*/
public func errorMessage() -> String {
return message
}
}
|
mit
|
77b5b91a18be46f69bfdbbdb8456187d
| 31.173077 | 134 | 0.680024 | 4.696629 | false | false | false | false |
khizkhiz/swift
|
validation-test/compiler_crashers_fixed/00193-swift-typebase-gettypevariables.swift
|
1
|
786
|
// RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
[]
}
protocol p {
}
protocol g : p {
}
n j }
}
protocol k {
class func q()
}
class n: k{ class func q {}
func r<e: t, s where j<s> == e.m { func g
k q<n : t> {
q g: n
}
func p<n>() ->(b: T) {
}
f(true as Boolean)
f> {
c(d ())
}
func b(e)-> <d>(() -> d)
d ""
e}
class d {
func b((Any, d)typealias b = b
d> Bool {
e !(f)
[]
}
f
m)
return ""
}
}
class C: B, A {
over }
}
func e<T where T: A, T: B>(t: T) {
t.c()
}
func a<T>() -> (T -> T) -> T {
T, T -> T) ->)func typealias F = Int
func g<T where T.E == F>(f: B<T>) {
}
}
|
apache-2.0
|
39c22826c322346102648bd925cf3975
| 13.830189 | 87 | 0.510178 | 2.448598 | false | false | false | false |
fousa/trackkit
|
Sources/Classes/Parser/NMEA/Parser/GPWPLParser.swift
|
1
|
1359
|
//
// TrackKit
//
// Created by Jelle Vandebeeck on 15/03/16.
//
import CoreLocation
class GPWPLParser: NMEAParsable {
private(set) var line: [String]
private(set) var name: String?
private(set) var time: Date?
private(set) var coordinate: CLLocationCoordinate2D?
private(set) var gpsQuality: GPSQuality?
private(set) var navigationReceiverWarning: NavigationReceiverWarning?
private(set) var numberOfSatellites: Int?
private(set) var horizontalDilutionOfPrecision: Double?
private(set) var elevation: Double?
private(set) var heightOfGeoid: Double?
private(set) var timeSinceLastUpdate: Double?
private(set) var speed: Double?
private(set) var trackAngle: Double?
private(set) var magneticVariation: Double?
private(set) var stationId: String?
required init?(line: [String]) {
self.line = line
// Parse the coordinate and invalidate the point when not available.
guard
let latitude = parseCoordinateValue(from: self[1], direction: self[2], offset: 2),
let longitude = parseCoordinateValue(from: self[3], direction: self[4], offset: 3) else {
return nil
}
coordinate = CLLocationCoordinate2DMake(latitude, longitude)
// Parse the main properties.
name = self[5]?.checksumEscapedString
}
}
|
mit
|
350e3edafb9d1319f2d8ab25daebe7b4
| 30.604651 | 101 | 0.681383 | 4.181538 | false | false | false | false |
nodes-vapor/admin-panel-provider
|
Sources/AdminPanelProvider/Tags/Leaf/WYSIWYG.swift
|
1
|
1509
|
import Leaf
import Vapor
public final class WYSIWYG: BasicTag {
public init(){}
public let name = "form:wysiwyg"
public func run(arguments: ArgumentList) throws -> Node? {
guard
arguments.count >= 2,
case .variable(let fieldsetPathNodes, value: let fieldset) = arguments.list[0],
let fieldsetPath = fieldsetPathNodes.last
else {
throw Abort(.internalServerError, reason: "FormDateGroup parse error, expecting: #form:dategroup(\"name\", \"default\", fieldset)")
}
// Retrieve input value, value from fieldset else passed default value
let inputValue = fieldset?["value"]?.string ?? arguments[1]?.string ?? ""
let label = fieldset?["label"]?.string
let errors = fieldset?["errors"]?.array
let hasErrors = !(errors?.isEmpty ?? true)
var template: [String] = [
"<div class=\"form-group action-wrapper\(hasErrors ? " has-error" : "")\">",
"<textarea class=\"textarea form-control\" id='\(fieldsetPath)-ta' name=\"\(fieldsetPath)\" value=\"\(inputValue)\">",
"</textarea>",
"</div><script>",
"$(function() { $('#\(fieldsetPath)-ta').wysihtml5(); });",
"</script>"
]
if let label = label {
template.insert("<label class=\"control-label\" for=\"\(fieldsetPath)\">\(label)</label>", at: 1)
}
return .bytes(template.joined(separator: "\n").bytes)
}
}
|
mit
|
7be334ef8d6997d455040d07f92bb7a2
| 36.725 | 147 | 0.567263 | 4.262712 | false | false | false | false |
tptee/Parsimmon
|
Parsimmon/DecisionTree.swift
|
1
|
7936
|
// DecisionTree.swift
//
// Copyright (c) 2015 Ayaka Nonaka
//
// 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 struct Datum {
public let featureValues: (Bit, Bit)
public let classification: Bit
public init(featureValues: (Bit, Bit), classification: Bit) {
self.featureValues = featureValues
self.classification = classification
}
public func featureValueAtPosition(position: Bit) -> Bit {
if position.rawValue == 0 {
return self.featureValues.0
} else {
return self.featureValues.1
}
}
}
public class Node<T> {
public var leftChild: Node<T>?
public var rightChild: Node<T>?
public var value: T
init(value: T) {
self.value = value
}
}
public class DecisionTree {
public var root: Node<Bit>?
public var maxDepth: Int = 5
private let featureNames: (String, String)
private let classificationNames: (String, String)
private var data = [Datum]()
public init(featureNames: (String, String), classificationNames: (String, String)) {
self.featureNames = featureNames
self.classificationNames = classificationNames
}
/**
Adds a data point to the decision tree.
@param datum A data point
*/
public func addSample(datum: Datum) {
self.data.append(datum)
}
/**
Builds the decision tree based on the data it has.
*/
public func build() {
let features = [ Bit.Zero, Bit.One ]
self.root = self.decisionTree(self.data, remainingFeatures: features, maxDepth: self.maxDepth)
}
public func classify(sample: [Int]) -> String? {
var node = self.root
while (node != nil) {
let unwrappedNode = node!
if let leftChild = unwrappedNode.leftChild {
let pathToTake = sample[unwrappedNode.value.rawValue]
if pathToTake == 0 {
node = unwrappedNode.leftChild
} else {
node = unwrappedNode.rightChild
}
} else if unwrappedNode.value.rawValue == 0 {
return self.classificationNames.0
} else if unwrappedNode.value.rawValue == 1 {
return self.classificationNames.1
}
}
return nil
}
private func decisionTree(data: [Datum], remainingFeatures: [Bit], maxDepth: Int) -> Node<Bit> {
let tree = Node<Bit>(value: Bit.Zero)
if data.first == nil {
return tree
}
// Check for the two base cases.
let firstDatum = data.first!
let firstDatumFeatureValues = [ firstDatum.featureValues.0, firstDatum.featureValues.1 ]
let firstDatumClassification = firstDatum.classification
var allSameClassification = true
var allSameFeatureValues = true
var count = 0
for datum in data {
let datumClassification = datum.classification
if firstDatumClassification != datumClassification {
allSameClassification = false
}
let datumFeatureValues = [ datum.featureValues.0, datum.featureValues.1 ]
if firstDatumFeatureValues != datumFeatureValues {
allSameFeatureValues = false
}
count += datumClassification.rawValue
}
if allSameClassification == true {
tree.value = firstDatum.classification
} else if allSameFeatureValues == true || maxDepth == 0 {
tree.value = count > (data.count / 2) ? Bit.One : Bit.Zero
} else {
// Find the best feature to split on and recurse.
var maxInformationGain = -Float.infinity
var bestFeature = Bit.Zero
for feature in remainingFeatures {
let informationGain = self.informationGain(feature, data: data)
if informationGain >= maxInformationGain {
maxInformationGain = informationGain
bestFeature = feature
}
}
let splitData = self.splitData(data, onFeature: bestFeature)
var newRemainingFeatures = remainingFeatures
if let bestFeatureIndex = find(newRemainingFeatures, bestFeature) {
newRemainingFeatures.removeAtIndex(bestFeatureIndex)
tree.leftChild = self.decisionTree(splitData.0, remainingFeatures: newRemainingFeatures, maxDepth: maxDepth - 1)
tree.rightChild = self.decisionTree(splitData.1, remainingFeatures: newRemainingFeatures, maxDepth: maxDepth - 1)
tree.value = bestFeature
}
}
return tree
}
private func splitData(data: [Datum], onFeature: Bit) -> ([Datum], [Datum]) {
var first = [Datum]()
var second = [Datum]()
for datum in data {
if datum.featureValueAtPosition(onFeature).rawValue == 0 {
first.append(datum)
} else {
second.append(datum)
}
}
return (first, second)
}
// MARK: Entropy
private func informationGain(feature: Bit, data: [Datum]) -> Float {
return self.HY(data) - self.HY(data, X: feature)
}
private func HY(data: [Datum]) -> Float {
let pY0: Float = self.pY(data, Y: 0)
let pY1 = 1.0 - pY0
return -1.0 * (pY0 * log2(pY0) + pY1 * log2(pY1))
}
private func HY(data: [Datum], X: Bit) -> Float {
var result = Float(0.0)
for x in [0, 1] {
for y in [0, 1] {
result -= self.pX(data, X: x, Y: y, feature: X) * log2(self.pY(data, Y: y, X: x, feature: X))
}
}
return result
}
private func pY(data: [Datum], Y: Int) -> Float {
var count = 0
for datum in data {
if datum.classification.rawValue == Y {
count++
}
}
return Float(count) / Float(data.count)
}
private func pY(data: [Datum], Y: Int, X: Int, feature: Bit) -> Float {
var yCount = 0
var xCount = 0
for datum in data {
if datum.featureValueAtPosition(feature).rawValue == X {
xCount++
if datum.classification.rawValue == Y {
yCount++
}
}
}
return Float(yCount) / Float(xCount)
}
private func pX(data: [Datum], X: Int, Y: Int, feature: Bit) -> Float {
var count = 0
for datum in data {
if datum.classification.rawValue == Y && datum.featureValueAtPosition(feature).rawValue == X {
count++
}
}
return Float(count) / Float(data.count)
}
}
|
mit
|
6a0e4410c0de4f0e421e698932be18d8
| 34.271111 | 129 | 0.584677 | 4.514221 | false | false | false | false |
tutsplus/watchos-2-from-scratch
|
Stocks WatchKit Extension/YQL.swift
|
1
|
1159
|
//
// YQL.swift
// Stocks
//
// Created by Derek Jensen on 11/19/15.
// Copyright © 2015 Derek Jensen. All rights reserved.
//
import Foundation
public class YQL
{
private class var prefix: String {
return "http://query.yahooapis.com/v1/public/yql?q="
}
private class var suffix: String {
return "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
}
public class func query(statement: String) -> NSDictionary
{
let query = "\(prefix)\(statement.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)\(suffix)"
let jsonData = (try? String(contentsOfURL: NSURL(string: query)!, encoding: NSUTF8StringEncoding))?.dataUsingEncoding(NSUTF8StringEncoding)
let result = { _ -> NSDictionary in
if let data = jsonData
{
return (try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
}
return NSDictionary()
}()
return result;
}
}
|
bsd-2-clause
|
6c5cd3657eb9ba1182311477e2ff57a3
| 29.473684 | 150 | 0.634715 | 4.650602 | false | false | false | false |
ronaldho/visionproject
|
EMIT/EMIT/MyMedicationViewController.swift
|
1
|
19600
|
//
// MyMedicationViewController.swift
// EMIT Project
//
// Created by Andrew on 30/04/16.
// Copyright © 2016 Andrew. All rights reserved.
//
import UIKit
class MyMedicationViewController: AGInputViewController {
@IBOutlet var medName: UITextField!;
@IBOutlet var breakfastButton: UIButton!;
@IBOutlet var lunchButton: UIButton!;
@IBOutlet var dinnerButton: UIButton!;
@IBOutlet var bedButton: UIButton!;
@IBOutlet var medInstructions: UITextView!;
@IBOutlet var discontinueButton: UIButton!;
@IBOutlet var addFromGlossaryButton: UIButton!;
@IBOutlet var medInfoButton: UIButton!;
@IBOutlet var photoActivityIndicator: UIActivityIndicatorView!
@IBOutlet var medHistoryStack: UIStackView!;
@IBOutlet var medHistoryTable: UITableView!
@IBOutlet weak var tableHeight: NSLayoutConstraint!
var delegate: InputViewDelegate?;
var med: MyMedication = MyMedication();
var medList: Medications = Medications();
var medToAdd: Medication?
var medAdded: Bool = false;
var medHistories: [MyMedicationHistory]?;
var breakfastButtonSelected = false;
var lunchButtonSelected = false;
var dinnerButtonSelected = false;
var bedButtonSelected = false;
var discontinued = false;
@IBAction func addMedFromGlossaryButtonPressed(sender: AnyObject) {
if medToAdd != nil {
self.setMedFromGlossary(nil)
// let dosages = Data.getMedicationDosagesForMedication(medToAdd!)
//
// let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
//
// for dosage in dosages {
// alertController.addAction(UIAlertAction(title: dosage.dosage, style: .Default, handler: { (action) -> Void in
// self.setMedFromGlossary(dosage)
// }));
// }
//
// let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action) -> Void in
// })
//
// alertController.addAction(cancel)
//
// alertController.popoverPresentationController?.sourceView = addFromGlossaryButton
// alertController.popoverPresentationController?.sourceRect = (addFromGlossaryButton?.bounds)!
// presentViewController(alertController, animated: true, completion: nil)
} else {
print("Error in addMedFromGlossaryButtonPressed")
}
}
func setMedFromGlossary(dosage: MedicationDosage?) {
// var imageUrl: String?
if dosage != nil {
medName.text = medToAdd!.name + " " + dosage!.dosage;
if dosage!.imageUrl != nil {
// imageUrl = dosage!.imageUrl
}
} else {
medName.text = medToAdd!.name
if medToAdd!.image != nil {
// imageUrl = medToAdd!.imageUrl
}
}
med.pageUrl = medToAdd!.pageUrl
medInfoButton.hidden = false;
addFromGlossaryButton.hidden = true;
medAdded = true;
// if imageUrl != nil {
// self.addPhotoButton!.hidden = true;
// photoActivityIndicator.hidden = false
// photoActivityIndicator.startAnimating()
//
// MedicationAPI().getImageFromUrlWithCompletion(imageUrl!, completion: { (imageFromUrl) in
// if imageFromUrl != nil {
// self.photo!.fullImage = imageFromUrl!
// self.photo!.image = ImageUtils.cropToSquare(imageFromUrl!)
// self.photoContainer!.hidden = false;
// } else {
// self.addPhotoButton!.hidden = false;
// }
// self.photoActivityIndicator.hidden = true
// self.photoActivityIndicator.stopAnimating()
// })
// }
}
@IBAction func medInfoButtonPressed(sender: AnyObject) {
let navCtrl = UIStoryboard(name: "ModalViews", bundle: nil).instantiateViewControllerWithIdentifier("MedInfoNav") as! UINavigationController
let infoCtrl: MedPageHTMLViewController = (navCtrl.viewControllers[0]) as! MedPageHTMLViewController;
infoCtrl.myMed = med;
self.presentViewController(navCtrl, animated: true, completion: nil)
}
@IBAction func medNameChanged(textField: UITextField){
var found: Bool = false;
if medAdded {
found = true;
} else if textField.text!.characters.count > 2 {
for med in medList.medications {
if med.name.lowercaseString.hasPrefix(textField.text!.lowercaseString){
found = true;
addFromGlossaryButton.hidden = false;
addFromGlossaryButton.setTitle(String(format: "Add %@ from Glossary", arguments: [med.name]), forState: UIControlState.Normal)
addFromGlossaryButton.sizeToFit()
medToAdd = med;
}
}
}
if !found {
addFromGlossaryButton.hidden = true;
medToAdd = nil;
}
}
func textViewDidBeginEditing(textView: UITextView) {
if textView == medInstructions {
if textView.textColor == UIColor.greyPlaceholderColor(){
textView.text = ""
textView.textColor = UIColor.blackColor()
}
}
}
func textViewDidEndEditing(textView: UITextView) {
let trimmedString = textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if (trimmedString == ""){
textView.text = "Instructions"
textView.textColor = UIColor.greyPlaceholderColor()
}
}
@IBAction func toggleDiscontinue(){
if discontinued == false {
discontinued = true
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.discontinueButton.backgroundColor = UIColor.EMITBlueColor();
self.discontinueButton.setTitle("Restart", forState: UIControlState.Normal)
})
} else {
discontinued = false
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.discontinueButton.backgroundColor = UIColor.EMITPurpleColor();
self.discontinueButton.setTitle("Discontinue", forState: UIControlState.Normal)
})
}
}
@IBAction func deleteMyMedication(){
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let delete = UIAlertAction(title: "Delete", style: .Destructive, handler: { (action) -> Void in
Data.deleteMyMedication(self.med);
self.dismissViewControllerAnimated(true, completion: nil)
})
let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action) -> Void in
})
alertController.addAction(delete)
alertController.addAction(cancel)
alertController.popoverPresentationController?.sourceView = deleteButton;
alertController.popoverPresentationController?.sourceRect = (deleteButton?.bounds)!
presentViewController(alertController, animated: true, completion: nil)
}
override func imageTapped(sender: UITapGestureRecognizer){
let fivc = UIStoryboard(name: "ModalViews", bundle: nil).instantiateViewControllerWithIdentifier("FullImage") as! FullImageViewController
fivc.image = photo!.fullImage;
fivc.shouldAutorotate()
self.presentViewController(fivc, animated: true, completion: nil)
}
override func viewDidLoad() {
photoActivityIndicator.hidden = true
for view: UIView in self.mainStackView!.arrangedSubviews {
for constraint in view.constraints {
constraint.priority = 999;
}
}
self.medHistoryTable.allowsSelection = false;
self.medHistoryTable.rowHeight = UITableViewAutomaticDimension;
self.medHistoryTable.estimatedRowHeight = 60
self.medHistoryTable.layer.cornerRadius = 5;
self.medHistoryTable.layer.borderColor = UIColor.greyTextFieldBorderColor().CGColor;
self.medHistoryTable.layer.borderWidth = 0.5;
medList.medications = Data.getAllMedications()
medHistories = []
addFromGlossaryButton.hidden = true;
medInfoButton.tintColor = UIColor.EMITDarkGreenColor()
if (med.pageUrl != nil) {
medInfoButton.hidden = false;
} else {
medInfoButton.hidden = true;
}
// Time Icons
let breakfastIcon: UIImage = UIImage(named: "sunrise-filled")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
let lunchIcon: UIImage = UIImage(named: "noon-filled")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
let dinnerIcon: UIImage = UIImage(named: "sunset-filled")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
let bedIcon: UIImage = UIImage(named: "night-filled")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
breakfastButton.setImage(breakfastIcon, forState: UIControlState.Normal)
lunchButton.setImage(lunchIcon, forState: UIControlState.Normal)
dinnerButton.setImage(dinnerIcon, forState: UIControlState.Normal)
bedButton.setImage(bedIcon, forState: UIControlState.Normal)
if (newMode){
self.title = "New My Medication"
self.discontinueButton!.hidden = true;
self.deleteButton!.hidden = true;
self.medHistoryStack.hidden = true;
} else {
self.title = "Edit My Medication"
if (med.discontinued){
self.discontinueButton.backgroundColor = UIColor.EMITBlueColor();
self.discontinueButton.setTitle("Restart", forState: UIControlState.Normal);
self.discontinued = true;
}
}
loadFields();
if (medToAdd != nil) {
setMedFromGlossary(nil)
}
medInstructions!.delegate = self
if (medInstructions != nil){
medInstructions!.layer.cornerRadius = 5;
medInstructions!.layer.borderColor = UIColor.greyTextFieldBorderColor().CGColor;
medInstructions!.layer.borderWidth = 0.5;
if (medInstructions!.text == ""){
medInstructions!.text = "Instructions"
medInstructions!.textColor = UIColor.greyPlaceholderColor()
} else {
medInstructions!.textColor = UIColor.blackColor()
}
}
super.viewDidLoad()
}
@IBAction func toggleBreakfast(){
if (breakfastButtonSelected){
breakfastButtonSelected = false;
breakfastButton.tintColor = UIColor.EMITMediumGreyColor();
} else {
breakfastButtonSelected = true;
breakfastButton.tintColor = UIColor.morningColor();
}
}
@IBAction func toggleLunch(){
if (lunchButtonSelected){
lunchButtonSelected = false;
lunchButton.tintColor = UIColor.EMITMediumGreyColor();
} else {
lunchButtonSelected = true;
lunchButton.tintColor = UIColor.noonColor();
}
}
@IBAction func toggleDinner(){
if (dinnerButtonSelected){
dinnerButtonSelected = false;
dinnerButton.tintColor = UIColor.EMITMediumGreyColor();
} else {
dinnerButtonSelected = true;
dinnerButton.tintColor = UIColor.sunsetColor();
}
}
@IBAction func toggleBed(){
if (bedButtonSelected){
bedButtonSelected = false;
bedButton.tintColor = UIColor.EMITMediumGreyColor();
} else {
bedButtonSelected = true;
bedButton.tintColor = UIColor.moonColor();
}
}
override func loadFields(){
if (med.image != nil){
photo!.fullImage = med.image;
photo!.image = med.croppedImage;
photoContainer!.hidden = false;
addPhotoButton!.hidden = true;
} else {
photoContainer!.hidden = true;
addPhotoButton!.hidden = false;
}
if (med.breakfast){
breakfastButtonSelected = true;
breakfastButton.tintColor = UIColor.morningColor();
} else {
breakfastButton.tintColor = UIColor.EMITMediumGreyColor();
}
if (med.lunch){
lunchButtonSelected = true;
lunchButton.tintColor = UIColor.noonColor();
} else {
lunchButton.tintColor = UIColor.EMITMediumGreyColor();
}
if (med.dinner){
dinnerButtonSelected = true;
dinnerButton.tintColor = UIColor.sunsetColor();
} else {
dinnerButton.tintColor = UIColor.EMITMediumGreyColor();
}
if (med.bed){
bedButtonSelected = true;
bedButton.tintColor = UIColor.moonColor();
} else {
bedButton.tintColor = UIColor.EMITMediumGreyColor();
}
if (med.id != "0"){
medName.text = med.name;
medInstructions.text = med.instructions;
if (medInstructions!.text == ""){
medInstructions!.text = "Instructions"
medInstructions!.textColor = UIColor.greyPlaceholderColor()
} else {
medInstructions!.textColor = UIColor.blackColor()
}
medHistories = Data.getMyMedicationHistory(med.id)
} else {
// No MyMedication to Load, probably New view
}
}
func getAddedOrRemoved(buttonSelected: Bool) -> String{
if (buttonSelected) {
return "added"
} else {
return "removed"
}
}
func getDiscontinuedOrRestarted(discontinued: Bool) -> String {
if (discontinued) {
return "Discontinued"
} else {
return "Restarted"
}
}
@IBAction func save(sender: UIButton){
if (medName.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) != ""){
// Prevent saving placeholder text as instructions data
var instructions = medInstructions.text
if medInstructions!.textColor == UIColor.greyPlaceholderColor() {
instructions = "";
}
var startedDate = med.startedDate
var discontinuedDate = med.discontinuedDate
if (med.discontinued != discontinued) {
if discontinued {
discontinuedDate = NSDate()
} else {
startedDate = NSDate()
}
}
let medIdFromSave = Data.saveMyMedication(MyMedication(withName: medName.text!, andImage: photo!.fullImage, andCroppedImage: photo!.image, andInstructions: instructions, andId: med.id, andBreakfast: breakfastButtonSelected, andLunch: lunchButtonSelected, andDinner: dinnerButtonSelected, andBed: bedButtonSelected, andDate: med.date, andDiscontinued: discontinued, andStartedDate: startedDate, andDiscontinuedDate: discontinuedDate, andPageUrl: med.pageUrl));
// Prepare text for history table
var historyText: String = "";
if (med.discontinued != discontinued) {
historyText += getDiscontinuedOrRestarted(discontinued)
}
if (med.breakfast != breakfastButtonSelected){
if (historyText != "") {
historyText += ", "
}
historyText += "Breakfast time \(getAddedOrRemoved(breakfastButtonSelected))"
}
if (med.lunch != lunchButtonSelected){
if (historyText != "") {
historyText += ", "
}
historyText += "Lunch time \(getAddedOrRemoved(lunchButtonSelected))"
}
if (med.dinner != dinnerButtonSelected){
if (historyText != "") {
historyText += ", "
}
historyText += "Dinner time \(getAddedOrRemoved(dinnerButtonSelected))"
}
if (med.bed != bedButtonSelected){
if (historyText != "") {
historyText += ", "
}
historyText += "Bed time \(getAddedOrRemoved(bedButtonSelected))"
}
if (medInstructions.text != med.instructions){
if (historyText != "") {
historyText += "\n"
}
historyText += medInstructions.text;
}
if (historyText != ""){
Data.saveMyMedicationHistory(MyMedicationHistory(withId: "0", andMedId: medIdFromSave, andDate: NSDate(), andText: historyText))
}
self.dismissViewControllerAnimated(true, completion: nil)
} else {
medName!.shake(10, delta: 10, speed: 0.1);
}
}
override func configureDatePicker(inout picker: UIDatePicker){
picker.datePickerMode = UIDatePickerMode.DateAndTime
picker.minuteInterval = 5;
let calendar = NSCalendar.currentCalendar();
let components = calendar.components([.Year,.Month,.Day], fromDate: NSDate());
components.hour = 12;
let newDate: NSDate = calendar.dateFromComponents(components)!;
picker.setDate((date == StaticDates.sharedInstance.defaultDate) ? newDate : date, animated: true)
}
override func getDateFormat() -> String{
return "MMMM d, h:mm a"
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return medHistories!.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MedHistoryCell", forIndexPath: indexPath) as! MedHistoryTableViewCell
let medHistory = medHistories![indexPath.row];
cell.medHistory = medHistory;
cell.dateLabel.text = medHistory.date.dayMonthYearFormat();
cell.historyTextLabel.text = medHistory.text;
if medHistoryTable.contentSize.height > 250 {
medHistoryTable.scrollEnabled = true
tableHeight.constant = 250;
}
if tableHeight.constant < 250 {
medHistoryTable.scrollEnabled = false
let newHeight = medHistoryTable.contentSize.height + 12
tableHeight.constant = newHeight > 250 ? 250 : newHeight;
}
return cell
}
}
|
mit
|
1b990c9cda5f493f26f4000f3dc26044
| 36.763006 | 471 | 0.584111 | 5.291307 | false | false | false | false |
ishaan1995/susi_iOS
|
Susi/Extensions.swift
|
1
|
1679
|
//
// Extensions.swift
// Susi
//
// Created by Chashmeet Singh on 2017-03-13.
// Copyright © 2017 FOSSAsia. All rights reserved.
//
import UIKit
import Material
extension UIColor {
static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor {
return UIColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: 1)
}
}
extension String {
func isValidEmail() -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,20}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
}
extension UIView {
func addConstraintsWithFormat(format: String, views: UIView...) {
var viewsDictionary = [String: UIView]()
for (index, view) in views.enumerated() {
let key = "v\(index)"
viewsDictionary[key] = view
view.translatesAutoresizingMaskIntoConstraints = false
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
}
}
class AuthTextField: ErrorTextField {
override init(frame: CGRect) {
super.init(frame: frame)
detailColor = .red
isClearIconButtonEnabled = true
placeholderNormalColor = .white
placeholderActiveColor = .white
dividerNormalColor = .white
dividerActiveColor = .white
textColor = .white
clearIconButton?.tintColor = .white
isErrorRevealed = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
apache-2.0
|
03b48a404663ff88de7dc1a4314cd869
| 26.508197 | 152 | 0.635876 | 4.358442 | false | false | false | false |
roddi/UltraschallHub
|
Application/UltraschallHub/DriverManager.swift
|
1
|
940
|
import Foundation
public struct DriverManager {
func load(driverPath: String) -> Bool {
if let param = driverPath.cStringUsingEncoding(NSUTF8StringEncoding) {
return DMLoadDriver(param)
} else {
return false
}
}
func unload(driverPath: String) -> Bool {
if let param = driverPath.cStringUsingEncoding(NSUTF8StringEncoding) {
return DMUnloadDriver(param)
} else {
return false
}
}
func isLoaded(bundleId: String) -> Bool {
if let param = bundleId.cStringUsingEncoding(NSUTF8StringEncoding) {
return (DMQueryDriverStatus(param, nil) == 1) ? true : false
} else {
return false;
}
}
public func activate(driverPath: String) -> Bool {
if isLoaded(driverPath) {
unload(driverPath)
}
return load(driverPath)
}
}
|
mit
|
1acc7d585967bdbf684af2d60bdfbe30
| 24.405405 | 78 | 0.571277 | 4.747475 | false | false | false | false |
piercefreeman/Groot
|
Groot/Groot.swift
|
1
|
6369
|
// Groot.swift
//
// Copyright (c) 2015 Guillermo Gonzalez
//
// 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 CoreData
extension NSManagedObjectContext {
internal func managedObjectModel() -> NSManagedObjectModel {
if let psc = persistentStoreCoordinator {
return psc.managedObjectModel
}
return parentContext!.managedObjectModel()
}
}
extension NSManagedObject {
internal class func entityInManagedObjectContext(context: NSManagedObjectContext) -> NSEntityDescription {
let className = NSStringFromClass(self)
let model = context.managedObjectModel()
for entity in model.entities {
if entity.managedObjectClassName == className {
return entity
}
}
fatalError("Could not locate the entity for \(className).")
}
}
/**
Creates or updates a set of managed objects from JSON data.
- parameter entityName: The name of an entity.
- parameter fromJSONData: A data object containing JSON data.
- parameter inContext: The context into which to fetch or insert the managed objects.
- returns: An array of managed objects
*/
public func objectsWithEntityName(name: String, fromJSONData data: NSData, inContext context: NSManagedObjectContext) throws -> [NSManagedObject] {
return try GRTJSONSerialization.objectsWithEntityName(name, fromJSONData: data, inContext: context)
}
/**
Creates or updates a set of managed objects from JSON data.
- parameter fromJSONData: A data object containing JSON data.
- parameter inContext: The context into which to fetch or insert the managed objects.
- returns: An array of managed objects.
*/
public func objectsFromJSONData<T: NSManagedObject>(data: NSData, inContext context: NSManagedObjectContext) throws -> [T] {
let entity = T.entityInManagedObjectContext(context)
let managedObjects = try objectsWithEntityName(entity.name!, fromJSONData: data, inContext: context)
return managedObjects as! [T]
}
public typealias JSONDictionary = [String: AnyObject]
/**
Creates or updates a managed object from a JSON dictionary.
This method converts the specified JSON dictionary into a managed object of a given entity.
- parameter entityName: The name of an entity.
- parameter fromJSONDictionary: A dictionary representing JSON data.
- parameter inContext: The context into which to fetch or insert the managed objects.
- returns: A managed object.
*/
public func objectWithEntityName(name: String, fromJSONDictionary dictionary: JSONDictionary, inContext context: NSManagedObjectContext) throws -> NSManagedObject {
return try GRTJSONSerialization.objectWithEntityName(name, fromJSONDictionary: dictionary, inContext: context)
}
/**
Creates or updates a managed object from a JSON dictionary.
This method converts the specified JSON dictionary into a managed object.
- parameter fromJSONDictionary: A dictionary representing JSON data.
- parameter inContext: The context into which to fetch or insert the managed objects.
- returns: A managed object.
*/
public func objectFromJSONDictionary<T: NSManagedObject>(dictionary: JSONDictionary, inContext context: NSManagedObjectContext) throws -> T {
let entity = T.entityInManagedObjectContext(context)
let managedObject = try objectWithEntityName(entity.name!, fromJSONDictionary: dictionary, inContext: context)
return managedObject as! T
}
public typealias JSONArray = [AnyObject]
/**
Creates or updates a set of managed objects from a JSON array.
- parameter entityName: The name of an entity.
- parameter fromJSONArray: An array representing JSON data.
- parameter context: The context into which to fetch or insert the managed objects.
- returns: An array of managed objects.
*/
public func objectsWithEntityName(name: String, fromJSONArray array: JSONArray, inContext context: NSManagedObjectContext) throws -> [NSManagedObject] {
return try GRTJSONSerialization.objectsWithEntityName(name, fromJSONArray: array, inContext: context)
}
/**
Creates or updates a set of managed objects from a JSON array.
- parameter fromJSONArray: An array representing JSON data.
- parameter context: The context into which to fetch or insert the managed objects.
- returns: An array of managed objects.
*/
public func objectsFromJSONArray<T: NSManagedObject>(array: JSONArray, inContext context: NSManagedObjectContext) throws -> [T] {
let entity = T.entityInManagedObjectContext(context)
let managedObjects = try objectsWithEntityName(entity.name!, fromJSONArray: array, inContext: context)
return managedObjects as! [T]
}
/**
Converts a managed object into a JSON representation.
- parameter object: The managed object to use for JSON serialization.
:return: A JSON dictionary.
*/
public func JSONDictionaryFromObject(object: NSManagedObject) -> JSONDictionary {
return GRTJSONSerialization.JSONDictionaryFromObject(object) as! JSONDictionary;
}
/**
Converts an array of managed objects into a JSON representation.
- parameter objects: The array of managed objects to use for JSON serialization.
:return: A JSON array.
*/
public func JSONArrayFromObjects(objects: [NSManagedObject]) -> JSONArray {
return GRTJSONSerialization.JSONArrayFromObjects(objects)
}
|
mit
|
056850a655bcd2fbba486097b5b4b938
| 38.314815 | 164 | 0.75789 | 4.987471 | false | false | false | false |
kickstarter/ios-oss
|
KsApi/models/Reward.swift
|
1
|
6171
|
import Foundation
import Prelude
public struct Reward {
public let backersCount: Int?
public let convertedMinimum: Double
public let description: String
public let endsAt: TimeInterval?
public let estimatedDeliveryOn: TimeInterval?
public let hasAddOns: Bool
public let id: Int
public let limit: Int?
public let limitPerBacker: Int?
public let minimum: Double
public let remaining: Int?
public let rewardsItems: [RewardsItem]
public let shipping: Shipping // only v1
public let shippingRules: [ShippingRule]? // only GraphQL
public let shippingRulesExpanded: [ShippingRule]? // only GraphQL
public let startsAt: TimeInterval?
public let title: String?
public let localPickup: Location?
/// Returns `true` is this is the "fake" "No reward" reward.
public var isNoReward: Bool {
return self.id == Reward.noReward.id
}
/// Returns `true` if the `Reward` has a value for the `limit` property.
public var isLimitedQuantity: Bool {
return self.limit != nil
}
/// Returns `true` if the `Reward` has a value for the `endsAt` property.
public var isLimitedTime: Bool {
return self.endsAt != nil
}
/**
Returns the closest matching `ShippingRule` for this `Reward` to `otherShippingRule`.
If no match is found `otherShippingRule` is returned, this is to be backward-compatible
with v1 Rewards that do not include the `shippingRulesExpanded` array.
*/
public func shippingRule(matching otherShippingRule: ShippingRule?) -> ShippingRule? {
return self.shippingRulesExpanded?
.first { shippingRule in
shippingRule.location.id == otherShippingRule?.location.id
}
?? otherShippingRule
}
public struct Shipping: Decodable {
public let enabled: Bool
public let location: Location? /// via v1 if `ShippingType` is `singleLocation`
public let preference: Preference?
public let summary: String?
public let type: ShippingType?
public struct Location: Equatable, Decodable {
private enum CodingKeys: String, CodingKey {
case id
case localizedName = "localized_name"
}
public let id: Int
public let localizedName: String
}
public enum Preference: String, Decodable {
case local
case none
case restricted
case unrestricted
}
public enum ShippingType: String, Decodable {
case anywhere
case multipleLocations = "multiple_locations"
case noShipping = "no_shipping"
case singleLocation = "single_location"
}
}
}
extension Reward: Equatable {}
public func == (lhs: Reward, rhs: Reward) -> Bool {
return lhs.id == rhs.id
}
private let minimumAndIdComparator = Reward.lens.minimum.comparator <> Reward.lens.id.comparator
extension Reward: Comparable {}
public func < (lhs: Reward, rhs: Reward) -> Bool {
return minimumAndIdComparator.isOrdered(lhs, rhs)
}
extension Reward: Decodable {
enum CodingKeys: String, CodingKey {
case backersCount = "backers_count"
case convertedMinimum = "converted_minimum"
case description
case reward
case endsAt = "ends_at"
case estimatedDeliveryOn = "estimated_delivery_on"
case hasAddOns = "has_addons"
case id
case limit
case limitPerBacker = "limit_per_backer"
case minimum
case remaining
case rewardsItems = "rewards_items"
case shippingRules = "shipping_rules"
case shippingRulesExpanded = "shipping_rules_expanded"
case startsAt = "starts_at"
case title
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.backersCount = try values.decodeIfPresent(Int.self, forKey: .backersCount)
self.convertedMinimum = try values.decode(Double.self, forKey: .convertedMinimum)
if let description = try? values.decode(String.self, forKey: .description) {
self.description = description
} else {
self.description = try values.decode(String.self, forKey: .reward)
}
self.endsAt = try values.decodeIfPresent(TimeInterval.self, forKey: .endsAt)
self.estimatedDeliveryOn = try values.decodeIfPresent(TimeInterval.self, forKey: .estimatedDeliveryOn)
self.hasAddOns = try values.decodeIfPresent(Bool.self, forKey: .hasAddOns) ?? false
self.id = try values.decode(Int.self, forKey: .id)
self.limit = try values.decodeIfPresent(Int.self, forKey: .limit)
self.limitPerBacker = try values.decodeIfPresent(Int.self, forKey: .limitPerBacker)
self.minimum = try values.decode(Double.self, forKey: .minimum)
self.remaining = try values.decodeIfPresent(Int.self, forKey: .remaining)
self.rewardsItems = try values.decodeIfPresent([RewardsItem].self, forKey: .rewardsItems) ?? []
self.shipping = try Shipping(from: decoder)
self.shippingRules = try values.decodeIfPresent([ShippingRule].self, forKey: .shippingRules) ?? []
self.shippingRulesExpanded = try values.decodeIfPresent(
[ShippingRule].self,
forKey: .shippingRulesExpanded
) ?? []
self.startsAt = try values.decodeIfPresent(TimeInterval.self, forKey: .startsAt)
self.title = try values.decodeIfPresent(String.self, forKey: .title)
// NOTE: `v1` is deprecated and doesn't contain any location pickup information.
self.localPickup = nil
}
}
extension Reward.Shipping {
private enum CodingKeys: String, CodingKey {
case enabled = "shipping_enabled"
case location = "shipping_single_location"
case preference = "shipping_preference"
case summary = "shipping_summary"
case type = "shipping_type"
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.enabled = try values.decodeIfPresent(Bool.self, forKey: .enabled) ?? false
self.location = try? values.decode(Location.self, forKey: .location)
self.preference = try? values.decode(Preference.self, forKey: .preference)
self.summary = try? values.decode(String.self, forKey: .summary)
self.type = try? values.decode(ShippingType.self, forKey: .type)
}
}
extension Reward: GraphIDBridging {
public static var modelName: String {
return "Reward"
}
}
|
apache-2.0
|
dc6b8d8b4e194fd7c925dd5b974e5682
| 34.67052 | 106 | 0.712688 | 4.133289 | false | false | false | false |
victorpimentel/PrimerosPasosConSwift
|
Primeros pasos con Swift.playground/Contents.swift
|
1
|
30203
|
//: # Primeros Pasos con Swift
//:
//: Con este playground intentaremos echarle un vistazo al nuevo lenguaje de programación de Apple partiendo desde el punto de vista de un programador de Objective C, pero intentando explicar los nuevos conceptos de manera más generalista.
//:
//: Como lenguaje en general, Swift intenta traer a la comunidad funcionalidades modernas exploradas en los últimos años (o décadas) en otros lenguajes, y aumentar la facilidad para escribir código seguro, de ahí la distancia que de manera voluntaria toma de C. A la vez, intenta seguir una sintaxis limpia, elegante y clara.
//:
//: Swift se postula como un reemplazo a Objective C como lenguaje de programación preferente de las plataformas de Apple. Esta realidad causa algunas asperezas al tratar con las APIs tradicionales como Cocoa que no están pensadas o adaptadas de manera óptima para Swift.
//:
//: Los playgrounds son una herramienta integrada en Xcode muy sencilla y muy útil a la hora de aprender. Incluso cuando ya estemos familiarizados con el lenguaje, son muy útiles para experimentar con nuevos conceptos o nuevas APIs. Sin duda es una de las cosas más espectaculares respecto a Objective C.
//:
//: ---
//:
//: ## Variables
//:
//: ### Inferencia de tipos
//:
//: En Swift una variable se declara de la siguiente manera:
var firstCat: String
//: Si queremos especificar un valor inicial:
var secondCat: String = "Félix"
//: Normalmente no escribiremos el tipo de lo que queremos tener, la mayor parte del tiempo aprovecharemos la inferencia de tipos que Swift implementa, quedando algo mucho más natural:
var thirdCat = "😺"
//: Swift automáticamente detecta en tiempo de compilación que la variable es un String y refuerza ese tipado, así que no podremos más adelante tratarlo como, por ejemplo, un entero:
//! secondCat = 42
//: Esta inferencia funciona en la mayoría de los casos: literales, llamadas a funciones, llamadas a inicializadores, etc.
var allCats = [secondCat, thirdCat, "Isidoro"]
var catCount = allCats.count
//: **Truco**: en los casos donde no tengamos claro qué tipo se está infiriendo, Alt + Click sobre el texto nos sirve para revisar el tipo de una variable o expresión.
//:
//: ### Mutabilidad
//:
//: Si declaramos una variable con la palabra clave `var`, podremos modificar su valor cuántas veces queramos, pero si la declaramos con la palabra `let` no se podrá redefinir. Es decir, en Swift utilizamos let para declarar constantes:
let friendsCount = 5
//! friendsCount = 3
//: Esto funciona en estructuras (los tipos básicos están definidos en el propio lenguaje como structs), enumerados y tuplas, pero no en clases: podremos modificar sus valores internos pero no podremos asignarle otro objeto a esa constante. Más adelante hablaremos más sobre estos tipos compuestos.
//:
//: Estos modificadores funcionan en todos los contextos, así que los veremos muy a menudo: para definir variables globales, variables locales, propiedades de clases, funciones/bloques, etc. Como regla general, es preferible usar let, y el compilador nos avisará cuando sea posible.
//:
//: ## Funciones
//:
//: Conocer la estructura de una función es básico en Swift, dado que exactamente la misma sintaxis se usa en funciones globales, lambdas (bloques) y métodos de una clase.
func doAwesomeStuff() {
}
func doAwesomeStuff() -> Int {
var total = 0
for i in 1...5 {
total += i
}
return total
}
func doAwesomeStuff(catName: String, doItFast: Bool = true) -> Int {
if doItFast {
return catName.hashValue
} else {
return catName.characters.count
}
}
//: Swift soporta sobrecarga de funciones, y en tiempo de compilación elegirá la versión de la función más adecuada al contexto.
//:
//: El tipo de retorno por defecto es Void (al contrario que otros lenguajes como C, donde es int). Si ese es el caso de nuestra función no hace falta especificarlo.
//:
//: Los parámetros de entrada de la función deben especificar el tipo, y pueden definirse como omitibles si definimos un valor por defecto.
//:
//: Para llamar a una función decimos adiós a los corchetes y utilizamos una forma mucho más familiar a otros lenguajes:
//! doAwesomeStuff()
//! let awesomeStuff = doAwesomeStuff()
var awesomeStuffInt: Int = doAwesomeStuff()
let awesomeStuffVoid: Void = doAwesomeStuff()
var awesomeStuff = doAwesomeStuff("Hello Kitty")
awesomeStuff = doAwesomeStuff("Hello Kitty", doItFast: false)
//: En las funciones los parámetros pueden ser nombrados o no. Las reglas son relativamente complejas, principalmente para ser compatible con las APIs de Objective C como Cocoa.
//:
//: Por defecto el primer parámetro al ser llamado no tiene nombre, mientras que el resto sí.
func printCatName(name: String, surname: String) {
print(name + surname)
}
printCatName("😼", surname: "🇪🇸")
//: Pero se puede optar por especificar un nombre externo a los parámetros, que puede ser independiente del interno:
func printCat(name catName: String) {
print(catName)
}
printCat(name: "😽")
//: Estas reglas son las mismas tanto para funciones como para métodos.
//:
//: # Tipos de datos compuestos
//:
//: Swift tiene diversos tipos de datos compuestos, pero al contrario que en otros lenguajes, todos los tipos son de primera clase. De hecho, una de las dudas que tendremos al crear un modelo será qué tipo es el más adecuado.
//:
//: ## Enumerados
//:
//: Los enumerados de Swift son muy potentes respecto a otros lenguajes. En el caso más básico su aspecto es:
enum CoolAnimals {
case Cat
case Pig
}
//: A partir de ahora podemos definir variables de este tipo, utilizando la inferencia de tipos para hacer más ameno trabajar con ellas:
let coolAnimal = CoolAnimals.Cat
var otherCoolAnimal: CoolAnimals
otherCoolAnimal = .Pig
//: Podemos añadir un valor a cada uno de los valores si tipamos el enumerado:
enum CoolAnimalsStrings: String {
case Cat = "🙀"
case Pig = "🐷"
}
CoolAnimalsStrings.Cat.rawValue
//: Por último también podemos enlazar valores dependiente de cada tipo por cada variable, pero para acceder a él tendremos que utilizar _pattern matching_, por ejemplo con un `switch`:
enum CoolHeterogeneousAnimals {
case Cat(name: String)
case Pig
}
let coolHeterogenerousAnimal = CoolHeterogeneousAnimals.Cat(name: "Mordisquitos")
switch (coolHeterogenerousAnimal) {
case .Pig:
print("Unnamed pig")
case .Cat(let name):
print(name)
}
//: ## Estructuras
//:
//: Las estructuras de Swift también son increíblemente potentes. De hecho, los tipos básicos como `String` o `Int` son estructuras, adaptando interesantes propiedades.
struct Payment {
var amount = 0.0
var currency: String
}
//: Automáticamente las estructuras generan un constructor con el orden en el que se han definido sus propiedades.
var firstPayment = Payment(amount: 25, currency: "EUR")
//: Las estructuras pueden tener también métodos, y también pueden ser extendidas (útil para extender los tipos comunes o para organizar nuestro código):
extension Payment {
func prettyPrint() -> String {
return "\(currency) \(amount)"
}
}
firstPayment.prettyPrint()
//: La semántica de mutabilidad está presente en las estructuras, de tal manera que no podremos modificar sus datos si las definimos como constantes:
firstPayment.amount = 35
firstPayment.prettyPrint()
let immutablePayment = Payment(amount: 39, currency: "USD")
//! immutablePayment.amount = 35
//: Los métodos tienen permitido modificar los valores internos de una estructura, pero deben estar marcados con la palabra clave **mutating** para especificar su comportamiento. Estos métodos no pueden usarse en constantes.
extension Payment {
mutating func doubleIt() {
amount *= 2
}
}
firstPayment.doubleIt()
firstPayment.prettyPrint()
//! staticPayment.doubleIt()
//: ## Clases
//:
//: Las clases siguen una estructura muy similar
class Cashier {
var name = "Unnamed"
func processPayment(payment: Payment, inCash: Bool) {
print(payment)
}
}
//: Como vemos, la semántica de mutabilidad es diferente, en constantes podemos modificar un atributo/propiedad pero no asignar otro objeto.
let firstCashier = Cashier()
firstCashier.name = "Paco"
//! firstCashier = Cashier()
//: También el constructor generado por defecto es distinto a las estructuras, simplemente tenemos un constructor vacío.
//:
//: ---
//:
//: Respecto a Objective C, podemos notar varios cambios:
//:
//: - No hay distinción de header/implementation (.h/.m)
//: - (Teóricamente) no hace falta heredar de NSObject.
//: - En general es mucho más sucinto.
//:
//: Para llamar a métodos las reglas son iguales a las funciones normales y mantienen una sintaxis consistente:
firstCashier.processPayment(firstPayment, inCash: true)
//: Si quisiéramos borrar el nombre de cualquiera de los parámetros adicionales, podríamos utilizar el símbolo `_`.
extension Cashier {
func processPaymentAndGuessTheSecondParam(payment: Payment, _ inCash: Bool) {
print(payment)
}
}
firstCashier.processPaymentAndGuessTheSecondParam(firstPayment, true)
//: Las clases, al contrario que las estructuras, admiten herencia, así que podríamos crear una nueva clase que extienda de la primera. Todos los métodos que se sobreescriban deben estar marcados con la palabra clave `override`:
class FastCashier: Cashier {
func processPayment(payment: Payment) {
super.processPayment(payment, inCash: false)
}
override func processPayment(payment: Payment, inCash: Bool) {
super.processPayment(payment, inCash: false)
}
}
let fastCashier = FastCashier()
//: Si queremos evitar que una clase sea heredable, podemos definirla con la palabra clave `final`.
final class StupiestClass {
}
//: Las clases pueden incluir constructores, que deben cumplir ciertas reglas para asegurar la correcta inicialización de una clase. Son bastante complejas, así que intentaremos simplificar centrándonos en los inicializadores más comunes (sin especificar **required** ni `convenience`):
//:
//: - Un constructor debe primero asignar un valor a todas sus variables (luego matizaremos con los opcionales).
//: - Luego debe llamar a un constructor de la clase padre.
//: - Al final puede hacer cualquier trabajo adicional que crea oportuno.
class NamedCashier {
var name: String
init(name: String) {
self.name = name
}
}
let namedCashier = NamedCashier(name: "Maria")
class SeniorCashier: NamedCashier {
var seniority: Int
init(seniority: Int) {
self.seniority = seniority
super.init(name: "Apu")
print(self.name)
}
}
let seniorCashier = SeniorCashier(seniority: Int.max)
//: También podemos generar propiedades computadas:
class Person {
var name = "Víctor"
var initial: Character {
return name.characters.first!
}
}
let yo = Person()
yo.initial
//: Estas propiedades pueden ser de lectura o de lectura y escritura:
class Person2 {
var name = "Víctor"
var initial: Character {
get {
return name.characters.first!
}
set {
name = String(newValue) + name
}
}
}
let yo2 = Person2()
yo2.initial
yo2.initial = "B"
//: Además podemos añadir observadores a las propiedades que se ejecutarán antes o después de cambiarlas:
class Person3 {
var name: String = "Víctor" {
willSet {
print("I'll be " + newValue)
}
didSet {
print("I was " + oldValue)
}
}
}
let yo3 = Person2()
yo3.name = "Victoria"
//: No hay que confundir estos observadores con KVO: ni reemplazan ni ofrecen las mismas funcionalidades. Para empezar estos observadores solo pueden ser definidos junto a la propiedad.
//:
//: ## Protocolos
//:
//: Los protocolos definen un contrato formal sobre una particular tarea sin definir cómo debería estar implementada (como las interfaces en lenguajes como Java).
//:
//: En Swift, tanto las clases como las estructuras y los enumerados pueden conformar protocolos.
protocol Describable {
func description() -> String
}
class Cesar: Describable {
func description() -> String {
return "I'm awesome"
}
}
enum Currency: String, Describable {
case Euro = "EUR"
case Dollar = "USD"
func description() -> String {
return "My symbol is " + rawValue
}
}
//: Podemos también conformar protocolos en extensiones:
extension Cashier: Describable {
func description() -> String {
return "I'm cashier " + name
}
}
firstCashier.description()
//: Y desde Swift 2.0 también podemos implementar métodos en protocolos. En la práctica facilita añadir funcionalidad a una gran variedad de clases del sistema. A la vez, nos ofrece una nueva herramienta para organizar nuestro propio código.
extension Describable {
func allCapsDescription() -> String {
return self.description().uppercaseString
}
}
//: ## Tuplas
//:
//: El tipo de datos compuesto más básico de Swift son las tuplas, una simple combinación de otros valores. Se definen así:
var myFirstTuple: (Int, Double, String)
//: La forma literal es muy simple:
let mySecondTuple = (42, "Wait a little")
//: Para acceder a los valores de una tupla podemos acceder a sus índices numéricos:
mySecondTuple.0
mySecondTuple.1
//: Pero podemos definir etiquetas para explicar su contenido:
let myThirdTuple = (code: 42, message: "Wait a little")
myThirdTuple.code
myThirdTuple.message
//: Sí vamos a reusar una tupla en particular, podemos definir un alias de tipo con los parámetros exactos de la tupla:
typealias ErrorTuple = (code: Int, message: String)
//: Así será más fácil referirse a ellas en funciones y otros contextos:
var myGreatTuple: ErrorTuple
func whereIsMyError(input: String) -> (code: Int, message: String) {
return (42, input)
}
func whereIsMyErrorBetter(input: String) -> ErrorTuple {
return (42, input)
}
//: Al igual que las estructuras o los enumerados, lamentablemente esta clase de tipos no es compatible con las APIs de Objective C, así que cualquier código escrito con esta clase es estructuras no será accesible fuera de Swift.
//:
//: ### ¿Qué elegir?
//:
//: No es una tarea fácil decidir qué tipo debemos usar a la hora de modelar.
//:
//: - Las tuplas son las más rápidas de definir, pero las menos extensibles.
//: - Las estructuras son muy potentes y bastante rápidas de definir, aparte de soportar la semántica de mutabilidad. En su contra (¿o a favor?) está el no poder heredar, solo extender.
//: - Las clases son las menos rápidas de definir y no soportan la semántica de mutabilidad. Sin embargo la posibilidad de extensión y su enorme presencia en las APIs de Cocoa las hacen la única solución para muchos problemas.
//: - Los enumerados tienen un ámbito distinto al del resto de estructuras de datos, pero los datos enlazados pueden ampliar su uso.
//:
//: También habría que tener en cuenta el aspecto de la memoria: las clases son pasadas por referencia, mientras que el resto son pasados por valor. Eso significa, entre otras cosas, que si pasamos una estructura a una función y la modificamos dentro de la función, esos cambios no serán visibles por quién llamó originalmente a esa función.
//:
//: ## Opcionales
//:
//: En Objective C y otros lenguajes cualquier variable que pueda contener un objeto es nulable. Esto causa null pointer exceptions en algunos lenguajes y en Objective C puede llevar a errores muy sutiles, hasta que crashea nuestra aplicación al invocar un método que no admite nil como parámetro aceptable. En otros lenguajes existe la posibilidad de marcar un variable como nulable, anotando explícitamente que puede contener el valor null.
//:
//: En Swift por defecto una variable no puede contener el valor null (o no estar asignada), en caso contrario ni siquiera compilará:
var nonOptional = "Hey there"
//! nonOptional = nil
//: Para modelar el concepto de nullable Apple ha optado por los opcionales, que no es más que un enumerado que modela dos estados: tener contenido y no tener contenido.
var firstOptional = Optional("Hey there")
firstOptional = Optional()
firstOptional = nil
firstOptional = "Hey there"
//: Para facilitar el trabajo con los opcionales, el lenguaje introduce el símbolo `?` para definir un opcional de manera más sucinta:
var secondOptional: String?
secondOptional = "Hey there"
//: Vemos que automáticamente (gracias a unos protocolos que nuestras clases/estructuras también pueden implementar) la asignación de valores es muy intuitiva. Quizás demasiado, ya que podemos perder de vista lo que realmente hay por debajo.
//:
//: Sin embargo, para acceder a su contenido tenemos explícitamente que tratar con los dos posibles casos, no podemos usarlos directamente:
//! secondOptional + " :("
if let secondOptional = secondOptional {
secondOptional + " :)"
}
//: Podemos pensar que los opcionales son como envoltorios de caramelos: pueden contener o no un caramelo, pero para saber si lo tienen tenemos que abrirlo antes.
//:
//: Para evitar este baile de condicionales, en los casos en los que estemos 100% seguros podemos unwrappear directamente el valor con el operador `!`. Hay que tener mucho cuidado con ese operador porque si el valor interno es nil, crasheará la aplicación en tiempo de ejecución.
secondOptional! + " :|"
//! firstOptional = nil
firstOptional! + " :S"
//: Por último también tenemos otra opción que veremos lamentablemente muy a menudo pero que hay que evitar en la medida de lo posible: los **implicitly unwrapped optionals**. Estas son variables definidas con el símbolo ! en vez de ?, y se comportan exactamente igual que una variable normal, pero si contienen nil crashean al intentar usarlos.
var implicitlyUnwrappedHell: String! = "Let's roll the dice"
implicitlyUnwrappedHell + " Yeah!"
implicitlyUnwrappedHell = nil
//! implicitlyUnwrappedHell + " Noooooo!"
//: Si queremos acceder a un método de un valor que pueda ser nulo de manera simple, podemos utilizar _encadenamientos opcionales_:
var mayBeNil: String?
mayBeNil?.startIndex
//: Este concepto puede ser especialmente útil al llamar a métodos en delegados.
//:
//: Aunque a primera vista no parezca muy complicado, el concepto de opcional será probablemente uno de los que mayores dolores de cabeza nos cause, al estar impregnado por toda la API de Cocoa. Y aunque en estos momentos la API de Cocoa está cerca de ser 100% auditada, lamentablemente veremos los opcionales implícitamente desenvueltos en demasiados sitios, como por ejemplo en los outlets.
//:
//: Por la inevitabilidad de lidiar con todos estos problemas, es imprescindible saberse manejar bien con los opcionales.
//:
//: ### Guard
//:
//: Trabajar con opcionales en código real antes o temprano acaba en famosas _pirámides de la muerte_ al enlazar varios _if let_:
func letPyramid(name: String?, surname: String?, nickname: String?) {
if let name = name {
if let surname = surname {
if let nickname = nickname {
print("\(name) \(surname) \(nickname)")
}
}
}
}
//: Podemos mejorar un poco el código y evitar niveles de indentación si encadenamos los _lets_ en la misma condición:
func letItBe(name: String?, surname: String?, nickname: String?) {
if let name = name, let surname = surname, let nickname = nickname {
print("\(name) \(surname) \(nickname)")
}
}
//: Sin embargo muchas veces por cómo está configurado nuestro código no podemos acogernos esa solución, o simplemente queremos evitar todos los niveles de indentación.
//:
//: Para esos casos podemos utilizar `guard` para implementar un _early return_ y dejar el nivel de indentación principal para el _happy case_:
func guardOfTheGalaxy(name: String?, surname: String?, nickname: String?) {
guard let name = name else { return }
guard let surname = surname else { return }
guard let nickname = nickname else { return }
print("\(name) \(surname) \(nickname)")
}
//: Una vez conocida la sintaxis y sus implicaciones, en programas reales el código resultante es mucho más legible y fácil de seguir respecto a las pirámides:
//:
//: - En el bloque principal (entre guard y else) definimos una precondición.
//: - El bloque else debe salir del scope actual, conteniendo un return o un continue/break en el caso de bucles.
//: - Esa precondición, de ser falsa, ejecuta el bloque else, por tanto siempre sale del scope actual.
//: - Esa precondición, de ser verdadera, sigue con la ejecución del scope actual.
//:
//: La característica más útil de los guards es que permite desenvolver opcionales y continuar con la ejecución garantizando que esos valores deselvueltos no son nulos.
//:
//: ## Genéricos
//:
//: Este tema da para hablar mucho, simplemente vamos a repasar lo mínimo indispensable para entender este concepto en Swift.
//:
//: Los genéricos son una herramienta increíblemente potente que nos ayudará a reutilizar código sin perder la seguridad que nos da el tipado fuerte.
//:
//: Imaginemos que queremos construir una pila que guarde enteros:
struct IntStack {
var items = [Int]()
mutating func push(item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
}
var intStack = IntStack()
intStack.push(1)
intStack.push(2)
intStack.push(3)
intStack.pop()
intStack.pop()
intStack.pop()
//: Funciona como esperamos, pero esta estructura es poco reutilizable. ¿Y si ahora queremos guardar Strings o Cashiers? En principio todo el código que hemos escrito no tiene que ver específicamente con enteros, estamos simplemente añadiendo y quitando elementos. Que sean enteros o cualquier otro tipo es un simple detalle concreto.
//:
//: Los genéricos nos permiten abstraer esa concreción y ampliar la utilidad del código que escribimos. Una versión genérica sería similar a:
struct Stack<Element> {
var items = [Element]()
mutating func push(item: Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
}
var intGenericStack = Stack<Int>()
intGenericStack.push(1)
intGenericStack.push(2)
intGenericStack.push(3)
intGenericStack.pop()
intGenericStack.pop()
intGenericStack.pop()
//: Funciona exactamente igual, simplemente hemos tenido que especificar que queríamos una pila de enteros al crear el objeto. Si quisieramos hacer una pila de Cashiers:
var cashierStack = Stack<Cashier>()
cashierStack.push(firstCashier)
//! cashierStack.push(2)
cashierStack.push(fastCashier)
cashierStack.pop()
cashierStack.pop()
//: Sin tener que escribir otra vez el algoritmo, hemos podido reutilizar el código sin perder ninguna ventaja del tipado fuerte.
//:
//: Este concepto es importante porque en Swift puro, varias de las clases más usadas están basadas en genéricos, como los arrays o los diccionarios, colecciones que por defecto solo admiten elementos del mismo tipo (al contrario que en Objective C):
var myStringArray: [String]
var myStringArray2: Array<String>
let myIntArray = [1, 2, 3]
//! let myWrongArray = [1, "wat", 3]
let myIntToDoubleDictionary = Dictionary<Int, Double>()
let myIntToDoubleDictionary2 = [Int: Double]()
let myIntToStringDictionary = [1: "one", 2: "two"]
//! let myWrongDictionary = [1: 5, 2: "two"]
//: Por debajo Swift directamente nos hará un puente a `NSArray` y `NSDictionary`, lo cual implica que esta seguridad de tipado solo se puede reforzar en tiempo de compilación. Mientras que en tiempo de ejecución si guardamos un valor incorrecto todo funcionará excepto en el sitio en que intentemos utilizar ese valor con el tipo incorrecto.
//:
//: ## Bloques (Closures)
//:
//: Las funciones son también ciudadanos de primera en Swift: se pueden asignar a variables, pasar como parámetro, etc.
//:
//: El método sort recibe una colección y una función que sepa distinguir el orden entre dos elementos de esa colección. Podemos pasarle directamente una función que creemos para tal efecto:
var unsortedList = [3, 1, 2]
func greaterThan(first: Int, second: Int) -> Bool {
return first > second
}
unsortedList.sort(greaterThan)
//: Quizás no nos interese o nos resulte tedioso crear una función adicional. Swift nos ofrece la opción de definirla directamente de diferentes maneras:
unsortedList.sort({
(first: Int, second: Int) -> Bool in
return first > second
})
unsortedList.sort {
(first: Int, second: Int) -> Bool in
return first > second
}
unsortedList.sort {
first, second in
return first > second
}
unsortedList.sort {
first, second in
first > second
}
unsortedList.sort { $0 > $1 }
unsortedList.sort(>)
//: Los bloques de Objective C son automáticamente convertidos a estas funciones sin necesidad de que el programador especifique nada. Esto significa que las mismas implicaciones de gestión de memoria de los bloques aplican aquí también.
//:
//: ## Casting e interoperabilidad con Objective C
//:
//: Si queremos castear un objeto a otro tipo, podemos utilizar los operadores `as?` y `as!`:
var surprise: Any
surprise = "Not any object"
//! surprise.startIndex
let surprisedString = surprise as! String
surprisedString.startIndex
let surprisedStringOptional = surprise as? String
surprisedStringOptional?.startIndex
//: Swift automáticamente nos realizará un casting de tipos de Foundation a los tipos nativos:
//:
//: - `NSArray` <-> `Array`
//: - `NSDictionary` <-> `Dictionary`
//: - `NSString` <-> `String`
//: - `int` <-> `Int`
//: - `float` <-> `Float`
//: - `double` <-> `Double`
//:
//: Este casting automático solo sucede en ciertas ocasiones, por ejemplo al traducir funciones de Objective C. Si queremos utilizar explícitamente un tipo nativo, deberemos especificarlo al crear la variable.
let myString = "I'm native"
import Foundation
let myNSString: NSString = "I'm native"
//: En ciertas ocasiones tendremos que traducir a un tipo específico de Objective C y el casting en lugar de hacerlo con `as?` lo haremos con inicializadores.
import UIKit
let myDouble = 5.2
//! let myCGFloat = myDouble as CGFloat
let myCGFloat = CGFloat(myDouble)
//: Esta traducción de tipos también incluye enumerados, que quedan mucho más claros y potentes en Swift sin necesidad de que hagamos otra cosa que seguir las convenciones de Objective-C.
//:
//: Por último, si queremos acceder a los tipos básicos de C, también lo podremos hacer, normalmente poniendo una C delante.
//:
//: ## Tratamiento de errores
//:
//: En Swift 2.0 el tratamiento de errores está basado en una sintaxis similar a las excepciones, pero con varias diferencias.
//:
//: Así definimos una función que puede lanzar un error:
func canThrowAnError() throws {
// this function may or may not throw an error
}
//: El error que puede lanzar no está definido, mejor dicho, el error puede ser de cualquier tipo siempre que conforme con el protocolo vacío `ErrorType`. Enumerados son probablemente la mejor opción:
struct MyError : ErrorType {
}
enum MyOtherError : ErrorType {
case NotFound
case ServerError(code: Int)
}
func willThrowAnError() throws {
throw MyOtherError.NotFound
}
//: Para llamar a esa función debemos utilizar la palabra reservada `try`, y si no queremos relanzar ese error debemos capturarlo dentro de un bloque do catch.
do {
try canThrowAnError()
print("no error :)");
} catch {
print("error :(");
}
//: Si queremos hacer algo con ese error debemos utilizar _pattern matching_:
do {
try canThrowAnError()
} catch is MyError {
print("hey")
} catch MyOtherError.NotFound {
print("not found!")
} catch MyOtherError.ServerError(let code) {
print("server error \(code)")
}
//: Lo más interesante y la razón por la que veremos más este patrón, es que cualquier método en Objective-C que siga las convenciones estándar será convertido automáticamente a este patrón:
//:
//: - `-(void)myMethod...error:(NSError **)error` a `myMethod: ... -> Void throws`
//: - `-(BOOL)myMethod...error:(NSError **)error` a `myMethod: ... -> Void throws`
//: - `-(id)myMethod...error:(NSError **)error` a `myMethod: ... -> Any throws`
//:
//: ## Recursos
//:
//: ### Imprescindibles
//:
//: - [The Swift Programming Language](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/): Libro básico oficial y documentación online.
//: - [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/): Trabajar con APIs de Cocoa y mezclar código Objective C y Swift.
//: - [Swift In Flux](https://github.com/ksm/SwiftInFlux): Documentación beta a beta.
//: - [Swift Blog](https://developer.apple.com/swift/blog/): Blog oficial de Apple.
//: - [NSHipster](http://nshipster.com/): Las mejores APIs de Swift y Objective C.
//: - [Objc.io sobre Swift](http://www.objc.io/issue-16/): Revista online con excelentes artículos sobre Swift.
//: - [Realm.io](https://realm.io/news/#apple): Artículos y vídeos sobre Swift (click en Apple).
//:
//: ### Blogs personales
//:
//: - [Airspeed Velocity](http://airspeedvelocity.net/)
//: - [Mike Ash](http://www.mikeash.com/pyblog/)
//: - [Russ Bishop](http://www.russbishop.net/)
//: - [Alejandro Salazar](http://nomothetis.svbtle.com/)
//: - [Giant Robots Smashing Into Other Giant Robots](http://robots.thoughtbot.com/)
//: - [David Owens](http://owensd.io/)
//: - [Rob Napier](http://robnapier.net/)
//: - [Nate Cook](http://natecook.com/blog/)
//: - [Artsy](http://artsy.github.io/)
//: - [Natasha The Robot](http://natashatherobot.com/)
//: - [That thing in Swift](https://thatthinginswift.com/)
//: - [Martin Krzyżanowski](http://blog.krzyzanowskim.com/)
//: - [Brent Simmons](http://inessential.com/)
//: - ...
//:
//: ### Listas de correo con enlaces semanales
//:
//: - [Natasha's This week in Swift](https://swiftnews.curated.co/)
//: - [Dave Werver's iOS Dev Weekly](https://iosdevweekly.com/)
//: - [Swift Sandbox](http://swiftsandbox.io/)
//: - [Indie iOS Focus](https://indieiosfocus.curated.co/)
//:
//: ## Repo
//:
//: [https://github.com/victorpimentel/PrimerosPasosConSwift](https://github.com/victorpimentel/PrimerosPasosConSwift)
//:
//: ## ¡Estamos contratando!
//:
//: Si quieres trabajar en pleno centro de Madrid en el fantástico equipo de Tuenti haciendo iOS, mándame un email a:
//:
//: [[email protected]](mailto:[email protected])
|
mit
|
bfdca6a90f8ee1a3f89b6a72f23b1603
| 35.654412 | 442 | 0.745904 | 3.08287 | false | false | false | false |
piars777/TheMovieDatabaseSwiftWrapper
|
Sources/Client/Client.swift
|
1
|
3659
|
//
// Client.swift
// MDBSwiftWrapper
//
// Created by George on 2016-02-11.
// Copyright © 2016 GeorgeKye. All rights reserved.
//
import Foundation
public struct ClientReturn{
public var error: NSError?
public var json: JSON?
// public var MBDBReturn: AnyObject?
public var pageResults: PageResultsMDB?
}
struct Client{
static func networkRequest(url url: String, parameters: [String : AnyObject], completion: (ClientReturn) -> ()) -> (){
var cReturn = ClientReturn()
HTTPRequest.request(url, parameters: parameters){
rtn in
if(rtn.error == nil){
let json = JSON(data: rtn.data!)
cReturn.error = nil
cReturn.json = json
if(json["page"] != nil){
cReturn.pageResults = PageResultsMDB.init(results: json)
}else{
cReturn.pageResults = nil
}
completion(cReturn)
}else{
print(rtn.error)
cReturn.error = rtn.error
cReturn.json = nil
cReturn.pageResults = nil
completion(cReturn)
}
}
}
}
class HTTPRequest{
class func request(url: String, parameters: [String: AnyObject],completionHandler: (data: NSData?, response: NSURLResponse?, error: NSError?) -> ()) -> (){
let parameterString = parameters.stringFromHttpParameters()
let url = NSURL(string: "\(url)?\(parameterString)")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error -> \(error)")
completionHandler(data: nil, response: nil, error: error)
}else{
completionHandler(data: data, response: response, error: nil)
}
}
task.resume()
}
}
extension String {
/// Percent escapes values to be added to a URL query as specified in RFC 3986
///
/// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Returns percent-escaped string.
func stringByAddingPercentEncodingForURLQueryValue() -> String? {
let allowedCharacters = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
return self.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters)
}
}
extension Dictionary {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// This percent escapes in compliance with RFC 3986
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
let parameterArray = self.map { (key, value) -> String in
let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (String(value)).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return parameterArray.joinWithSeparator("&")
}
}
|
mit
|
3314572243a9c8341afded90d3103a0b
| 32.87037 | 159 | 0.603062 | 4.997268 | false | false | false | false |
alvarozizou/Noticias-Leganes-iOS
|
Pods/Kingfisher/Sources/General/Deprecated.swift
|
2
|
28870
|
//
// Deprecated.swift
// Kingfisher
//
// Created by onevcat on 2018/09/28.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
#elseif canImport(UIKit)
import UIKit
#endif
// MARK: - Deprecated
extension KingfisherWrapper where Base: KFCrossPlatformImage {
@available(*, deprecated, message:
"Will be removed soon. Pass parameters with `ImageCreatingOptions`, use `image(with:options:)` instead.")
public static func image(
data: Data,
scale: CGFloat,
preloadAllAnimationData: Bool,
onlyFirstFrame: Bool) -> KFCrossPlatformImage?
{
let options = ImageCreatingOptions(
scale: scale,
duration: 0.0,
preloadAll: preloadAllAnimationData,
onlyFirstFrame: onlyFirstFrame)
return KingfisherWrapper.image(data: data, options: options)
}
@available(*, deprecated, message:
"Will be removed soon. Pass parameters with `ImageCreatingOptions`, use `animatedImage(with:options:)` instead.")
public static func animated(
with data: Data,
scale: CGFloat = 1.0,
duration: TimeInterval = 0.0,
preloadAll: Bool,
onlyFirstFrame: Bool = false) -> KFCrossPlatformImage?
{
let options = ImageCreatingOptions(
scale: scale, duration: duration, preloadAll: preloadAll, onlyFirstFrame: onlyFirstFrame)
return animatedImage(data: data, options: options)
}
}
@available(*, deprecated, message: "Will be removed soon. Use `Result<RetrieveImageResult>` based callback instead")
public typealias CompletionHandler =
((_ image: KFCrossPlatformImage?, _ error: NSError?, _ cacheType: CacheType, _ imageURL: URL?) -> Void)
@available(*, deprecated, message: "Will be removed soon. Use `Result<ImageLoadingResult>` based callback instead")
public typealias ImageDownloaderCompletionHandler =
((_ image: KFCrossPlatformImage?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> Void)
// MARK: - Deprecated
@available(*, deprecated, message: "Will be removed soon. Use `DownloadTask` to cancel a task.")
extension RetrieveImageTask {
@available(*, deprecated, message: "RetrieveImageTask.empty will be removed soon. Use `nil` to represent a no task.")
public static let empty = RetrieveImageTask()
}
// MARK: - Deprecated
extension KingfisherManager {
/// Get an image with resource.
/// If `.empty` is used as `options`, Kingfisher will seek the image in memory and disk first.
/// If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`.
/// These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
///
/// - Parameters:
/// - resource: Resource object contains information such as `cacheKey` and `downloadURL`.
/// - options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
/// - completionHandler: Called when the whole retrieving process finished.
/// - Returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
@available(*, deprecated, message: "Use `Result` based callback instead.")
@discardableResult
public func retrieveImage(with resource: Resource,
options: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> DownloadTask?
{
return retrieveImage(with: resource, options: options, progressBlock: progressBlock) {
result in
switch result {
case .success(let value): completionHandler?(value.image, nil, value.cacheType, value.source.url)
case .failure(let error): completionHandler?(nil, error as NSError, .none, resource.downloadURL)
}
}
}
}
// MARK: - Deprecated
extension ImageDownloader {
@available(*, deprecated, message: "Use `Result` based callback instead.")
@discardableResult
open func downloadImage(with url: URL,
retrieveImageTask: RetrieveImageTask? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: ImageDownloaderProgressBlock? = nil,
completionHandler: ImageDownloaderCompletionHandler?) -> DownloadTask?
{
return downloadImage(with: url, options: options, progressBlock: progressBlock) {
result in
switch result {
case .success(let value): completionHandler?(value.image, nil, value.url, value.originalData)
case .failure(let error): completionHandler?(nil, error as NSError, nil, nil)
}
}
}
}
@available(*, deprecated, message: "RetrieveImageDownloadTask is removed. Use `DownloadTask` to cancel a task.")
public struct RetrieveImageDownloadTask {
}
@available(*, deprecated, message: "RetrieveImageTask is removed. Use `DownloadTask` to cancel a task.")
public final class RetrieveImageTask {
}
@available(*, deprecated, message: "Use `DownloadProgressBlock` instead.", renamed: "DownloadProgressBlock")
public typealias ImageDownloaderProgressBlock = DownloadProgressBlock
#if !os(watchOS)
// MARK: - Deprecated
extension KingfisherWrapper where Base: KFCrossPlatformImageView {
@available(*, deprecated, message: "Use `Result` based callback instead.")
@discardableResult
public func setImage(with resource: Resource?,
placeholder: Placeholder? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler?) -> DownloadTask?
{
return setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock) {
result in
switch result {
case .success(let value):
completionHandler?(value.image, nil, value.cacheType, value.source.url)
case .failure(let error):
completionHandler?(nil, error as NSError, .none, nil)
}
}
}
}
#endif
#if canImport(UIKit) && !os(watchOS)
// MARK: - Deprecated
extension KingfisherWrapper where Base: UIButton {
@available(*, deprecated, message: "Use `Result` based callback instead.")
@discardableResult
public func setImage(
with resource: Resource?,
for state: UIControl.State,
placeholder: UIImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler?) -> DownloadTask?
{
return setImage(
with: resource,
for: state,
placeholder: placeholder,
options: options,
progressBlock: progressBlock)
{
result in
switch result {
case .success(let value):
completionHandler?(value.image, nil, value.cacheType, value.source.url)
case .failure(let error):
completionHandler?(nil, error as NSError, .none, nil)
}
}
}
@available(*, deprecated, message: "Use `Result` based callback instead.")
@discardableResult
public func setBackgroundImage(
with resource: Resource?,
for state: UIControl.State,
placeholder: UIImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler?) -> DownloadTask?
{
return setBackgroundImage(
with: resource,
for: state,
placeholder: placeholder,
options: options,
progressBlock: progressBlock)
{
result in
switch result {
case .success(let value):
completionHandler?(value.image, nil, value.cacheType, value.source.url)
case .failure(let error):
completionHandler?(nil, error as NSError, .none, nil)
}
}
}
}
#endif
#if os(watchOS)
import WatchKit
// MARK: - Deprecated
extension KingfisherWrapper where Base: WKInterfaceImage {
@available(*, deprecated, message: "Use `Result` based callback instead.")
@discardableResult
public func setImage(_ resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler?) -> DownloadTask?
{
return setImage(
with: resource,
placeholder: placeholder,
options: options,
progressBlock: progressBlock)
{
result in
switch result {
case .success(let value):
completionHandler?(value.image, nil, value.cacheType, value.source.url)
case .failure(let error):
completionHandler?(nil, error as NSError, .none, nil)
}
}
}
}
#endif
#if os(macOS)
// MARK: - Deprecated
extension KingfisherWrapper where Base: NSButton {
@discardableResult
@available(*, deprecated, message: "Use `Result` based callback instead.")
public func setImage(with resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler?) -> DownloadTask?
{
return setImage(
with: resource,
placeholder: placeholder,
options: options,
progressBlock: progressBlock)
{
result in
switch result {
case .success(let value):
completionHandler?(value.image, nil, value.cacheType, value.source.url)
case .failure(let error):
completionHandler?(nil, error as NSError, .none, nil)
}
}
}
@discardableResult
@available(*, deprecated, message: "Use `Result` based callback instead.")
public func setAlternateImage(with resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler?) -> DownloadTask?
{
return setAlternateImage(
with: resource,
placeholder: placeholder,
options: options,
progressBlock: progressBlock)
{
result in
switch result {
case .success(let value):
completionHandler?(value.image, nil, value.cacheType, value.source.url)
case .failure(let error):
completionHandler?(nil, error as NSError, .none, nil)
}
}
}
}
#endif
// MARK: - Deprecated
extension ImageCache {
/// The largest cache cost of memory cache. The total cost is pixel count of
/// all cached images in memory.
/// Default is unlimited. Memory cache will be purged automatically when a
/// memory warning notification is received.
@available(*, deprecated, message: "Use `memoryStorage.config.totalCostLimit` instead.",
renamed: "memoryStorage.config.totalCostLimit")
open var maxMemoryCost: Int {
get { return memoryStorage.config.totalCostLimit }
set { memoryStorage.config.totalCostLimit = newValue }
}
/// The default DiskCachePathClosure
@available(*, deprecated, message: "Not needed anymore.")
public final class func defaultDiskCachePathClosure(path: String?, cacheName: String) -> String {
let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
return (dstPath as NSString).appendingPathComponent(cacheName)
}
/// The default file extension appended to cached files.
@available(*, deprecated, message: "Use `diskStorage.config.pathExtension` instead.",
renamed: "diskStorage.config.pathExtension")
open var pathExtension: String? {
get { return diskStorage.config.pathExtension }
set { diskStorage.config.pathExtension = newValue }
}
///The disk cache location.
@available(*, deprecated, message: "Use `diskStorage.directoryURL.absoluteString` instead.",
renamed: "diskStorage.directoryURL.absoluteString")
public var diskCachePath: String {
return diskStorage.directoryURL.absoluteString
}
/// The largest disk size can be taken for the cache. It is the total
/// allocated size of cached files in bytes.
/// Default is no limit.
@available(*, deprecated, message: "Use `diskStorage.config.sizeLimit` instead.",
renamed: "diskStorage.config.sizeLimit")
open var maxDiskCacheSize: UInt {
get { return UInt(diskStorage.config.sizeLimit) }
set { diskStorage.config.sizeLimit = newValue }
}
@available(*, deprecated, message: "Use `diskStorage.cacheFileURL(forKey:).path` instead.",
renamed: "diskStorage.cacheFileURL(forKey:)")
open func cachePath(forComputedKey key: String) -> String {
return diskStorage.cacheFileURL(forKey: key).path
}
/**
Get an image for a key from disk.
- parameter key: Key for the image.
- parameter options: Options of retrieving image. If you need to retrieve an image which was
stored with a specified `ImageProcessor`, pass the processor in the option too.
- returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
@available(*, deprecated,
message: "Use `Result` based `retrieveImageInDiskCache(forKey:options:callbackQueue:completionHandler:)` instead.",
renamed: "retrieveImageInDiskCache(forKey:options:callbackQueue:completionHandler:)")
open func retrieveImageInDiskCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> KFCrossPlatformImage? {
let options = KingfisherParsedOptionsInfo(options ?? .empty)
let computedKey = key.computedKey(with: options.processor.identifier)
do {
if let data = try diskStorage.value(forKey: computedKey, extendingExpiration: options.diskCacheAccessExtendingExpiration) {
return options.cacheSerializer.image(with: data, options: options)
}
} catch {}
return nil
}
@available(*, deprecated,
message: "Use `Result` based `retrieveImage(forKey:options:callbackQueue:completionHandler:)` instead.",
renamed: "retrieveImage(forKey:options:callbackQueue:completionHandler:)")
open func retrieveImage(forKey key: String,
options: KingfisherOptionsInfo?,
completionHandler: ((KFCrossPlatformImage?, CacheType) -> Void)?)
{
retrieveImage(
forKey: key,
options: options,
callbackQueue: .dispatch((options ?? .empty).callbackDispatchQueue))
{
result in
do {
let value = try result.get()
completionHandler?(value.image, value.cacheType)
} catch {
completionHandler?(nil, .none)
}
}
}
/// The longest time duration in second of the cache being stored in disk.
/// Default is 1 week (60 * 60 * 24 * 7 seconds).
/// Setting this to a negative value will make the disk cache never expiring.
@available(*, deprecated, message: "Deprecated. Use `diskStorage.config.expiration` instead")
open var maxCachePeriodInSecond: TimeInterval {
get { return diskStorage.config.expiration.timeInterval }
set { diskStorage.config.expiration = newValue < 0 ? .never : .seconds(newValue) }
}
@available(*, deprecated, message: "Use `Result` based callback instead.")
open func store(_ image: KFCrossPlatformImage,
original: Data? = nil,
forKey key: String,
processorIdentifier identifier: String = "",
cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
toDisk: Bool = true,
completionHandler: (() -> Void)?)
{
store(
image,
original: original,
forKey: key,
processorIdentifier: identifier,
cacheSerializer: serializer,
toDisk: toDisk)
{
_ in
completionHandler?()
}
}
@available(*, deprecated, message: "Use the `Result`-based `calculateDiskStorageSize` instead.")
open func calculateDiskCacheSize(completion handler: @escaping ((_ size: UInt) -> Void)) {
calculateDiskStorageSize { result in
let size: UInt? = try? result.get()
handler(size ?? 0)
}
}
}
// MARK: - Deprecated
extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
/// The queue of callbacks should happen from Kingfisher.
@available(*, deprecated, message: "Use `callbackQueue` instead.", renamed: "callbackQueue")
public var callbackDispatchQueue: DispatchQueue {
return KingfisherParsedOptionsInfo(Array(self)).callbackQueue.queue
}
}
/// Error domain of Kingfisher
@available(*, deprecated, message: "Use `KingfisherError.domain` instead.", renamed: "KingfisherError.domain")
public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error"
/// Key will be used in the `userInfo` of `.invalidStatusCode`
@available(*, unavailable,
message: "Use `.invalidHTTPStatusCode` or `isInvalidResponseStatusCode` of `KingfisherError` instead for the status code.")
public let KingfisherErrorStatusCodeKey = "statusCode"
// MARK: - Deprecated
extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
/// The target `ImageCache` which is used.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `targetCache` instead.")
public var targetCache: ImageCache? {
return KingfisherParsedOptionsInfo(Array(self)).targetCache
}
/// The original `ImageCache` which is used.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `originalCache` instead.")
public var originalCache: ImageCache? {
return KingfisherParsedOptionsInfo(Array(self)).originalCache
}
/// The `ImageDownloader` which is specified.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `downloader` instead.")
public var downloader: ImageDownloader? {
return KingfisherParsedOptionsInfo(Array(self)).downloader
}
/// Member for animation transition when using UIImageView.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `transition` instead.")
public var transition: ImageTransition {
return KingfisherParsedOptionsInfo(Array(self)).transition
}
/// A `Float` value set as the priority of image download task. The value for it should be
/// between 0.0~1.0.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `downloadPriority` instead.")
public var downloadPriority: Float {
return KingfisherParsedOptionsInfo(Array(self)).downloadPriority
}
/// Whether an image will be always downloaded again or not.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `forceRefresh` instead.")
public var forceRefresh: Bool {
return KingfisherParsedOptionsInfo(Array(self)).forceRefresh
}
/// Whether an image should be got only from memory cache or download.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `fromMemoryCacheOrRefresh` instead.")
public var fromMemoryCacheOrRefresh: Bool {
return KingfisherParsedOptionsInfo(Array(self)).fromMemoryCacheOrRefresh
}
/// Whether the transition should always happen or not.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `forceTransition` instead.")
public var forceTransition: Bool {
return KingfisherParsedOptionsInfo(Array(self)).forceTransition
}
/// Whether cache the image only in memory or not.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `cacheMemoryOnly` instead.")
public var cacheMemoryOnly: Bool {
return KingfisherParsedOptionsInfo(Array(self)).cacheMemoryOnly
}
/// Whether the caching operation will be waited or not.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `waitForCache` instead.")
public var waitForCache: Bool {
return KingfisherParsedOptionsInfo(Array(self)).waitForCache
}
/// Whether only load the images from cache or not.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `onlyFromCache` instead.")
public var onlyFromCache: Bool {
return KingfisherParsedOptionsInfo(Array(self)).onlyFromCache
}
/// Whether the image should be decoded in background or not.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `backgroundDecode` instead.")
public var backgroundDecode: Bool {
return KingfisherParsedOptionsInfo(Array(self)).backgroundDecode
}
/// Whether the image data should be all loaded at once if it is an animated image.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `preloadAllAnimationData` instead.")
public var preloadAllAnimationData: Bool {
return KingfisherParsedOptionsInfo(Array(self)).preloadAllAnimationData
}
/// The `CallbackQueue` on which completion handler should be invoked.
/// If not set in the options, `.mainCurrentOrAsync` will be used.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `callbackQueue` instead.")
public var callbackQueue: CallbackQueue {
return KingfisherParsedOptionsInfo(Array(self)).callbackQueue
}
/// The scale factor which should be used for the image.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `scaleFactor` instead.")
public var scaleFactor: CGFloat {
return KingfisherParsedOptionsInfo(Array(self)).scaleFactor
}
/// The `ImageDownloadRequestModifier` will be used before sending a download request.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `requestModifier` instead.")
public var modifier: ImageDownloadRequestModifier? {
return KingfisherParsedOptionsInfo(Array(self)).requestModifier
}
/// `ImageProcessor` for processing when the downloading finishes.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `processor` instead.")
public var processor: ImageProcessor {
return KingfisherParsedOptionsInfo(Array(self)).processor
}
/// `ImageModifier` for modifying right before the image is displayed.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `imageModifier` instead.")
public var imageModifier: ImageModifier? {
return KingfisherParsedOptionsInfo(Array(self)).imageModifier
}
/// `CacheSerializer` to convert image to data for storing in cache.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `cacheSerializer` instead.")
public var cacheSerializer: CacheSerializer {
return KingfisherParsedOptionsInfo(Array(self)).cacheSerializer
}
/// Keep the existing image while setting another image to an image view.
/// Or the placeholder will be used while downloading.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `keepCurrentImageWhileLoading` instead.")
public var keepCurrentImageWhileLoading: Bool {
return KingfisherParsedOptionsInfo(Array(self)).keepCurrentImageWhileLoading
}
/// Whether the options contains `.onlyLoadFirstFrame`.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `onlyLoadFirstFrame` instead.")
public var onlyLoadFirstFrame: Bool {
return KingfisherParsedOptionsInfo(Array(self)).onlyLoadFirstFrame
}
/// Whether the options contains `.cacheOriginalImage`.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `cacheOriginalImage` instead.")
public var cacheOriginalImage: Bool {
return KingfisherParsedOptionsInfo(Array(self)).cacheOriginalImage
}
/// The image which should be used when download image request fails.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `onFailureImage` instead.")
public var onFailureImage: Optional<KFCrossPlatformImage?> {
return KingfisherParsedOptionsInfo(Array(self)).onFailureImage
}
/// Whether the `ImagePrefetcher` should load images to memory in an aggressive way or not.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `alsoPrefetchToMemory` instead.")
public var alsoPrefetchToMemory: Bool {
return KingfisherParsedOptionsInfo(Array(self)).alsoPrefetchToMemory
}
/// Whether the disk storage file loading should happen in a synchronous behavior or not.
@available(*, deprecated,
message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `loadDiskFileSynchronously` instead.")
public var loadDiskFileSynchronously: Bool {
return KingfisherParsedOptionsInfo(Array(self)).loadDiskFileSynchronously
}
}
/// The default modifier.
/// It does nothing and returns the image as is.
@available(*, deprecated, message: "Use `nil` in KingfisherOptionsInfo to indicate no modifier.")
public struct DefaultImageModifier: ImageModifier {
/// A default `DefaultImageModifier` which can be used everywhere.
public static let `default` = DefaultImageModifier()
private init() {}
/// Modifies an input `Image`. See `ImageModifier` protocol for more.
public func modify(_ image: KFCrossPlatformImage) -> KFCrossPlatformImage { return image }
}
|
mit
|
870232ed48a246d71a5808b4994a0be9
| 43.143731 | 135 | 0.674091 | 5.377165 | false | false | false | false |
milseman/swift
|
stdlib/public/SDK/Foundation/NSExpression.swift
|
16
|
1036
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
extension NSExpression {
// + (NSExpression *) expressionWithFormat:(NSString *)expressionFormat, ...;
public
convenience init(format expressionFormat: String, _ args: CVarArg...) {
let va_args = getVaList(args)
self.init(format: expressionFormat, arguments: va_args)
}
}
extension NSExpression {
public convenience init<Root, Value>(forKeyPath keyPath: KeyPath<Root, Value>) {
self.init(forKeyPath: _bridgeKeyPathToString(keyPath))
}
}
|
apache-2.0
|
4634f9101b72521b2654977fcfc6c97a
| 36 | 84 | 0.612934 | 4.933333 | false | false | false | false |
yeziahehe/Gank
|
Pods/LeanCloud/Sources/Storage/FileUploader.swift
|
1
|
19846
|
//
// FileUploader.swift
// LeanCloud
//
// Created by Tianyong Tang on 2018/9/19.
// Copyright © 2018 LeanCloud. All rights reserved.
//
import Foundation
import Alamofire
#if canImport(MobileCoreServices)
import MobileCoreServices
#endif
/**
File uploader.
*/
class FileUploader {
/// The file to be uploaded.
let file: LCFile
/// The file payload to be uploaded.
let payload: LCFile.Payload
/**
Create file uploader with file.
- parameter file: The file to be uploaded.
- parameter payload: The file payload to be uploaded.
*/
init(file: LCFile, payload: LCFile.Payload) {
self.file = file
self.payload = payload
}
/// The HTTP client for touching file or other LeanCloud requests.
private lazy var httpClient = HTTPClient.default
/// Session manager for uploading file.
private lazy var sessionManager: SessionManager = {
let sessionManager = SessionManager(configuration: .default)
sessionManager.startRequestsImmediately = false
return sessionManager
}()
/**
File tokens.
*/
private struct FileTokens {
/**
File hosting provider.
*/
enum Provider: String {
case qiniu
case qcloud
case s3
}
let provider: Provider
let uploadingURLString: String
let token: String
let mimeType: String?
init(plainTokens: LCDictionary) throws {
guard
let providerString = plainTokens["provider"]?.stringValue,
let provider = Provider(rawValue: providerString)
else {
throw LCError(code: .malformedData, reason: "Unknown file hosting provider.")
}
guard let uploadingURLString = plainTokens["upload_url"]?.stringValue else {
throw LCError(code: .malformedData, reason: "Uploading URL not found.")
}
guard let token = plainTokens["token"]?.stringValue else {
throw LCError(code: .malformedData, reason: "Uploading token not found.")
}
let mimeType = plainTokens["mime_type"]?.stringValue
self.provider = provider
self.uploadingURLString = uploadingURLString
self.token = token
self.mimeType = mimeType
}
}
/**
File attributes.
*/
private struct FileAttributes {
/// File payload.
let payload: LCFile.Payload
/// File name.
let name: String
/// File size.
let size: UInt64
/// The resource key.
/// Strictly speaking, it's not a file attribute.
let resourceKey: String
/// File mime type.
let mimeType: String
/// The default MIME type.
private static let defaultMIMEType = "application/octet-stream"
/**
Inspect file attributes.
- parameter file: The file to be uploaded.
- parameter payload: The file payload to be uploaded.
*/
init(file: LCFile, payload: LCFile.Payload) throws {
let filename = file.name?.value
let mimeType = file.mimeType?.value
let resourceKey = FileAttributes.getResourceKey(filename: filename)
switch payload {
case .data(let data):
self.name = filename ?? resourceKey
self.size = UInt64(data.count)
self.resourceKey = FileAttributes.getResourceKey(filename: filename)
if let mimeType = mimeType {
self.mimeType = mimeType
} else if let mimeType = FileAttributes.getMIMEType(filename: name) {
self.mimeType = mimeType
} else {
self.mimeType = FileAttributes.defaultMIMEType
}
case .fileURL(let fileURL):
let filename = filename ?? fileURL.lastPathComponent
self.name = filename
self.size = try FileAttributes.getFileSize(fileURL: fileURL)
self.resourceKey = FileAttributes.getResourceKey(filename: filename)
// It might be a bit odd that, unlike name, we detect MIME type from fileURL firstly.
if let mimeType = mimeType {
self.mimeType = mimeType
} else if let mimeType = try FileAttributes.getMIMEType(fileURL: fileURL) {
self.mimeType = mimeType
} else if let mimeType = FileAttributes.getMIMEType(filename: name) {
self.mimeType = mimeType
} else {
self.mimeType = FileAttributes.defaultMIMEType
}
}
self.payload = payload
}
static private func validate<T>(fileURL url: URL, body: (URL) throws -> T) throws -> T {
let fileManager = FileManager.default
guard fileManager.isReadableFile(atPath: url.path) else {
throw LCError(code: .notFound, reason: "File not found.")
}
return try body(url)
}
static private func getFileSize(fileURL url: URL) throws -> UInt64 {
return try validate(fileURL: url) { url in
let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
guard let fileSize = attributes[.size] as? UInt64 else {
throw LCError(code: .notFound, reason: "Failed to get file size.")
}
return fileSize
}
}
/**
Generate resource key for file name.
It will generate a new random resource key everytime.
- parameter filename: The file name.
*/
static private func getResourceKey(filename: String?) -> String {
let key = Utility.uuid()
guard let filename = filename else {
return key
}
let filenameExtension = (filename as NSString).pathExtension
if filenameExtension.isEmpty {
return key
} else {
return "\(key).\(filenameExtension)"
}
}
static private func getMIMEType(filenameExtension: String) -> String? {
if filenameExtension.isEmpty {
return nil
} else if
let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, filenameExtension as CFString, nil)?.takeRetainedValue(),
let mimeType = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue()
{
return mimeType as String
} else {
return nil
}
}
static private func getMIMEType(filename: String?) -> String? {
guard let filename = filename else {
return nil
}
let filenameExtension = (filename as NSString).pathExtension
let mimeType = getMIMEType(filenameExtension: filenameExtension)
return mimeType
}
static private func getMIMEType(fileURL url: URL) throws -> String? {
return try validate(fileURL: url) { url in
getMIMEType(filenameExtension: url.pathExtension)
}
}
}
private func createTouchParameters(file: LCFile, attributes: FileAttributes) -> [String: Any] {
var parameters: [String: Any]
// Fuse file properties into parameters.
if let properties = file.dictionary.jsonValue as? [String: Any] {
parameters = properties
} else {
parameters = [:]
}
// Add extra file related attributes to parameters.
parameters["key"] = attributes.resourceKey
parameters["name"] = attributes.name
parameters["mime_type"] = attributes.mimeType
var metaData: [String: Any] = [:]
metaData["size"] = attributes.size
metaData["mime_type"] = attributes.mimeType
parameters["metaData"] = metaData
return parameters
}
private struct TouchResult {
let plainTokens: LCDictionary
let typedTokens: FileTokens
}
private func touch(
parameters: [String: Any],
completion: @escaping (LCGenericResult<TouchResult>) -> Void) -> LCRequest
{
return httpClient.request(.post, "fileTokens", parameters: parameters) { response in
let dictionaryResult = LCValueResult<LCDictionary>(response: response)
switch dictionaryResult {
case .success(let plainTokens):
do {
let typedTokens = try FileTokens(plainTokens: plainTokens)
let value = TouchResult(plainTokens: plainTokens, typedTokens: typedTokens)
completion(.success(value: value))
} catch let error {
completion(.failure(error: LCError(error: error)))
}
case .failure(let error):
completion(.failure(error: error))
}
}
}
private func writeToQiniu(
tokens: FileTokens,
attributes: FileAttributes,
progress: @escaping (Double) -> Void,
completion: @escaping (LCBooleanResult) -> Void) -> LCRequest
{
let token = tokens.token
let resourceKey = attributes.resourceKey
let payload = self.payload
let mimeType = attributes.mimeType
let fileName = attributes.name
var tokenData: Data
var resourceKeyData: Data
do {
if let aKeyData = resourceKey.data(using: .utf8) {
resourceKeyData = aKeyData
} else {
throw LCError(code: .malformedData, reason: "Invalid resource key.")
}
if let aTokenData = token.data(using: .utf8) {
tokenData = aTokenData
} else {
throw LCError(code: .malformedData, reason: "Invalid uploading token.")
}
} catch let error {
return httpClient.request(error: error) { result in
completion(result)
}
}
let sequenceRequest = LCSequenceRequest()
sessionManager.upload(
multipartFormData: { multipartFormData in
/*
Qiniu multipart format:
https://developer.qiniu.com/kodo/manual/1272/form-upload
*/
multipartFormData.append(tokenData, withName: "token")
multipartFormData.append(resourceKeyData, withName: "key")
switch payload {
case .data(let data):
multipartFormData.append(data, withName: "file", fileName: fileName, mimeType: mimeType)
case .fileURL(let fileURL):
multipartFormData.append(fileURL, withName: "file", fileName: fileName, mimeType: mimeType)
}
},
to: tokens.uploadingURLString,
method: .post, // We assume that Qiniu *always* use POST method to upload file.
encodingCompletion: { result in
switch result {
case let .success(request, _, _):
request.validate()
request.uploadProgress { object in
progress(object.fractionCompleted)
}
request.response { response in
if let error = response.error {
completion(.failure(error: LCError(error: error)))
} else {
completion(.success)
}
}
sequenceRequest.setCurrentRequest(request)
request.resume()
case let .failure(error):
completion(.failure(error: LCError(error: error)))
}
})
return sequenceRequest
}
private func writeToQCloud(
tokens: FileTokens,
attributes: FileAttributes,
progress: @escaping (Double) -> Void,
completion: @escaping (LCBooleanResult) -> Void) -> LCRequest
{
let payload = self.payload
let mimeType = attributes.mimeType
let fileName = attributes.name
let sequenceRequest = LCSequenceRequest()
sessionManager.upload(
multipartFormData: { multipartFormData in
switch payload {
case .data(let data):
multipartFormData.append(data, withName: "filecontent", fileName: fileName, mimeType: mimeType)
case .fileURL(let fileURL):
multipartFormData.append(fileURL, withName: "filecontent", fileName: fileName, mimeType: mimeType)
}
multipartFormData.append("upload".data(using: .utf8)!, withName: "op")
},
to: tokens.uploadingURLString,
method: .post, // We assume that Qiniu *always* use POST method to upload file.
headers: ["Authorization": tokens.token],
encodingCompletion: { result in
switch result {
case let .success(request, _, _):
request.validate()
request.uploadProgress { object in
progress(object.fractionCompleted)
}
request.response { response in
if let error = response.error {
completion(.failure(error: LCError(error: error)))
} else {
completion(.success)
}
}
sequenceRequest.setCurrentRequest(request)
request.resume()
case let .failure(error):
completion(.failure(error: LCError(error: error)))
}
})
return sequenceRequest
}
private func writeToS3(
tokens: FileTokens,
attributes: FileAttributes,
progress: @escaping (Double) -> Void,
completion: @escaping (LCBooleanResult) -> Void) -> LCRequest
{
var uploadRequest: UploadRequest
let uploadingURLString = tokens.uploadingURLString
var headers: [String: String] = [:]
headers["Content-Type"] = attributes.mimeType
headers["Content-Length"] = String(attributes.size)
headers["Cache-Control"] = "public, max-age=31536000"
switch payload {
case .data(let data):
uploadRequest = sessionManager.upload(data, to: uploadingURLString, method: .put, headers: headers)
case .fileURL(let fileURL):
uploadRequest = sessionManager.upload(fileURL, to: uploadingURLString, method: .put, headers: headers)
}
uploadRequest.validate()
uploadRequest.uploadProgress { object in
progress(object.fractionCompleted)
}
uploadRequest.response { response in
if let error = response.error {
completion(.failure(error: LCError(error: error)))
} else {
completion(.success)
}
}
uploadRequest.resume()
let request = LCSingleRequest(request: uploadRequest)
return request
}
private func write(
tokens: FileTokens,
attributes: FileAttributes,
progress: @escaping (Double) -> Void,
completion: @escaping (LCBooleanResult) -> Void) -> LCRequest
{
switch tokens.provider {
case .qiniu:
return writeToQiniu(tokens: tokens, attributes: attributes, progress: progress, completion: completion)
case .qcloud:
return writeToQCloud(tokens: tokens, attributes: attributes, progress: progress, completion: completion)
case .s3:
return writeToS3(tokens: tokens, attributes: attributes, progress: progress, completion: completion)
}
}
private func feedback(
result: LCBooleanResult,
tokens: FileTokens)
{
var parameters: [String: Any] = [:]
parameters["token"] = tokens.token
switch result {
case .success:
parameters["result"] = true
case .failure:
parameters["result"] = false
}
_ = httpClient.request(.post, "fileCallback", parameters: parameters) { response in
/* Ignore response of file feedback. */
}
}
private func close(
result: LCBooleanResult,
tokens: LCDictionary,
touchParameters: [String: Any])
{
switch result {
case .success:
let properties = LCDictionary(tokens)
// Touch parameters are also part of propertise.
do {
let dictionary = try LCDictionary(unsafeObject: touchParameters)
dictionary.forEach { (key, value) in
properties.set(key, value)
}
} catch let error {
Logger.shared.error(error)
}
// Remove security-sensitive and pointless information.
properties.removeValue(forKey: "token")
properties.removeValue(forKey: "access_key")
properties.removeValue(forKey: "access_token")
properties.removeValue(forKey: "upload_url")
properties.forEach { element in
file.update(element.key, element.value)
}
case .failure:
break
}
}
/**
Upload file in background.
- parameter progress: The progress handler.
- parameter completion: The completion handler.
- returns: The upload request.
*/
func upload(
progress: @escaping (Double) -> Void,
completion: @escaping (LCBooleanResult) -> Void) -> LCRequest
{
// If objectId exists, we think that the file has already been uploaded.
if let _ = file.objectId {
return httpClient.request(object: LCBooleanResult.success) { result in
completion(result)
}
}
var attributes: FileAttributes
do {
attributes = try FileAttributes(file: file, payload: payload)
} catch let error {
return httpClient.request(error: error) { result in
completion(result)
}
}
let sequenceRequest = LCSequenceRequest()
let touchParameters = createTouchParameters(file: file, attributes: attributes)
// Before upload resource, we have to touch file first.
let touchRequest = touch(parameters: touchParameters) { result in
switch result {
case .success(let value):
let plainTokens = value.plainTokens
let typedTokens = value.typedTokens
// If file is touched, write resource to third-party file provider.
let writeRequest = self.write(tokens: typedTokens, attributes: attributes, progress: progress) { result in
self.close(result: result, tokens: plainTokens, touchParameters: touchParameters)
self.feedback(result: result, tokens: typedTokens)
completion(result)
}
sequenceRequest.setCurrentRequest(writeRequest)
case .failure(let error):
completion(.failure(error: error))
}
}
sequenceRequest.setCurrentRequest(touchRequest)
return sequenceRequest
}
}
|
gpl-3.0
|
064137c2971a8a6606d6e49c6aab1cf4
| 32.241206 | 151 | 0.561602 | 5.408831 | false | false | false | false |
chadoneba/MTools
|
MTools/Classes/Route/MainRouter.swift
|
1
|
2028
|
import Foundation
import UIKit
// Протокол для обобщения разных подклассов презентеров
public protocol RouterProtocol:NSObjectProtocol {
var delegate:PresenterProtocol? { get set }
}
// Основной класс организации роутинга
public class MainRouter {
static let instance:MainRouter = MainRouter()
public static var TheInstance : MainRouter {
get { return instance }
}
private var storyboard = "Main"
public func setStoryboard(name:String!) {
self.storyboard = name
}
// Вся магия роутинга. Забирает из сториборда контроллер по ID и кастирует его по T из UIViewController
// Назначает контроллер делегатом presenter, и Презентер назначает свойству презентер контроллера
// Возвращает настроенный контроллер для использования в любом типе перехода
public func getController<T:UIViewController ,U:RouterProtocol>(type_ctr:T, presenter:inout U)->T where T:PresenterProtocol {
let controller = getController(type_ctr: type_ctr)
presenter.delegate = controller
controller.set_presenter(presenter_par: presenter)
return controller
}
public func getController<T:UIViewController>(type_ctr:T)->T where T:PresenterProtocol {
let story = UIStoryboard.init(name: self.storyboard, bundle: nil)
let controller = story.instantiateViewController(withIdentifier: type_ctr.get_storyboard_name()) as! T
return controller
}
public func getController<T:UIViewController>(type:String)->T {
let story = UIStoryboard.init(name: self.storyboard, bundle: nil)
let controller = story.instantiateViewController(withIdentifier: type) as! T
return controller
}
}
|
mit
|
5eaf7c0db0e648c65955a05aeaa788fb
| 31.296296 | 129 | 0.708716 | 4.084309 | false | false | false | false |
evnaz/Design-Patterns-In-Swift
|
source-cn/behavioral/memento.swift
|
2
|
2084
|
/*:
💾 备忘录(Memento)
--------------
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态
### 示例:
*/
typealias Memento = [String: String]
/*:
发起人(Originator)
*/
protocol MementoConvertible {
var memento: Memento { get }
init?(memento: Memento)
}
struct GameState: MementoConvertible {
private enum Keys {
static let chapter = "com.valve.halflife.chapter"
static let weapon = "com.valve.halflife.weapon"
}
var chapter: String
var weapon: String
init(chapter: String, weapon: String) {
self.chapter = chapter
self.weapon = weapon
}
init?(memento: Memento) {
guard let mementoChapter = memento[Keys.chapter],
let mementoWeapon = memento[Keys.weapon] else {
return nil
}
chapter = mementoChapter
weapon = mementoWeapon
}
var memento: Memento {
return [ Keys.chapter: chapter, Keys.weapon: weapon ]
}
}
/*:
管理者(Caretaker)
*/
enum CheckPoint {
private static let defaults = UserDefaults.standard
static func save(_ state: MementoConvertible, saveName: String) {
defaults.set(state.memento, forKey: saveName)
defaults.synchronize()
}
static func restore(saveName: String) -> Any? {
return defaults.object(forKey: saveName)
}
}
/*:
### 用法
*/
var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar")
gameState.chapter = "Anomalous Materials"
gameState.weapon = "Glock 17"
CheckPoint.save(gameState, saveName: "gameState1")
gameState.chapter = "Unforeseen Consequences"
gameState.weapon = "MP5"
CheckPoint.save(gameState, saveName: "gameState2")
gameState.chapter = "Office Complex"
gameState.weapon = "Crossbow"
CheckPoint.save(gameState, saveName: "gameState3")
if let memento = CheckPoint.restore(saveName: "gameState1") as? Memento {
let finalState = GameState(memento: memento)
dump(finalState)
}
|
gpl-3.0
|
ac610bacf37c97754fcff483fd9a48ae
| 22.216867 | 75 | 0.667878 | 3.548803 | false | false | false | false |
shahmishal/swift
|
test/ParseableInterface/where-clause.swift
|
1
|
1819
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -typecheck %s -emit-module-interface-path %t/main.swiftinterface -enable-library-evolution
// RUN: %FileCheck %s < %t/main.swiftinterface
// RUN: %target-build-swift %s -emit-module-interface-path %t/main.swiftinterface -enable-library-evolution
// RUN: %FileCheck %s < %t/main.swiftinterface
// RUN: %target-build-swift %s -emit-module-interface-path %t/main.swiftinterface -enable-library-evolution -wmo
// RUN: %FileCheck %s < %t/main.swiftinterface
// CHECK: import Swift
// CHECK: public struct Holder<Value> {
public struct Holder<Value> {
var value: Value
// CHECK-NEXT: public init(value: Value){{$}}
public init(value: Value) {
self.value = value
}
// CHECK-NEXT: public init<T>(_ value: T) where Value == Swift.AnyHashable, T : Swift.Hashable{{$}}
public init<T : Hashable>(_ value: T) where Value == AnyHashable {
self.value = value
}
// CHECK-NEXT: public struct Transform<Result> {
public struct Transform<Result> {
var fn: (Value) -> Result
// CHECK-NEXT: public init(fn: @escaping (Value) -> Result){{$}}
public init(fn: @escaping (Value) -> Result) {
self.fn = fn
}
// CHECK-NEXT: func transform(_ holder: main.Holder<Value>) -> Result{{$}}
public func transform(_ holder: Holder<Value>) -> Result {
return fn(holder.value)
}
// CHECK-NEXT: }
}
// CHECK-NEXT: }
}
// CHECK-NEXT: extension Holder.Transform where Value == Swift.Int {
extension Holder.Transform where Value == Int {
// CHECK-NEXT: public func negate(_ holder: main.Holder<Value>) -> Result{{$}}
public func negate(_ holder: Holder<Value>) -> Result {
return transform(Holder(value: -holder.value))
}
}
|
apache-2.0
|
ac7ae190144c2e707377123141d3356b
| 32.703704 | 121 | 0.633315 | 3.727459 | false | false | false | false |
sschiau/swift
|
test/expr/postfix/dot/init_ref_delegation.swift
|
1
|
20750
|
// RUN: %target-typecheck-verify-swift
// Tests for initializer delegation via self.init(...).
// Initializer delegation: classes
class C0 {
convenience init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
}
class C1 {
convenience init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
// Initializer delegation: structs
struct S0 {
init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
}
struct S1 {
init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
// Initializer delegation: enum
enum E0 {
case A
case B
init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
}
enum E1 {
case A
case B
init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
// Ill-formed initializer delegation: no matching constructor
class Z0 {
init() { // expected-error {{designated initializer for 'Z0' cannot delegate (with 'self.init'); did you mean this to be a convenience initializer?}} {{3-3=convenience }}
// expected-note @+2 {{delegation occurs here}}
self.init(5, 5) // expected-error{{cannot invoke 'Z0.init' with an argument list of type '(Int, Int)'}}
// expected-note @-1 {{overloads for 'Z0.init' exist with these partially matching parameter lists: (), (value: Double), (value: Int)}}
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
struct Z1 {
init() {
self.init(5, 5) // expected-error{{cannot invoke 'Z1.init' with an argument list of type '(Int, Int)'}}
// expected-note @-1 {{overloads for 'Z1.init' exist with these partially matching parameter lists: (), (value: Double), (value: Int)}}
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
enum Z2 {
case A
case B
init() {
self.init(5, 5) // expected-error{{cannot invoke 'Z2.init' with an argument list of type '(Int, Int)'}}
// expected-note @-1 {{overloads for 'Z2.init' exist with these partially matching parameter lists: (), (value: Double), (value: Int)}}
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
// Ill-formed initialization: wrong context.
class Z3 {
func f() {
self.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{5-5=type(of: }} {{9-9=)}}
}
init() { }
}
// 'init' is a static-ish member.
class Z4 {
init() {} // expected-note{{selected non-required initializer}}
convenience init(other: Z4) {
other.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{5-5=type(of: }} {{10-10=)}}
type(of: other).init() // expected-error{{must use a 'required' initializer}}
}
}
class Z5 : Z4 {
override init() { }
convenience init(other: Z5) {
other.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{5-5=type(of: }} {{10-10=)}}
}
}
// Ill-formed initialization: failure to call initializer.
class Z6 {
convenience init() {
var _ : () -> Z6 = self.init // expected-error{{partial application of 'self.init' initializer delegation is not allowed}}
}
init(other: Z6) { }
}
// Ill-formed initialization: both superclass and delegating.
class Z7Base { }
class Z7 : Z7Base {
override init() { }
init(b: Bool) {
if b { super.init() } // expected-note{{previous chaining call is here}}
else { self.init() } // expected-error{{initializer cannot both delegate ('self.init') and chain to a }}
}
}
struct RDar16603812 {
var i = 42
init() {}
func foo() {
self.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{7-7=type(of: }} {{11-11=)}}
type(of: self).init() // expected-warning{{result of 'RDar16603812' initializer is unused}}
}
}
class RDar16666631 {
var i: Int
var d: Double
var s: String
init(i: Int, d: Double, s: String) { // expected-note {{'init(i:d:s:)' declared here}}
self.i = i
self.d = d
self.s = s
}
convenience init(i: Int, s: String) {
self.init(i: i, d: 0.1, s: s)
}
}
let rdar16666631 = RDar16666631(i: 5, d: 6) // expected-error {{missing argument for parameter 's' in call}} {{43-43=, s: <#String#>}}
struct S {
init() {
let _ = S.init()
self.init()
let _ = self.init // expected-error{{partial application of 'self.init' initializer delegation is not allowed}}
}
}
class C {
convenience init() { // expected-note 11 {{selected non-required initializer 'init()'}}
self.init()
let _: C = self.init() // expected-error{{cannot convert value of type '()' to specified type 'C'}}
let _: () -> C = self.init // expected-error{{partial application of 'self.init' initializer delegation is not allowed}}
}
init(x: Int) {} // expected-note 11 {{selected non-required initializer 'init(x:)'}}
required init(required: Double) {}
}
class D: C {
override init(x: Int) {
super.init(x: x)
let _: C = super.init() // expected-error{{cannot convert value of type '()' to specified type 'C'}}
let _: () -> C = super.init // expected-error{{partial application of 'super.init' initializer chain is not allowed}}
}
func foo() {
self.init(x: 0) // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{5-5=type(of: }} {{9-9=)}}
}
func bar() {
super.init(x: 0) // expected-error{{'super.init' cannot be called outside of an initializer}}
}
class func zim() -> Self {
return self.init(required: 0)
}
class func zang() -> C {
return super.init(required: 0)
}
required init(required: Double) {}
}
func init_tests() {
var s = S.self
var s1 = s.init()
var ss1 = S.init()
var c: C.Type = D.self
var c1 = c.init(required: 0)
var c2 = c.init(x: 0) // expected-error{{'required' initializer}}
var c3 = c.init() // expected-error{{'required' initializer}}
var c1a = c.init(required: 0)
var c2a = c.init(x: 0) // expected-error{{'required' initializer}}
var c3a = c.init() // expected-error{{'required' initializer}}
var cf1: (Double) -> C = c.init
var cf2: (Int) -> C = c.init // expected-error{{'required' initializer}}
var cf3: () -> C = c.init // expected-error{{'required' initializer}}
var cs1 = C.init(required: 0)
var cs2 = C.init(x: 0)
var cs3 = C.init()
var csf1: (Double) -> C = C.init
var csf2: (Int) -> C = C.init
var csf3: () -> C = C.init
var cs1a = C(required: 0)
var cs2a = C(x: 0)
var cs3a = C()
var y = x.init() // expected-error{{use of unresolved identifier 'x'}}
}
protocol P {
init(proto: String)
}
func foo<T: C>(_ x: T, y: T.Type) where T: P {
var c1 = type(of: x).init(required: 0)
var c2 = type(of: x).init(x: 0) // expected-error{{'required' initializer}}
var c3 = type(of: x).init() // expected-error{{'required' initializer}}
var c4 = type(of: x).init(proto: "")
var cf1: (Double) -> T = type(of: x).init
var cf2: (Int) -> T = type(of: x).init // expected-error{{'required' initializer}}
var cf3: () -> T = type(of: x).init // expected-error{{'required' initializer}}
var cf4: (String) -> T = type(of: x).init
var c1a = type(of: x).init(required: 0)
var c2a = type(of: x).init(x: 0) // expected-error{{'required' initializer}}
var c3a = type(of: x).init() // expected-error{{'required' initializer}}
var c4a = type(of: x).init(proto: "")
var ci1 = x.init(required: 0) // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{13-13=type(of: }} {{14-14=)}}
var ci2 = x.init(x: 0) // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{13-13=type(of: }} {{14-14=)}}
var ci3 = x.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{13-13=type(of: }} {{14-14=)}}
var ci4 = x.init(proto: "") // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{13-13=type(of: }} {{14-14=)}}
var z = x
z.init(required: 0) // expected-error {{'init' is a member of the type; use assignment to initalize the value instead}} {{4-4= = }}
z.init(x: 0) // expected-error {{'init' is a member of the type; use assignment to initalize the value instead}} {{4-4= = }}
z.init() // expected-error {{'init' is a member of the type; use assignment to initalize the value instead}} {{4-4= = }}
z.init(proto: "") // expected-error {{'init' is a member of the type; use assignment to initalize the value instead}} {{4-4= = }}
var ci1a = z.init(required: 0) // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{14-14=type(of: }} {{15-15=)}}
var ci2a = z.init(x: 0) // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{14-14=type(of: }} {{15-15=)}}
var ci3a = z.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{14-14=type(of: }} {{15-15=)}}
var ci4a = z.init(proto: "") // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{14-14=type(of: }} {{15-15=)}}
var ci1b = x(required: 0) // expected-error{{cannot call value of non-function type 'T'}}
var ci2b = x(x: 0) // expected-error{{cannot call value of non-function type 'T'}}
var ci3b = x() // expected-error{{cannot call value of non-function type 'T'}}{{15-17=}}
var ci4b = x(proto: "") // expected-error{{cannot call value of non-function type 'T'}}
var cm1 = y.init(required: 0)
var cm2 = y.init(x: 0) // expected-error{{'required' initializer}}
var cm3 = y.init() // expected-error{{'required' initializer}}
var cm4 = y.init(proto: "")
var cm1a = y.init(required: 0)
var cm2a = y.init(x: 0) // expected-error{{'required' initializer}}
var cm3a = y.init() // expected-error{{'required' initializer}}
var cm4a = y.init(proto: "")
var cs1 = T.init(required: 0)
var cs2 = T.init(x: 0) // expected-error{{'required' initializer}}
var cs3 = T.init() // expected-error{{'required' initializer}}
var cs4 = T.init(proto: "")
var cs5 = T.init(notfound: "") // expected-error{{incorrect argument label in call (have 'notfound:', expected 'proto:')}}
var csf1: (Double) -> T = T.init
var csf2: (Int) -> T = T.init // expected-error{{'required' initializer}}
var csf3: () -> T = T.init // expected-error{{'required' initializer}}
var csf4: (String) -> T = T.init
var cs1a = T(required: 0)
var cs2a = T(x: 0) // expected-error{{'required' initializer}}
var cs3a = T() // expected-error{{'required' initializer}}
var cs4a = T(proto: "")
}
class TestOverloadSets {
convenience init() {
self.init(5, 5) // expected-error{{cannot invoke 'TestOverloadSets.init' with an argument list of type '(Int, Int)'}}
// expected-note @-1 {{overloads for 'TestOverloadSets.init' exist with these partially matching parameter lists: (), (a: Z0), (value: Double), (value: Int)}}
}
convenience init(a : Z0) {
self.init(42 as Int8) // expected-error{{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'TestOverloadSets.init' exist with these partially matching parameter lists: (a: Z0), (value: Double), (value: Int)}}
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
class TestNestedExpr {
init() {}
init?(fail: Bool) {}
init(error: Bool) throws {}
convenience init(a: Int) {
let x: () = self.init() // expected-error {{initializer delegation ('self.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
convenience init(b: Int) {
func use(_ x: ()) {}
use(self.init()) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(c: Int) {
_ = ((), self.init()) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(d: Int) {
let x: () = self.init(fail: true)! // expected-error {{initializer delegation ('self.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
convenience init(e: Int) {
func use(_ x: ()) {}
use(self.init(fail: true)!) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(f: Int) {
_ = ((), self.init(fail: true)!) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(g: Int) {
let x: () = try! self.init(error: true) // expected-error {{initializer delegation ('self.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
convenience init(h: Int) {
func use(_ x: ()) {}
use(try! self.init(error: true)) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(i: Int) {
_ = ((), try! self.init(error: true)) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(j: Int) throws {
_ = {
try self.init(error: true)
// expected-error@-1 {{initializer delegation ('self.init') cannot be nested in another expression}}
}
_ = {
do {
try self.init(error: true)
// expected-error@-1 {{initializer delegation ('self.init') cannot be nested in another expression}}
}
}
defer {
try! self.init(error: true)
// expected-error@-1 {{initializer delegation ('self.init') cannot be nested in another expression}}
}
func local() throws {
try self.init(error: true)
// expected-error@-1 {{initializer delegation ('self.init') cannot be nested in another expression}}
}
}
convenience init(k: Int) {
func use(_ x: Any...) {}
use(self.init()) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
}
class TestNestedExprSub : TestNestedExpr {
init(a: Int) {
let x: () = super.init() // expected-error {{initializer chaining ('super.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
init(b: Int) {
func use(_ x: ()) {}
use(super.init()) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(c: Int) {
_ = ((), super.init()) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(d: Int) {
let x: () = super.init(fail: true)! // expected-error {{initializer chaining ('super.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
init(e: Int) {
func use(_ x: ()) {}
use(super.init(fail: true)!) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(f: Int) {
_ = ((), super.init(fail: true)!) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(g: Int) {
let x: () = try! super.init(error: true) // expected-error {{initializer chaining ('super.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
init(h: Int) {
func use(_ x: ()) {}
use(try! super.init(error: true)) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(i: Int) {
_ = ((), try! super.init(error: true)) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(j: Int) {
func use(_ x: Any...) {}
use(super.init()) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
}
class TestOptionalTry {
init() throws {}
convenience init(a: Int) { // expected-note {{propagate the failure with 'init?'}} {{19-19=?}}
try? self.init() // expected-error {{a non-failable initializer cannot use 'try?' to delegate to another initializer}}
// expected-note@-1 {{force potentially-failing result with 'try!'}} {{5-9=try!}}
}
init?(fail: Bool) throws {}
convenience init(failA: Int) { // expected-note {{propagate the failure with 'init?'}} {{19-19=?}}
try? self.init(fail: true)! // expected-error {{a non-failable initializer cannot use 'try?' to delegate to another initializer}}
// expected-note@-1 {{force potentially-failing result with 'try!'}} {{5-9=try!}}
}
convenience init(failB: Int) { // expected-note {{propagate the failure with 'init?'}} {{19-19=?}}
try! self.init(fail: true) // expected-error {{a non-failable initializer cannot delegate to failable initializer 'init(fail:)' written with 'init?'}}
// expected-note@-1 {{force potentially-failing result with '!'}} {{31-31=!}}
}
convenience init(failC: Int) {
try! self.init(fail: true)! // okay
}
convenience init?(failD: Int) {
try? self.init(fail: true) // okay
}
convenience init?(failE: Int) {
try! self.init(fail: true) // okay
}
convenience init?(failF: Int) {
try! self.init(fail: true)! // okay
}
convenience init?(failG: Int) {
try? self.init(fail: true) // okay
}
}
class TestOptionalTrySub : TestOptionalTry {
init(a: Int) { // expected-note {{propagate the failure with 'init?'}} {{7-7=?}}
try? super.init() // expected-error {{a non-failable initializer cannot use 'try?' to chain to another initializer}}
// expected-note@-1 {{force potentially-failing result with 'try!'}} {{5-9=try!}}
}
}
struct X { init() {} }
func +(lhs: X, rhs: X) -> X { return lhs }
func testInsideOperator(x: X) {
x.init() + x // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{3-3=type(of: }} {{4-4=)}}
x + x.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{7-7=type(of: }} {{8-8=)}}
x.init() + x.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{3-3=type(of: }} {{4-4=)}}
// expected-error@-1 {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{14-14=type(of: }} {{15-15=)}}
}
struct Y {
var x: X
let x2: X
init() {
x.init() // expected-error {{'init' is a member of the type; use assignment to initalize the value instead}} {{6-6= = }}
foo(x.init()) // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{9-9=type(of: }} {{10-10=)}}
}
func foo(_: X) {}
func asFunctionReturn() -> X {
var a = X()
return a.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{12-12=type(of: }} {{13-13=)}}
}
}
struct MultipleMemberAccesses {
var y: Y
let y2: Y
init() {
y = Y()
y2 = Y()
y.x.init() // expected-error {{'init' is a member of the type; use assignment to initalize the value instead}} {{8-8= = }}
y2.x2.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{5-5=type(of: }} {{10-10=)}}
}
}
func sr10670() {
struct S {
init(_ x: inout String) {}
init(_ x: inout [Int]) {}
}
var a = 0
S.init(&a) // expected-error {{cannot invoke 'S.Type.init' with an argument list of type '(inout Int)'}}
// expected-note@-1 {{overloads for 'S.Type.init' exist with these partially matching parameter lists: (inout String), (inout [Int])}}
}
|
apache-2.0
|
14afe72cc0e3cdeac9816db5bfa6b354
| 36.18638 | 190 | 0.620675 | 3.361413 | false | false | false | false |
sschiau/swift
|
stdlib/public/Darwin/AppKit/NSEvent.swift
|
7
|
7676
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import AppKit
extension NSEvent {
public struct SpecialKey : RawRepresentable, Equatable, Hashable {
public init(rawValue: Int) {
self.rawValue = rawValue
}
public let rawValue: Int
public var unicodeScalar: Unicode.Scalar {
return Unicode.Scalar(rawValue)!
}
}
/// Returns nil if the receiver is not a "special" key event.
open var specialKey: SpecialKey? {
guard let unicodeScalars = charactersIgnoringModifiers?.unicodeScalars else {
return nil
}
guard unicodeScalars.count == 1 else {
return nil
}
guard let codePoint = unicodeScalars.first?.value else {
return nil
}
switch codePoint {
case 0x0003:
return .enter
case 0x0008:
return .backspace
case 0x0009:
return .tab
case 0x000a:
return .newline
case 0x000c:
return .formFeed
case 0x000d:
return .carriageReturn
case 0x0019:
return .backTab
case 0x007f:
return .delete
case 0x2028:
return .lineSeparator
case 0x2029:
return .paragraphSeparator
case 0xF700..<0xF900:
return SpecialKey(rawValue: Int(codePoint))
default:
return nil
}
}
}
extension NSEvent.SpecialKey {
static public let upArrow = NSEvent.SpecialKey(rawValue: 0xF700)
static public let downArrow = NSEvent.SpecialKey(rawValue: 0xF701)
static public let leftArrow = NSEvent.SpecialKey(rawValue: 0xF702)
static public let rightArrow = NSEvent.SpecialKey(rawValue: 0xF703)
static public let f1 = NSEvent.SpecialKey(rawValue: 0xF704)
static public let f2 = NSEvent.SpecialKey(rawValue: 0xF705)
static public let f3 = NSEvent.SpecialKey(rawValue: 0xF706)
static public let f4 = NSEvent.SpecialKey(rawValue: 0xF707)
static public let f5 = NSEvent.SpecialKey(rawValue: 0xF708)
static public let f6 = NSEvent.SpecialKey(rawValue: 0xF709)
static public let f7 = NSEvent.SpecialKey(rawValue: 0xF70A)
static public let f8 = NSEvent.SpecialKey(rawValue: 0xF70B)
static public let f9 = NSEvent.SpecialKey(rawValue: 0xF70C)
static public let f10 = NSEvent.SpecialKey(rawValue: 0xF70D)
static public let f11 = NSEvent.SpecialKey(rawValue: 0xF70E)
static public let f12 = NSEvent.SpecialKey(rawValue: 0xF70F)
static public let f13 = NSEvent.SpecialKey(rawValue: 0xF710)
static public let f14 = NSEvent.SpecialKey(rawValue: 0xF711)
static public let f15 = NSEvent.SpecialKey(rawValue: 0xF712)
static public let f16 = NSEvent.SpecialKey(rawValue: 0xF713)
static public let f17 = NSEvent.SpecialKey(rawValue: 0xF714)
static public let f18 = NSEvent.SpecialKey(rawValue: 0xF715)
static public let f19 = NSEvent.SpecialKey(rawValue: 0xF716)
static public let f20 = NSEvent.SpecialKey(rawValue: 0xF717)
static public let f21 = NSEvent.SpecialKey(rawValue: 0xF718)
static public let f22 = NSEvent.SpecialKey(rawValue: 0xF719)
static public let f23 = NSEvent.SpecialKey(rawValue: 0xF71A)
static public let f24 = NSEvent.SpecialKey(rawValue: 0xF71B)
static public let f25 = NSEvent.SpecialKey(rawValue: 0xF71C)
static public let f26 = NSEvent.SpecialKey(rawValue: 0xF71D)
static public let f27 = NSEvent.SpecialKey(rawValue: 0xF71E)
static public let f28 = NSEvent.SpecialKey(rawValue: 0xF71F)
static public let f29 = NSEvent.SpecialKey(rawValue: 0xF720)
static public let f30 = NSEvent.SpecialKey(rawValue: 0xF721)
static public let f31 = NSEvent.SpecialKey(rawValue: 0xF722)
static public let f32 = NSEvent.SpecialKey(rawValue: 0xF723)
static public let f33 = NSEvent.SpecialKey(rawValue: 0xF724)
static public let f34 = NSEvent.SpecialKey(rawValue: 0xF725)
static public let f35 = NSEvent.SpecialKey(rawValue: 0xF726)
static public let insert = NSEvent.SpecialKey(rawValue: 0xF727)
static public let deleteForward = NSEvent.SpecialKey(rawValue: 0xF728)
static public let home = NSEvent.SpecialKey(rawValue: 0xF729)
static public let begin = NSEvent.SpecialKey(rawValue: 0xF72A)
static public let end = NSEvent.SpecialKey(rawValue: 0xF72B)
static public let pageUp = NSEvent.SpecialKey(rawValue: 0xF72C)
static public let pageDown = NSEvent.SpecialKey(rawValue: 0xF72D)
static public let printScreen = NSEvent.SpecialKey(rawValue: 0xF72E)
static public let scrollLock = NSEvent.SpecialKey(rawValue: 0xF72F)
static public let pause = NSEvent.SpecialKey(rawValue: 0xF730)
static public let sysReq = NSEvent.SpecialKey(rawValue: 0xF731)
static public let `break` = NSEvent.SpecialKey(rawValue: 0xF732)
static public let reset = NSEvent.SpecialKey(rawValue: 0xF733)
static public let stop = NSEvent.SpecialKey(rawValue: 0xF734)
static public let menu = NSEvent.SpecialKey(rawValue: 0xF735)
static public let user = NSEvent.SpecialKey(rawValue: 0xF736)
static public let system = NSEvent.SpecialKey(rawValue: 0xF737)
static public let print = NSEvent.SpecialKey(rawValue: 0xF738)
static public let clearLine = NSEvent.SpecialKey(rawValue: 0xF739)
static public let clearDisplay = NSEvent.SpecialKey(rawValue: 0xF73A)
static public let insertLine = NSEvent.SpecialKey(rawValue: 0xF73B)
static public let deleteLine = NSEvent.SpecialKey(rawValue: 0xF73C)
static public let insertCharacter = NSEvent.SpecialKey(rawValue: 0xF73D)
static public let deleteCharacter = NSEvent.SpecialKey(rawValue: 0xF73E)
static public let prev = NSEvent.SpecialKey(rawValue: 0xF73F)
static public let next = NSEvent.SpecialKey(rawValue: 0xF740)
static public let select = NSEvent.SpecialKey(rawValue: 0xF741)
static public let execute = NSEvent.SpecialKey(rawValue: 0xF742)
static public let undo = NSEvent.SpecialKey(rawValue: 0xF743)
static public let redo = NSEvent.SpecialKey(rawValue: 0xF744)
static public let find = NSEvent.SpecialKey(rawValue: 0xF745)
static public let help = NSEvent.SpecialKey(rawValue: 0xF746)
static public let modeSwitch = NSEvent.SpecialKey(rawValue: 0xF747)
static public let enter = NSEvent.SpecialKey(rawValue: 0x0003)
static public let backspace = NSEvent.SpecialKey(rawValue: 0x0008)
static public let tab = NSEvent.SpecialKey(rawValue: 0x0009)
static public let newline = NSEvent.SpecialKey(rawValue: 0x000a)
static public let formFeed = NSEvent.SpecialKey(rawValue: 0x000c)
static public let carriageReturn = NSEvent.SpecialKey(rawValue: 0x000d)
static public let backTab = NSEvent.SpecialKey(rawValue: 0x0019)
static public let delete = NSEvent.SpecialKey(rawValue: 0x007f)
static public let lineSeparator = NSEvent.SpecialKey(rawValue: 0x2028)
static public let paragraphSeparator = NSEvent.SpecialKey(rawValue: 0x2029)
}
|
apache-2.0
|
936d67624150e1732f2bb18c9ff352bb
| 46.382716 | 85 | 0.690334 | 4.30028 | false | false | false | false |
practicalswift/swift
|
test/Serialization/comments.swift
|
12
|
3329
|
// Test the case when we have a single file in a module.
//
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc %s
// RUN: llvm-bcanalyzer %t/comments.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER
// RUN: llvm-bcanalyzer %t/comments.swiftdoc | %FileCheck %s -check-prefix=BCANALYZER
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -source-filename %s -I %t | %FileCheck %s -check-prefix=FIRST
// Test the case when we have a multiple files in a module.
//
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/first.swiftmodule -emit-module-doc -emit-module-doc-path %t/first.swiftdoc -primary-file %s %S/Inputs/def_comments.swift
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/second.swiftmodule -emit-module-doc -emit-module-doc-path %t/second.swiftdoc %s -primary-file %S/Inputs/def_comments.swift
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc %t/first.swiftmodule %t/second.swiftmodule
// RUN: llvm-bcanalyzer %t/comments.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER
// RUN: llvm-bcanalyzer %t/comments.swiftdoc | %FileCheck %s -check-prefix=BCANALYZER
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -source-filename %s -I %t > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=FIRST < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=SECOND < %t.printed.txt
// BCANALYZER-NOT: UnknownCode
/// first_decl_generic_class_1 Aaa.
public class first_decl_generic_class_1<T> {
/// deinit of first_decl_generic_class_1 Aaa.
deinit {
}
}
/// first_decl_class_1 Aaa.
public class first_decl_class_1 {
/// decl_func_1 Aaa.
public func decl_func_1() {}
/**
* decl_func_3 Aaa.
*/
public func decl_func_2() {}
/// decl_func_3 Aaa.
/** Bbb. */
public func decl_func_3() {}
}
/// Comment for bar1
extension first_decl_class_1 {
func bar1(){}
}
/// Comment for bar2
extension first_decl_class_1 {
func bar2(){}
}
public protocol P1 { }
/// Comment for no member extension
extension first_decl_class_1 : P1 {}
// FIRST: Class/first_decl_generic_class_1 RawComment=[/// first_decl_generic_class_1 Aaa.\n]
// FIRST: Destructor/first_decl_generic_class_1.deinit RawComment=[/// deinit of first_decl_generic_class_1 Aaa.\n]
// FIRST: Class/first_decl_class_1 RawComment=[/// first_decl_class_1 Aaa.\n]
// FIRST: Func/first_decl_class_1.decl_func_1 RawComment=[/// decl_func_1 Aaa.\n]
// FIRST: Func/first_decl_class_1.decl_func_2 RawComment=[/**\n * decl_func_3 Aaa.\n */]
// FIRST: Func/first_decl_class_1.decl_func_3 RawComment=[/// decl_func_3 Aaa.\n/** Bbb. */]
// SECOND: Extension/ RawComment=[/// Comment for bar1\n] BriefComment=[Comment for bar1]
// SECOND: Extension/ RawComment=[/// Comment for bar2\n] BriefComment=[Comment for bar2]
// SECOND: Extension/ RawComment=[/// Comment for no member extension\n] BriefComment=[Comment for no member extension]
// SECOND: Class/second_decl_class_1 RawComment=[/// second_decl_class_1 Aaa.\n]
|
apache-2.0
|
27adb89914895f36b4b220a09ad92aa6
| 45.887324 | 210 | 0.710724 | 3.16746 | false | true | false | false |
DavdRoman/rehatch
|
Sources/CLI/RehatchCommand.swift
|
1
|
2470
|
import Foundation
import SwiftCLI
import Twitter
import CSV
final class RehatchCommand: Command {
enum Constant {
static let consumerKey = ConsumerKey(
key: "<CONSUMER_KEY>",
secret: "<CONSUMER_SECRET>"
)
}
let name = "rehatch"
let twitterArchivePath = Parameter(
completion: .none,
validation: [.custom("file does not exist at specified path", { FileManager.default.fileExists(atPath: $0) })]
)
let untilDate = Key<Int>("--until-date", "-d", description: "UNIX date until which tweets are deleted")
init() {}
func execute() throws {
let oauthApi = OAuth.API(consumerKey: Constant.consumerKey)
let requestToken = try oauthApi.requestToken()
let authorizationResponse = try oauthApi.authorize(with: requestToken)
let accessToken = try oauthApi.exchangeRequestTokenForAccessToken(with: requestToken, authorizationResponse: authorizationResponse)
let twitterArchiveFolderName = URL(fileURLWithPath: twitterArchivePath.value).deletingPathExtension().lastPathComponent
let twitterArchiveFolderPathURL = FileManager.default.temporaryDirectory.appendingPathComponent(twitterArchiveFolderName)
let twitterArchiveFolderPath = twitterArchiveFolderPathURL.path
_ = try Task.capture(bash: "unzip -qq -o \(twitterArchivePath.value) -d \(twitterArchiveFolderPath)")
let archive = try Archive(contentsOfFolder: twitterArchiveFolderPath)
let tweetsToDelete: [Archive.Tweet]
if let untilDateUnix = untilDate.value {
tweetsToDelete = archive.tweets.sortedTweets(until: Date(timeIntervalSince1970: TimeInterval(untilDateUnix)))
} else {
tweetsToDelete = archive.tweets
}
let report = Archive.Tweet.DeletionReport(totalTweets: archive.tweets.count)
let statusesAPI = StatusesAPI(consumerKey: Constant.consumerKey, accessToken: accessToken)
Logger.info("Hey @\(accessToken.username)! You are about to delete \(tweetsToDelete.count) tweets.")
guard Input.readBool(prompt: "Would you like to proceed? (y/n)") else {
return
}
Logger.step(report.progressString, succeedPrevious: false)
for tweet in tweetsToDelete {
do {
if tweet.isRetweet {
try statusesAPI.unretweetTweet(with: tweet.id)
} else {
try statusesAPI.deleteTweet(with: tweet.id)
}
report.add(tweet, success: true)
} catch {
report.add(tweet, success: false)
}
if !report.didFinish {
Logger.step(report.progressString, succeedPrevious: false)
} else {
Logger.succeed(report.endString)
}
}
}
}
|
mit
|
f8f36ac8138bed4418c4155846957551
| 34.285714 | 133 | 0.750607 | 3.871473 | false | false | false | false |
tensorflow/examples
|
lite/examples/posenet/ios/PoseNet/ViewControllers/ViewController.swift
|
1
|
12177
|
// Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import AVFoundation
import UIKit
import os
class ViewController: UIViewController {
// MARK: Storyboards Connections
@IBOutlet weak var previewView: PreviewView!
@IBOutlet weak var overlayView: OverlayView!
@IBOutlet weak var resumeButton: UIButton!
@IBOutlet weak var cameraUnavailableLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var threadCountLabel: UILabel!
@IBOutlet weak var threadCountStepper: UIStepper!
@IBOutlet weak var delegatesControl: UISegmentedControl!
// MARK: ModelDataHandler traits
var threadCount: Int = Constants.defaultThreadCount
var delegate: Delegates = Constants.defaultDelegate
// MARK: Result Variables
// Inferred data to render.
private var inferredData: InferredData?
// Minimum score to render the result.
private let minimumScore: Float = 0.5
// Relative location of `overlayView` to `previewView`.
private var overlayViewFrame: CGRect?
private var previewViewFrame: CGRect?
// MARK: Controllers that manage functionality
// Handles all the camera related functionality
private lazy var cameraCapture = CameraFeedManager(previewView: previewView)
// Handles all data preprocessing and makes calls to run inference.
private var modelDataHandler: ModelDataHandler?
// MARK: View Handling Methods
override func viewDidLoad() {
super.viewDidLoad()
do {
modelDataHandler = try ModelDataHandler()
} catch let error {
fatalError(error.localizedDescription)
}
cameraCapture.delegate = self
tableView.delegate = self
tableView.dataSource = self
// MARK: UI Initialization
// Setup thread count stepper with white color.
// https://forums.developer.apple.com/thread/121495
threadCountStepper.setDecrementImage(
threadCountStepper.decrementImage(for: .normal), for: .normal)
threadCountStepper.setIncrementImage(
threadCountStepper.incrementImage(for: .normal), for: .normal)
// Setup initial stepper value and its label.
threadCountStepper.value = Double(Constants.defaultThreadCount)
threadCountLabel.text = Constants.defaultThreadCount.description
// Setup segmented controller's color.
delegatesControl.setTitleTextAttributes(
[NSAttributedString.Key.foregroundColor: UIColor.lightGray],
for: .normal)
delegatesControl.setTitleTextAttributes(
[NSAttributedString.Key.foregroundColor: UIColor.black],
for: .selected)
// Remove existing segments to initialize it with `Delegates` entries.
delegatesControl.removeAllSegments()
Delegates.allCases.forEach { delegate in
delegatesControl.insertSegment(
withTitle: delegate.description,
at: delegate.rawValue,
animated: false)
}
delegatesControl.selectedSegmentIndex = 0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
cameraCapture.checkCameraConfigurationAndStartSession()
}
override func viewWillDisappear(_ animated: Bool) {
cameraCapture.stopSession()
}
override func viewDidLayoutSubviews() {
overlayViewFrame = overlayView.frame
previewViewFrame = previewView.frame
}
// MARK: Button Actions
@IBAction func didChangeThreadCount(_ sender: UIStepper) {
let changedCount = Int(sender.value)
if threadCountLabel.text == changedCount.description {
return
}
do {
modelDataHandler = try ModelDataHandler(threadCount: changedCount, delegate: delegate)
} catch let error {
fatalError(error.localizedDescription)
}
threadCount = changedCount
threadCountLabel.text = changedCount.description
os_log("Thread count is changed to: %d", threadCount)
}
@IBAction func didChangeDelegate(_ sender: UISegmentedControl) {
guard let changedDelegate = Delegates(rawValue: delegatesControl.selectedSegmentIndex) else {
fatalError("Unexpected value from delegates segemented controller.")
}
do {
modelDataHandler = try ModelDataHandler(threadCount: threadCount, delegate: changedDelegate)
} catch let error {
fatalError(error.localizedDescription)
}
delegate = changedDelegate
os_log("Delegate is changed to: %s", delegate.description)
}
@IBAction func didTapResumeButton(_ sender: Any) {
cameraCapture.resumeInterruptedSession { complete in
if complete {
self.resumeButton.isHidden = true
self.cameraUnavailableLabel.isHidden = true
} else {
self.presentUnableToResumeSessionAlert()
}
}
}
func presentUnableToResumeSessionAlert() {
let alert = UIAlertController(
title: "Unable to Resume Session",
message: "There was an error while attempting to resume session.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}
}
// MARK: - CameraFeedManagerDelegate Methods
extension ViewController: CameraFeedManagerDelegate {
func cameraFeedManager(_ manager: CameraFeedManager, didOutput pixelBuffer: CVPixelBuffer) {
runModel(on: pixelBuffer)
}
// MARK: Session Handling Alerts
func cameraFeedManagerDidEncounterSessionRunTimeError(_ manager: CameraFeedManager) {
// Handles session run time error by updating the UI and providing a button if session can be
// manually resumed.
self.resumeButton.isHidden = false
}
func cameraFeedManager(
_ manager: CameraFeedManager, sessionWasInterrupted canResumeManually: Bool
) {
// Updates the UI when session is interupted.
if canResumeManually {
self.resumeButton.isHidden = false
} else {
self.cameraUnavailableLabel.isHidden = false
}
}
func cameraFeedManagerDidEndSessionInterruption(_ manager: CameraFeedManager) {
// Updates UI once session interruption has ended.
self.cameraUnavailableLabel.isHidden = true
self.resumeButton.isHidden = true
}
func presentVideoConfigurationErrorAlert(_ manager: CameraFeedManager) {
let alertController = UIAlertController(
title: "Confirguration Failed", message: "Configuration of camera has failed.",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
func presentCameraPermissionsDeniedAlert(_ manager: CameraFeedManager) {
let alertController = UIAlertController(
title: "Camera Permissions Denied",
message:
"Camera permissions have been denied for this app. You can change this by going to Settings",
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { action in
if let url = URL.init(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
present(alertController, animated: true, completion: nil)
}
@objc func runModel(on pixelBuffer: CVPixelBuffer) {
guard let overlayViewFrame = overlayViewFrame, let previewViewFrame = previewViewFrame
else {
return
}
// To put `overlayView` area as model input, transform `overlayViewFrame` following transform
// from `previewView` to `pixelBuffer`. `previewView` area is transformed to fit in
// `pixelBuffer`, because `pixelBuffer` as a camera output is resized to fill `previewView`.
// https://developer.apple.com/documentation/avfoundation/avlayervideogravity/1385607-resizeaspectfill
let modelInputRange = overlayViewFrame.applying(
previewViewFrame.size.transformKeepAspect(toFitIn: pixelBuffer.size))
// Run PoseNet model.
guard
let (result, times) = self.modelDataHandler?.runPoseNet(
on: pixelBuffer,
from: modelInputRange,
to: overlayViewFrame.size)
else {
os_log("Cannot get inference result.", type: .error)
return
}
// Update `inferredData` to render data in `tableView`.
inferredData = InferredData(score: result.score, times: times)
// Draw result.
DispatchQueue.main.async {
self.tableView.reloadData()
// If score is too low, clear result remaining in the overlayView.
if result.score < self.minimumScore {
self.clearResult()
return
}
self.drawResult(of: result)
}
}
func drawResult(of result: Result) {
self.overlayView.dots = result.dots
self.overlayView.lines = result.lines
self.overlayView.setNeedsDisplay()
}
func clearResult() {
self.overlayView.clear()
self.overlayView.setNeedsDisplay()
}
}
// MARK: - TableViewDelegate, TableViewDataSource Methods
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return InferenceSections.allCases.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = InferenceSections(rawValue: section) else {
return 0
}
return section.subcaseCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell") as! InfoCell
guard let section = InferenceSections(rawValue: indexPath.section) else {
return cell
}
guard let data = inferredData else { return cell }
var fieldName: String
var info: String
switch section {
case .Score:
fieldName = section.description
info = String(format: "%.3f", data.score)
case .Time:
guard let row = ProcessingTimes(rawValue: indexPath.row) else {
return cell
}
var time: Double
switch row {
case .InferenceTime:
time = data.times.inference
}
fieldName = row.description
info = String(format: "%.2fms", time)
}
cell.fieldNameLabel.text = fieldName
cell.infoLabel.text = info
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let section = InferenceSections(rawValue: indexPath.section) else {
return 0
}
var height = Traits.normalCellHeight
if indexPath.row == section.subcaseCount - 1 {
height = Traits.separatorCellHeight + Traits.bottomSpacing
}
return height
}
}
// MARK: - Private enums
/// UI constraint values
fileprivate enum Traits {
static let normalCellHeight: CGFloat = 35.0
static let separatorCellHeight: CGFloat = 25.0
static let bottomSpacing: CGFloat = 30.0
}
fileprivate struct InferredData {
var score: Float
var times: Times
}
/// Type of sections in Info Cell
fileprivate enum InferenceSections: Int, CaseIterable {
case Score
case Time
var description: String {
switch self {
case .Score:
return "Score"
case .Time:
return "Processing Time"
}
}
var subcaseCount: Int {
switch self {
case .Score:
return 1
case .Time:
return ProcessingTimes.allCases.count
}
}
}
/// Type of processing times in Time section in Info Cell
fileprivate enum ProcessingTimes: Int, CaseIterable {
case InferenceTime
var description: String {
switch self {
case .InferenceTime:
return "Inference Time"
}
}
}
|
apache-2.0
|
158d789d9dca09e0910d68c6907e0a23
| 30.384021 | 106 | 0.717007 | 4.728932 | false | false | false | false |
MatheusGodinho/SnapKitLearning
|
SnapKitCRUD/ViewControllerTextFieldDelegate.swift
|
1
|
1190
|
//
// ViewControllerTextFieldDelegate.swift
// SnapKitCRUD
//
// Created by Matheus Godinho on 16/09/16.
// Copyright © 2016 Godinho. All rights reserved.
//
import UIKit
extension ViewController: UITextFieldDelegate{
func setDelegates(){
fieldsView.emailField.delegate = self
fieldsView.passField.delegate = self
fieldsView.passConfirmationField.delegate = self
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if(textField.tag != 2){
textField.returnKeyType = .next
}else{
textField.returnKeyType = .done
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
moveInTextFields(textField)
return true // We do not want UITextFiel
}
func moveInTextFields(_ textField: UITextField){
let nextTag: NSInteger = textField.tag + 1;
// Try to find next responder
if let nextResponder: UIResponder? = textField.superview!.superview!.superview!.viewWithTag(nextTag){
nextResponder?.becomeFirstResponder()
}
else {
textField.resignFirstResponder()
}
}
}
|
mit
|
a7120d3d2e7ff431361317c8ea684368
| 27.309524 | 109 | 0.636669 | 4.995798 | false | false | false | false |
PureSwift/Bluetooth
|
Sources/BluetoothHCI/HCILETransmitterTest.swift
|
1
|
2254
|
//
// HCILETransmitterTest.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Method
public extension BluetoothHostControllerInterface {
/// LE Transmitter Test Command
///
/// This command is used to start a test where the DUT generates test reference packets
/// at a fixed interval. The Controller shall transmit at maximum power.
func lowEnergyTransmitterTest(txChannel: LowEnergyTxChannel,
lengthOfTestData: UInt8,
packetPayload: LowEnergyPacketPayload,
timeout: HCICommandTimeout = .default) async throws {
let parameters = HCILETransmitterTest(txChannel: txChannel, lengthOfTestData: lengthOfTestData, packetPayload: packetPayload)
try await deviceRequest(parameters, timeout: timeout)
}
}
// MARK: - Command
/// LE Transmitter Test Command
///
/// This command is used to start a test where the DUT generates test reference packets
/// at a fixed interval. The Controller shall transmit at maximum power.
///
/// An LE Controller supporting the LE_Transmitter_Test command shall support Packet_Payload values 0x00,
/// 0x01 and 0x02. An LE Controller may support other values of Packet_Payload.
@frozen
public struct HCILETransmitterTest: HCICommandParameter {
public static let command = HCILowEnergyCommand.transmitterTest //0x001E
/// N = (F – 2402) / 2
/// Range: 0x00 – 0x27. Frequency Range : 2402 MHz to 2480 MHz
public let txChannel: LowEnergyTxChannel //RX_Channel
/// Length in bytes of payload data in each packet
public let lengthOfTestData: UInt8
public let packetPayload: LowEnergyPacketPayload
public init(txChannel: LowEnergyTxChannel,
lengthOfTestData: UInt8,
packetPayload: LowEnergyPacketPayload) {
self.txChannel = txChannel
self.lengthOfTestData = lengthOfTestData
self.packetPayload = packetPayload
}
public var data: Data {
return Data([txChannel.rawValue, packetPayload.rawValue])
}
}
|
mit
|
90669b21f0181d84647505123031f191
| 33.075758 | 133 | 0.673633 | 4.637113 | false | true | false | false |
jaredsinclair/sodes-audio-example
|
Sodes/SodesFoundation/Throttle.swift
|
1
|
2566
|
//
// Throttle.swift
// SodesFoundation
//
// Created by Jared Sinclair on 8/11/16.
//
//
import Foundation
public class Throttle {
public typealias Action = () -> Void
fileprivate let serialQueue: OperationQueue
fileprivate var pendingAction: Action?
fileprivate var hasTakenActionAtLeastOnce = false
fileprivate var timer: Timer?
fileprivate var timerTarget: TimerTarget! {
didSet { assert(oldValue == nil) }
}
public init(minimumInterval: TimeInterval, qualityOfService: QualityOfService) {
serialQueue = {
let queue = OperationQueue()
queue.qualityOfService = qualityOfService
queue.maxConcurrentOperationCount = 1
return queue
}()
timerTarget = TimerTarget(delegate: self)
timer = {
let timer = Timer(
timeInterval: minimumInterval,
target: timerTarget,
selector: #selector(TimerTarget.timerFired),
userInfo: nil,
repeats: true
)
timer.tolerance = minimumInterval * 0.5
RunLoop.main.add(timer, forMode: .commonModes)
return timer
}()
}
deinit {
timer?.invalidate()
timer = nil
}
public func enqueue(immediately: Bool = false, action: @escaping Action) {
let op = BlockOperation { [weak self] in
guard let this = self else {return}
if !this.hasTakenActionAtLeastOnce || immediately {
this.hasTakenActionAtLeastOnce = true
this.pendingAction = nil
action()
} else {
this.pendingAction = action
}
}
op.queuePriority = immediately ? .veryHigh : .normal
serialQueue.addOperation(op)
}
}
extension Throttle: TimerTargetDelegate {
fileprivate func timerFired(for: TimerTarget) {
serialQueue.addOperation { [weak self] in
guard let this = self else {return}
guard let action = this.pendingAction else {return}
this.pendingAction = nil
action()
}
}
}
private protocol TimerTargetDelegate: class {
func timerFired(for: TimerTarget)
}
private class TimerTarget {
weak var delegate: TimerTargetDelegate?
init(delegate: TimerTargetDelegate) {
self.delegate = delegate
}
@objc func timerFired(_ timer: Timer) {
delegate?.timerFired(for: self)
}
}
|
mit
|
843dace36d41012d91cf7fe1378b5d97
| 25.729167 | 84 | 0.583009 | 5.121756 | false | false | false | false |
data-licious/ceddl4swift
|
ceddl4swift/Example/Example1.swift
|
1
|
1868
|
//
// Example1.swift
// ceddl4swift
//
// Created by Sachin Vas on 23/10/16.
// Copyright © 2016 Sachin Vas. All rights reserved.
//
import Foundation
/// Generates the following example from the CEDDL specification on page 9.
///
/// digitalData={
/// pageInstanceID: "MyHomePage-Production",
/// page: {
/// pageInfo: {
/// pageID: "Home Page",
/// destinationURL: "http://mysite.com/index.html"
/// }
/// },
/// category: {
/// primaryCategory: "FAQ Pages",
/// subCategory1: "ProductInfo",
/// pageType: "FAQ"
/// },
/// attributes: {
/// country: "US",
/// language: "en-US"
/// }
/// }
public class Example1 {
public func exampleFromSpec1() {
let example1DigitalData = DigitalData.create("MyHomePage-Production")
.page().pageInfo()
.pageID("Home Page")
.destinationURL("http://mysite.com/index.html")
.endPageInfo()
.addPrimaryCategory("FAQ Pages")
.addCategory("subCategory1", value: "ProductInfo" as AnyObject)
.addCategory("pageType", value: "FAQ" as AnyObject)
.addAttribute("country", value: "US" as AnyObject)
.addAttribute("language", value: "en-US" as AnyObject)
.endPage()
do {
let example1DigitalDataDict = example1DigitalData.getMap()
if let json = try Utility.loadJSONFromFile(type(of: self), name: "example1") as? Dictionary<String, AnyObject> {
assert(example1DigitalDataDict == json, "Digital Data is not equal to contents of file")
} else {
assert(false, "Unable to generate dictionary from file")
}
} catch let error {
print(error)
}
}
}
|
bsd-3-clause
|
fd5ab6a6cc8e66ebd07ba7b4b717d01d
| 30.644068 | 124 | 0.547402 | 4.067538 | false | false | false | false |
saeta/penguin
|
Sources/PenguinStructures/KeyValuePair.swift
|
1
|
2094
|
//******************************************************************************
// Copyright 2020 Penguin Authors
//
// 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.
//
/// A nominal version of the tuple type that is the `Element` of
/// `Swift.Dictionary`.
public struct KeyValuePair<Key, Value> {
/// Creates an instance with the given key and value.
public init(key: Key, value: Value) {
(self.key, self.value) = (key, value)
}
public var key: Key
public var value: Value
}
extension KeyValuePair: Equatable where Key: Equatable, Value: Equatable {}
extension KeyValuePair: Comparable where Key: Comparable, Value: Comparable {
public static func < (a: Self, b: Self) -> Bool {
a.key < b.key || a.key == b.key && a.value < b.value
}
}
extension KeyValuePair: Hashable where Key: Hashable, Value: Hashable {}
/// Useful extensions for Dictionary interop.
extension KeyValuePair {
internal init(tuple x: (key: Key, value: Value)) {
self.init(key: x.key, value: x.value)
}
internal var tuple: (key: Key, value: Value) { (key, value) }
}
extension KeyValuePair
: Decodable where Key : Decodable, Value : Decodable
{
/// Deserializes a new instance from the given decoder.
public init(from decoder: Decoder) throws {
try key = .init(from: decoder)
try value = .init(from: decoder)
}
}
extension KeyValuePair : Encodable
where Key : Encodable, Value : Encodable
{
/// Serializes `self` into the given encoder.
public func encode(to encoder: Encoder) throws {
try key.encode(to: encoder)
try value.encode(to: encoder)
}
}
|
apache-2.0
|
5a1e25da81eced859de103b90d940f28
| 32.774194 | 80 | 0.677173 | 3.958412 | false | false | false | false |
ello/ello-ios
|
Sources/Controllers/Profile/ProfileScreen.swift
|
1
|
19039
|
////
/// ProfileScreen.swift
//
import SnapKit
import PINRemoteImage
class ProfileScreen: StreamableScreen, ProfileScreenProtocol {
struct Size {
static let whiteTopOffset: CGFloat = 338
static let profileButtonsContainerViewHeight: CGFloat = 60
static let profileButtonsContainerTallHeight: CGFloat = 84
static let navBarHeight: CGFloat = 64
static let buttonMargin: CGFloat = 15
static let innerButtonMargin: CGFloat = 5
static let buttonHeight: CGFloat = 30
static let buttonWidth: CGFloat = 70
static let mentionButtonWidth: CGFloat = 100
static let relationshipButtonMaxWidth: CGFloat = 283
static let relationshipControlLeadingMargin: CGFloat = 5
static let editButtonMargin: CGFloat = 10
}
var coverImage: UIImage? {
get { return coverImageView.image }
set { coverImageView.image = newValue }
}
var coverImageURL: URL? {
get { return nil }
set { coverImageView.pin_setImage(from: newValue) { _ in } }
}
var topInsetView: UIView {
return profileButtonsEffect
}
var hasRoleAdminButton: Bool = false {
didSet { updateRoleAdminButton() }
}
var hasBackButton: Bool = false {
didSet { updateBackButton() }
}
var showBackButton: Bool = false {
didSet { updateBackButton() }
}
// 'internal' visibitility for testing
let relationshipControl = RelationshipControl()
let roleAdminButton = UIButton()
let collaborateButton = StyledButton(style: .blackPill)
let hireButton = StyledButton(style: .blackPill)
let mentionButton = StyledButton(style: .blackPill)
let inviteButton = StyledButton(style: .blackPill)
let editButton = StyledButton(style: .blackPill)
private let whiteSolidView = UIView()
private let loaderView = InterpolatedLoadingView()
private let coverImageView = PINAnimatedImageView()
private let ghostLeftButton = StyledButton(style: .blackPill)
private let ghostRightButton = StyledButton(style: .blackPill)
private let profileButtonsEffect = UIVisualEffectView()
private var profileButtonsContainer: UIView { return profileButtonsEffect.contentView }
private let profileButtonsLeadingGuide = UILayoutGuide()
private let persistentBackButton = PersistentBackButton()
// constraints
private var whiteSolidTop: Constraint!
private var coverImageHeight: Constraint!
private var roleAdminVisibleConstraint: Constraint!
private var roleAdminHiddenConstraint: Constraint!
private var profileButtonsContainerTopConstraint: Constraint!
private var profileButtonsContainerHeightConstraint: Constraint!
private var hireLeftConstraint: Constraint!
private var hireRightConstraint: Constraint!
private var relationshipHireConstraint: Constraint!
private var relationshipCollabConstraint: Constraint!
private var relationshipMentionConstraint: Constraint!
private var showBackButtonConstraint: Constraint!
private var hideBackButtonConstraint: Constraint!
weak var delegate: ProfileScreenDelegate?
override func layoutSubviews() {
super.layoutSubviews()
roleAdminButton.layer.cornerRadius = roleAdminButton.frame.size.height / 2
}
override func setup() {
persistentBackButton.alpha = 0
roleAdminButton.isHidden = true
collaborateButton.isHidden = true
hireButton.isHidden = true
mentionButton.isHidden = true
relationshipControl.isHidden = true
editButton.isHidden = true
inviteButton.isHidden = true
ghostLeftButton.isVisible = true
ghostRightButton.isVisible = true
ghostLeftButton.isEnabled = false
ghostRightButton.isEnabled = false
}
override func setText() {
collaborateButton.title = InterfaceString.Profile.Collaborate
hireButton.title = InterfaceString.Profile.Hire
inviteButton.title = InterfaceString.Profile.Invite
editButton.title = InterfaceString.Profile.EditProfile
mentionButton.title = InterfaceString.Profile.Mention
}
override func style() {
whiteSolidView.backgroundColor = .white
relationshipControl.usage = .profileView
profileButtonsEffect.effect = UIBlurEffect(style: .light)
coverImageView.contentMode = .scaleAspectFill
roleAdminButton.setImage(.roleAdmin, imageStyle: .white, for: .normal)
roleAdminButton.setImage(.roleAdmin, imageStyle: .normal, for: .selected)
roleAdminButton.backgroundColor = .black
roleAdminButton.layer.masksToBounds = true
}
override func bindActions() {
mentionButton.addTarget(self, action: #selector(mentionTapped(_:)), for: .touchUpInside)
collaborateButton.addTarget(
self,
action: #selector(collaborateTapped(_:)),
for: .touchUpInside
)
roleAdminButton.addTarget(self, action: #selector(roleAdminTapped(_:)), for: .touchUpInside)
hireButton.addTarget(self, action: #selector(hireTapped(_:)), for: .touchUpInside)
editButton.addTarget(self, action: #selector(editTapped(_:)), for: .touchUpInside)
inviteButton.addTarget(self, action: #selector(inviteTapped(_:)), for: .touchUpInside)
persistentBackButton.addTarget(
navigationBar,
action: #selector(ElloNavigationBar.backButtonTapped),
for: .touchUpInside
)
}
override func arrange() {
super.arrange()
addSubview(loaderView)
addSubview(coverImageView)
addSubview(whiteSolidView)
addSubview(streamContainer)
addSubview(profileButtonsEffect)
addSubview(navigationBar)
// relationship controls sub views
profileButtonsContainer.addLayoutGuide(profileButtonsLeadingGuide)
profileButtonsContainer.addSubview(mentionButton)
profileButtonsContainer.addSubview(roleAdminButton)
profileButtonsContainer.addSubview(collaborateButton)
profileButtonsContainer.addSubview(hireButton)
profileButtonsContainer.addSubview(inviteButton)
profileButtonsContainer.addSubview(relationshipControl)
profileButtonsContainer.addSubview(editButton)
profileButtonsContainer.addSubview(ghostLeftButton)
profileButtonsContainer.addSubview(ghostRightButton)
profileButtonsContainer.addSubview(persistentBackButton)
loaderView.snp.makeConstraints { make in
make.edges.equalTo(coverImageView)
}
coverImageView.snp.makeConstraints { make in
coverImageHeight = make.height.equalTo(Size.whiteTopOffset).constraint
make.width.equalTo(coverImageView.snp.height).multipliedBy(
ProfileHeaderAvatarCell.Size.ratio
)
make.top.equalTo(streamContainer.snp.top)
make.centerX.equalTo(self)
}
whiteSolidView.snp.makeConstraints { make in
whiteSolidTop = make.top.equalTo(self).offset(Size.whiteTopOffset).constraint
make.leading.trailing.bottom.equalTo(self)
}
profileButtonsEffect.snp.makeConstraints { make in
profileButtonsContainerTopConstraint = make.top.equalTo(self).constraint
make.centerX.equalTo(self)
make.width.equalTo(self)
profileButtonsContainerHeightConstraint =
make.height.equalTo(Size.profileButtonsContainerViewHeight).constraint
}
profileButtonsLeadingGuide.snp.makeConstraints { make in
showBackButtonConstraint =
make.leading.trailing.equalTo(persistentBackButton.snp.trailing).offset(
Size.buttonMargin
).constraint
hideBackButtonConstraint =
make.leading.trailing.equalTo(profileButtonsContainer.snp.leading).offset(
Size.buttonMargin
).constraint
}
showBackButtonConstraint.deactivate()
persistentBackButton.setContentHuggingPriority(UILayoutPriority.required, for: .horizontal)
persistentBackButton.snp.makeConstraints { make in
make.leading.equalTo(profileButtonsContainer).offset(Size.buttonMargin)
make.bottom.equalTo(profileButtonsContainer).offset(-Size.buttonMargin)
}
roleAdminButton.snp.makeConstraints { make in
make.leading.equalTo(profileButtonsLeadingGuide.snp.trailing)
make.width.height.equalTo(Size.buttonHeight)
make.top.equalTo(mentionButton)
}
let buttonLeadingGuide = UILayoutGuide()
addLayoutGuide(buttonLeadingGuide)
buttonLeadingGuide.snp.makeConstraints { make in
roleAdminHiddenConstraint =
make.leading.equalTo(profileButtonsLeadingGuide.snp.trailing).constraint
roleAdminVisibleConstraint =
make.leading.equalTo(roleAdminButton.snp.trailing).offset(Size.buttonMargin)
.constraint
}
roleAdminHiddenConstraint.deactivate()
mentionButton.snp.makeConstraints { make in
make.leading.equalTo(buttonLeadingGuide)
make.width.equalTo(Size.mentionButtonWidth).priority(Priority.required)
make.height.equalTo(Size.buttonHeight)
make.bottom.equalTo(profileButtonsContainer).offset(-Size.buttonMargin)
}
collaborateButton.snp.makeConstraints { make in
make.height.equalTo(Size.buttonHeight)
make.top.equalTo(mentionButton)
make.leading.equalTo(buttonLeadingGuide)
make.width.equalTo(Size.buttonWidth).priority(Priority.required)
}
roleAdminVisibleConstraint.deactivate()
hireButton.snp.makeConstraints { make in
make.height.equalTo(Size.buttonHeight)
hireLeftConstraint = make.leading.equalTo(buttonLeadingGuide).constraint
hireRightConstraint =
make.leading.equalTo(collaborateButton.snp.trailing).offset(Size.innerButtonMargin)
.constraint
make.top.equalTo(mentionButton)
make.width.equalTo(Size.buttonWidth).priority(Priority.required)
}
hireLeftConstraint.deactivate()
hireRightConstraint.deactivate()
inviteButton.snp.makeConstraints { make in
make.leading.equalTo(buttonLeadingGuide)
make.width.equalTo(Size.mentionButtonWidth).priority(Priority.medium)
make.width.greaterThanOrEqualTo(Size.mentionButtonWidth)
make.height.equalTo(Size.buttonHeight)
make.bottom.equalTo(profileButtonsContainer).offset(-Size.buttonMargin)
}
relationshipControl.snp.makeConstraints { make in
make.height.equalTo(Size.buttonHeight)
make.width.lessThanOrEqualTo(Size.relationshipButtonMaxWidth).priority(
Priority.required
)
relationshipHireConstraint =
make.leading.equalTo(hireButton.snp.trailing).offset(
Size.relationshipControlLeadingMargin
).priority(Priority.medium).constraint
relationshipCollabConstraint =
make.leading.equalTo(collaborateButton.snp.trailing).offset(
Size.relationshipControlLeadingMargin
).priority(Priority.medium).constraint
relationshipMentionConstraint =
make.leading.equalTo(mentionButton.snp.trailing).offset(
Size.relationshipControlLeadingMargin
).priority(Priority.medium).constraint
make.bottom.equalTo(profileButtonsContainer).offset(-Size.buttonMargin)
make.trailing.equalTo(profileButtonsContainer).offset(-Size.buttonMargin).priority(
Priority.required
)
}
relationshipHireConstraint.deactivate()
relationshipCollabConstraint.deactivate()
relationshipMentionConstraint.deactivate()
editButton.snp.makeConstraints { make in
make.height.equalTo(Size.buttonHeight)
make.width.lessThanOrEqualTo(Size.relationshipButtonMaxWidth)
make.leading.equalTo(inviteButton.snp.trailing).offset(Size.editButtonMargin)
make.trailing.equalTo(profileButtonsContainer).offset(-Size.editButtonMargin)
make.bottom.equalTo(-Size.buttonMargin)
}
ghostLeftButton.snp.makeConstraints { make in
make.leading.equalTo(profileButtonsContainer).offset(Size.buttonMargin)
make.width.equalTo(Size.mentionButtonWidth).priority(Priority.required)
make.height.equalTo(Size.buttonHeight)
make.bottom.equalTo(profileButtonsContainer).offset(-Size.buttonMargin)
}
ghostRightButton.snp.makeConstraints { make in
make.height.equalTo(Size.buttonHeight)
make.width.lessThanOrEqualTo(Size.relationshipButtonMaxWidth)
make.leading.equalTo(ghostLeftButton.snp.trailing).offset(Size.editButtonMargin)
make.trailing.equalTo(profileButtonsContainer).offset(-Size.editButtonMargin)
make.bottom.equalTo(-Size.buttonMargin)
}
}
@objc
func mentionTapped(_ button: UIButton) {
delegate?.mentionTapped()
}
@objc
func hireTapped(_ button: UIButton) {
delegate?.hireTapped()
}
@objc
func editTapped(_ button: UIButton) {
delegate?.editTapped()
}
@objc
func inviteTapped(_ button: UIButton) {
delegate?.inviteTapped()
}
@objc
func collaborateTapped(_ button: UIButton) {
delegate?.collaborateTapped()
}
@objc
func roleAdminTapped(_ button: UIButton) {
delegate?.roleAdminTapped()
}
func enableButtons() {
setButtonsEnabled(true)
}
func disableButtons() {
setButtonsEnabled(false)
}
func configureButtonsForNonCurrentUser(isHireable: Bool, isCollaborateable: Bool) {
let showBoth = isHireable && isCollaborateable
let showOne = !showBoth && (isHireable || isCollaborateable)
hireLeftConstraint.set(isActivated: showOne)
hireRightConstraint.set(isActivated: showBoth)
relationshipHireConstraint.set(isActivated: isHireable)
relationshipCollabConstraint.set(isActivated: !isHireable && isCollaborateable)
relationshipMentionConstraint.set(isActivated: !(isHireable || isCollaborateable))
collaborateButton.isVisible = isCollaborateable
hireButton.isVisible = isHireable
mentionButton.isHidden = isHireable || isCollaborateable
relationshipControl.isVisible = true
editButton.isHidden = true
inviteButton.isHidden = true
ghostLeftButton.isHidden = true
ghostRightButton.isHidden = true
}
func configureButtonsForCurrentUser() {
collaborateButton.isHidden = true
hireButton.isHidden = true
mentionButton.isHidden = true
relationshipControl.isHidden = true
editButton.isVisible = true
inviteButton.isVisible = true
ghostLeftButton.isHidden = true
ghostRightButton.isHidden = true
}
private func setButtonsEnabled(_ enabled: Bool) {
roleAdminButton.isEnabled = enabled
collaborateButton.isEnabled = enabled
hireButton.isEnabled = enabled
mentionButton.isEnabled = enabled
editButton.isEnabled = enabled
inviteButton.isEnabled = enabled
relationshipControl.isEnabled = enabled
}
func updateRelationshipControl(user: User) {
relationshipControl.userId = user.id
relationshipControl.userAtName = user.atName
relationshipControl.relationshipPriority = user.relationshipPriority
}
func updateRelationshipPriority(_ relationshipPriority: RelationshipPriority) {
relationshipControl.relationshipPriority = relationshipPriority
}
func updateHeaderHeightConstraints(
max maxHeaderHeight: CGFloat,
scrollAdjusted scrollAdjustedHeight: CGFloat
) {
coverImageHeight.update(offset: maxHeaderHeight)
whiteSolidTop.update(offset: max(scrollAdjustedHeight, 0))
}
func resetCoverImage() {
coverImageView.pin_cancelImageDownload()
coverImageView.image = nil
}
override func showNavBars(animated: Bool) {
elloAnimate(animated: animated) {
let effectsTop = self.navigationBar.frame.height
let effectsHeight = Size.profileButtonsContainerViewHeight
self.updateNavBars(effectsTop: effectsTop, effectsHeight: effectsHeight)
self.showBackButton = false
super.showNavBars(animated: false)
}
}
func hideNavBars(_ offset: CGPoint, isCurrentUser: Bool) {
elloAnimate {
let effectsTop: CGFloat
let effectsHeight: CGFloat
if isCurrentUser {
effectsTop = -self.profileButtonsEffect.frame.height
effectsHeight = Size.profileButtonsContainerViewHeight
}
else {
effectsTop = 0
effectsHeight = Globals.isIphoneX
? Size.profileButtonsContainerTallHeight
: Size.profileButtonsContainerViewHeight
}
self.updateNavBars(effectsTop: effectsTop, effectsHeight: effectsHeight)
self.showBackButton = true
super.hideNavBars(animated: false)
}
}
private func updateNavBars(effectsTop: CGFloat, effectsHeight: CGFloat) {
let buttonTop = effectsHeight - Size.buttonMargin - mentionButton.frame.size.height
profileButtonsContainerTopConstraint.update(offset: effectsTop)
profileButtonsEffect.frame.origin.y = effectsTop
profileButtonsContainerHeightConstraint.update(offset: effectsHeight)
profileButtonsEffect.frame.size.height = effectsHeight
[
relationshipControl, roleAdminButton, collaborateButton, hireButton, mentionButton,
inviteButton, editButton
].forEach { button in
button.frame.origin.y = buttonTop
}
}
}
extension ProfileScreen: ArrangeNavBackButton {
func arrangeNavBackButton(_ button: UIButton) {
}
private func updateRoleAdminButton() {
roleAdminButton.isVisible = hasRoleAdminButton
roleAdminVisibleConstraint.set(isActivated: hasRoleAdminButton)
roleAdminHiddenConstraint.set(isActivated: !hasRoleAdminButton)
}
private func updateBackButton() {
let showButton = hasBackButton && showBackButton
showBackButtonConstraint.set(isActivated: showButton)
hideBackButtonConstraint.set(isActivated: !showButton)
persistentBackButton.alpha = showButton ? 1 : 0
profileButtonsEffect.layoutIfNeeded()
}
}
|
mit
|
91a82d41fa8133a8a07af881db7765fe
| 38.336777 | 100 | 0.685278 | 5.177862 | false | false | false | false |
sviatoslav/EndpointProcedure
|
Sources/Alamofire/AlamofireProcedure.swift
|
3
|
1534
|
//
// AlamofireProcedure.swift
// EndpointProcedure
//
// Created by Sviatoslav Yakymiv on 12/18/16.
// Copyright © 2016 Sviatoslav Yakymiv. All rights reserved.
//
#if canImport(ProcedureKit)
import ProcedureKit
#endif
#if canImport(Alamofire)
import Alamofire
#endif
#if canImport(EndpointProcedure)
import EndpointProcedure
#endif
/// Errors that `AlamofireProcedure` can return in `output` property.
public enum AlamofireProcedureError: Swift.Error {
/// Request to server did not fail, but response data is `nil`
case invalidDataRequest
}
/// Procedure that wrapps `Alamofire.DataRequest`
class AlamofireProcedure: Procedure, OutputProcedure {
var output: Pending<ProcedureResult<HTTPResponseData>> = .pending
let request: DataRequest
/// Creates `AlamofireProcedure`.
///
/// - parameter request: `Alamofire.DataRequest` for data loading.
init(request: DataRequest) {
self.request = request
super.init()
}
override func execute() {
self.request.response { [weak self] in
if let error = $0.error {
self?.finish(withResult: .failure(error))
} else {
if let data = $0.data {
let result = HTTPResponseData(urlResponse: $0.response, data: data)
self?.finish(withResult: .success(result))
} else {
self?.finish(withResult: .failure(AlamofireProcedureError.invalidDataRequest))
}
}
}
}
}
|
mit
|
a5813d937d993f35b295fb68d7deaca2
| 27.924528 | 98 | 0.641226 | 4.603604 | false | false | false | false |
sdhjl2000/swiftdialog
|
SwiftDialog/SectionElement.swift
|
1
|
1315
|
// Copyright 2014 Thomas K. Dyas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
public class SectionElement : Element {
public var elements: WrappedArray<Element>
public var header: String?
public var footer: String?
public var headerView: UIView?
public var footerView: UIView?
public init(
elements: WrappedArray<Element> = [],
header: String? = nil,
footer: String? = nil,
headerView: UIView? = nil,
footerView: UIView? = nil
) {
self.elements = elements
self.header = header
self.footer = footer
self.headerView = headerView
self.footerView = footerView
super.init()
for element in self.elements {
element.parent = self
}
}
}
|
apache-2.0
|
49a39ad018ae285e92c8a1f11708698d
| 29.581395 | 75 | 0.658555 | 4.488055 | false | false | false | false |
jsslai/Action
|
Carthage/Checkouts/RxSwift/RxCocoa/Common/RxCocoa.swift
|
1
|
12101
|
//
// RxCocoa.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
#if os(iOS)
import UIKit
#endif
/**
RxCocoa errors.
*/
public enum RxCocoaError
: Swift.Error
, CustomDebugStringConvertible {
/**
Unknown error has occurred.
*/
case unknown
/**
Invalid operation was attempted.
*/
case invalidOperation(object: Any)
/**
Items are not yet bound to user interface but have been requested.
*/
case itemsNotYetBound(object: Any)
/**
Invalid KVO Path.
*/
case invalidPropertyName(object: Any, propertyName: String)
/**
Invalid object on key path.
*/
case invalidObjectOnKeyPath(object: Any, sourceObject: AnyObject, propertyName: String)
/**
Error during swizzling.
*/
case errorDuringSwizzling
/*
Casting error.
*/
case castingError(object: Any, targetType: Any.Type)
}
#if !DISABLE_SWIZZLING
/**
RxCocoa ObjC runtime interception mechanism.
*/
public enum RxCocoaInterceptionMechanism {
/**
Unknown message interception mechanism.
*/
case unknown
/**
Key value observing interception mechanism.
*/
case kvo
}
/**
RxCocoa ObjC runtime modification errors.
*/
public enum RxCocoaObjCRuntimeError
: Swift.Error
, CustomDebugStringConvertible {
/**
Unknown error has occurred.
*/
case unknown(target: AnyObject)
/**
If the object is reporting a different class then it's real class, that means that there is probably
already some interception mechanism in place or something weird is happening.
The most common case when this would happen is when using a combination of KVO (`observe`) and `sentMessage`.
This error is easily resolved by just using `sentMessage` observing before `observe`.
The reason why the other way around could create issues is because KVO will unregister it's interceptor
class and restore original class. Unfortunately that will happen no matter was there another interceptor
subclass registered in hierarchy or not.
Failure scenario:
* KVO sets class to be `__KVO__OriginalClass` (subclass of `OriginalClass`)
* `sentMessage` sets object class to be `_RX_namespace___KVO__OriginalClass` (subclass of `__KVO__OriginalClass`)
* then unobserving with KVO will restore class to be `OriginalClass` -> failure point (possibly a bug in KVO)
The reason why changing order of observing works is because any interception method on unregistration
should return object's original real class (if that doesn't happen then it's really easy to argue that's a bug
in that interception mechanism).
This library won't remove registered interceptor even if there aren't any observers left because
it's highly unlikely it would have any benefit in real world use cases, and it's even more
dangerous.
*/
case objectMessagesAlreadyBeingIntercepted(target: AnyObject, interceptionMechanism: RxCocoaInterceptionMechanism)
/**
Trying to observe messages for selector that isn't implemented.
*/
case selectorNotImplemented(target: AnyObject)
/**
Core Foundation classes are usually toll free bridged. Those classes crash the program in case
`object_setClass` is performed on them.
There is a possibility to just swizzle methods on original object, but since those won't be usual use
cases for this library, then an error will just be reported for now.
*/
case cantInterceptCoreFoundationTollFreeBridgedObjects(target: AnyObject)
/**
Two libraries have simultaneously tried to modify ObjC runtime and that was detected. This can only
happen in scenarios where multiple interception libraries are used.
To synchronize other libraries intercepting messages for an object, use `synchronized` on target object and
it's meta-class.
*/
case threadingCollisionWithOtherInterceptionMechanism(target: AnyObject)
/**
For some reason saving original method implementation under RX namespace failed.
*/
case savingOriginalForwardingMethodFailed(target: AnyObject)
/**
Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason.
*/
case replacingMethodWithForwardingImplementation(target: AnyObject)
/**
Attempt to intercept one of the performance sensitive methods:
* class
* respondsToSelector:
* methodSignatureForSelector:
* forwardingTargetForSelector:
*/
case observingPerformanceSensitiveMessages(target: AnyObject)
/**
Message implementation has unsupported return type (for example large struct). The reason why this is a error
is because in some cases intercepting sent messages requires replacing implementation with `_objc_msgForward_stret`
instead of `_objc_msgForward`.
The unsupported cases should be fairly uncommon.
*/
case observingMessagesWithUnsupportedReturnType(target: AnyObject)
}
#endif
// MARK: Debug descriptions
public extension RxCocoaError {
/**
A textual representation of `self`, suitable for debugging.
*/
public var debugDescription: String {
switch self {
case .unknown:
return "Unknown error occurred."
case let .invalidOperation(object):
return "Invalid operation was attempted on `\(object)`."
case let .itemsNotYetBound(object):
return "Data source is set, but items are not yet bound to user interface for `\(object)`."
case let .invalidPropertyName(object, propertyName):
return "Object `\(object)` dosn't have a property named `\(propertyName)`."
case let .invalidObjectOnKeyPath(object, sourceObject, propertyName):
return "Unobservable object `\(object)` was observed as `\(propertyName)` of `\(sourceObject)`."
case .errorDuringSwizzling:
return "Error during swizzling."
case .castingError(let object, let targetType):
return "Error casting `\(object)` to `\(targetType)`"
}
}
}
#if !DISABLE_SWIZZLING
public extension RxCocoaObjCRuntimeError {
/**
A textual representation of `self`, suitable for debugging.
*/
public var debugDescription: String {
switch self {
case let .unknown(target):
return "Unknown error occurred.\nTarget: `\(target)`"
case let .objectMessagesAlreadyBeingIntercepted(target, interceptionMechanism):
let interceptionMechanismDescription = interceptionMechanism == .kvo ? "KVO" : "other interception mechanism"
return "Collision between RxCocoa interception mechanism and \(interceptionMechanismDescription)."
+ " To resolve this conflict please use this interception mechanism first.\nTarget: \(target)"
case let .selectorNotImplemented(target):
return "Trying to observe messages for selector that isn't implemented.\nTarget: \(target)"
case let .cantInterceptCoreFoundationTollFreeBridgedObjects(target):
return "Interception of messages sent to Core Foundation isn't supported.\nTarget: \(target)"
case let .threadingCollisionWithOtherInterceptionMechanism(target):
return "Detected a conflict while modifying ObjC runtime.\nTarget: \(target)"
case let .savingOriginalForwardingMethodFailed(target):
return "Saving original method implementation failed.\nTarget: \(target)"
case let .replacingMethodWithForwardingImplementation(target):
return "Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason.\nTarget: \(target)"
case let .observingPerformanceSensitiveMessages(target):
return "Attempt to intercept one of the performance sensitive methods. \nTarget: \(target)"
case let .observingMessagesWithUnsupportedReturnType(target):
return "Attempt to intercept a method with unsupported return type. \nTarget: \(target)"
}
}
}
#endif
// MARK: Error binding policies
func bindingErrorToInterface(_ error: Swift.Error) {
let error = "Binding error to UI: \(error)"
#if DEBUG
rxFatalError(error)
#else
print(error)
#endif
}
// MARK: Abstract methods
func rxAbstractMethodWithMessage(_ message: String) -> Swift.Never {
rxFatalError(message)
}
func rxAbstractMethod() -> Swift.Never {
rxFatalError("Abstract method")
}
// MARK: casts or fatal error
// workaround for Swift compiler bug, cheers compiler team :)
func castOptionalOrFatalError<T>(_ value: Any?) -> T? {
if value == nil {
return nil
}
let v: T = castOrFatalError(value)
return v
}
func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
func castOptionalOrThrow<T>(_ resultType: T.Type, _ object: AnyObject) throws -> T? {
if NSNull().isEqual(object) {
return nil
}
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
func castOrFatalError<T>(_ value: AnyObject!, message: String) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError(message)
}
return result
}
func castOrFatalError<T>(_ value: Any!) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError("Failure converting from \(value) to \(T.self)")
}
return result
}
// MARK: Error messages
let dataSourceNotSet = "DataSource not set"
let delegateNotSet = "Delegate not set"
#if !DISABLE_SWIZZLING
// MARK: Conversions `NSError` > `RxCocoaObjCRuntimeError`
extension Error {
func rxCocoaErrorForTarget(_ target: AnyObject) -> RxCocoaObjCRuntimeError {
let error = self as NSError
if error.domain == RXObjCRuntimeErrorDomain {
let errorCode = RXObjCRuntimeError(rawValue: error.code) ?? .unknown
switch errorCode {
case .unknown:
return .unknown(target: target)
case .objectMessagesAlreadyBeingIntercepted:
let isKVO = (error.userInfo[RXObjCRuntimeErrorIsKVOKey] as? NSNumber)?.boolValue ?? false
return .objectMessagesAlreadyBeingIntercepted(target: target, interceptionMechanism: isKVO ? .kvo : .unknown)
case .selectorNotImplemented:
return .selectorNotImplemented(target: target)
case .cantInterceptCoreFoundationTollFreeBridgedObjects:
return .cantInterceptCoreFoundationTollFreeBridgedObjects(target: target)
case .threadingCollisionWithOtherInterceptionMechanism:
return .threadingCollisionWithOtherInterceptionMechanism(target: target)
case .savingOriginalForwardingMethodFailed:
return .savingOriginalForwardingMethodFailed(target: target)
case .replacingMethodWithForwardingImplementation:
return .replacingMethodWithForwardingImplementation(target: target)
case .observingPerformanceSensitiveMessages:
return .observingPerformanceSensitiveMessages(target: target)
case .observingMessagesWithUnsupportedReturnType:
return .observingMessagesWithUnsupportedReturnType(target: target)
}
}
return RxCocoaObjCRuntimeError.unknown(target: target)
}
}
#endif
// MARK: Shared with RxSwift
#if !RX_NO_MODULE
func rxFatalError(_ lastMessage: String) -> Never {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage)
}
#endif
|
mit
|
7b52b48bea6e3cfedf614a8b3d62163d
| 34.072464 | 152 | 0.696612 | 4.9509 | false | false | false | false |
rrunfa/StreamRun
|
StreamRun/Classes/StreamServiceClients/TwitchClient.swift
|
1
|
1039
|
//
// TwitchClient.swift
// StreamRun
//
// Created by Nikita Nagajnik on 19/10/14.
// Copyright (c) 2014 rrunfa. All rights reserved.
//
import Foundation
class TwitchClient: NSObject, StreamServiceClient {
func checkOnlineChannel(channel: String, result: (Bool, Bool) -> ()) {
let url = NSURL(string: "https://api.twitch.tv/kraken/streams".stringByAddQueryParams(["channel": channel]))
dispatch_async(dispatch_get_global_queue(0, 0)) {
let request = NSURLRequest(URL: url!)
var response: NSURLResponse?
var error: NSError?
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
dispatch_async(dispatch_get_main_queue()) {
if let d = data {
let json = JSON(data: d)
result(json["streams"].arrayValue.count > 0, false)
} else {
result(false, true)
}
}
}
}
}
|
mit
|
22177bbad8776377c2a380e6aee40179
| 32.516129 | 116 | 0.568816 | 4.27572 | false | false | false | false |
sammyd/VT_InAppPurchase
|
prototyping/GreenGrocer/GreenGrocer/DataStoreIAP.swift
|
1
|
2337
|
/*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
private let ShoppingListCountKey = "ShoppingListCount"
extension DataStore {
private(set) var numberAvailableShoppingLists: Int {
get {
return readNumberShoppingLists()
}
set(newValue) {
writeNumberShoppingLists(newValue)
}
}
func purchaseNewShoppingLists(productID: String) {
guard let product = GreenGrocerPurchase(productId: productID) else { return }
var numberOfShoppingListsToAdd: Int
switch product {
case .NewShoppingLists_One:
numberOfShoppingListsToAdd = 1
case .NewShoppingLists_Five:
numberOfShoppingListsToAdd = 5
case .NewShoppingLists_Ten:
numberOfShoppingListsToAdd = 10
default:
numberOfShoppingListsToAdd = 0
}
numberAvailableShoppingLists += numberOfShoppingListsToAdd
}
func useShoppingList() {
numberAvailableShoppingLists -= 1
}
private func readNumberShoppingLists() -> Int {
return NSUserDefaults.standardUserDefaults().integerForKey(ShoppingListCountKey)
}
private func writeNumberShoppingLists(number: Int) {
NSUserDefaults.standardUserDefaults().setInteger(number, forKey: ShoppingListCountKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
|
mit
|
a8b8d6e9a9fd237b347ebb8cfd7318d6
| 34.409091 | 90 | 0.754814 | 4.769388 | false | false | false | false |
TG908/iOS
|
TUM Campus App/TuitionCardTableViewCell.swift
|
1
|
934
|
//
// TuitionCard.swift
// TUM Campus App
//
// Created by Mathias Quintero on 12/6/15.
// Copyright © 2015 LS1 TUM. All rights reserved.
//
import UIKit
class TuitionCardTableViewCell: CardTableViewCell {
override func setElement(_ element: DataElement) {
if let tuitionElement = element as? Tuition {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "MMM dd, yyyy"
deadLineLabel.text = dateformatter.string(from: tuitionElement.frist as Date)
balanceLabel.text = tuitionElement.soll + " €"
}
}
@IBOutlet weak var cardView: UIView! {
didSet {
backgroundColor = UIColor.clear
cardView.layer.shadowOpacity = 0.4
cardView.layer.shadowOffset = CGSize(width: 3.0, height: 2.0)
}
}
@IBOutlet weak var deadLineLabel: UILabel!
@IBOutlet weak var balanceLabel: UILabel!
}
|
gpl-3.0
|
a22fcd6ffd05bbdcfbfa96639c8ed905
| 28.09375 | 89 | 0.635875 | 4.174888 | false | false | false | false |
DenHeadless/DTTableViewManager
|
Example/Controllers/AutoDiffSearchViewController.swift
|
1
|
2291
|
//
// AutoDiffSearchViewController.swift
// Example
//
// Created by Denys Telezhkin on 22.09.2018.
// Copyright © 2018 Denys Telezhkin. All rights reserved.
//
import UIKit
import DTTableViewManager
import Changeset
struct ChangesetDiffer : EquatableDiffingAlgorithm {
func diff<T>(from: [T], to: [T]) -> [SingleSectionOperation] where T : EntityIdentifiable, T : Equatable {
let changeset = Changeset.edits(from: from, to: to)
return changeset.map {
switch $0.operation {
case .deletion: return SingleSectionOperation.delete($0.destination)
case .insertion: return SingleSectionOperation.insert($0.destination)
case .substitution: return SingleSectionOperation.update($0.destination)
case .move(origin: let offset): return SingleSectionOperation.move(from: offset, to: $0.destination)
}
}
}
}
extension String: EntityIdentifiable {
public var identifier: AnyHashable { return self }
}
class AutoDiffSearchViewController: UITableViewController, DTTableViewManageable, UISearchResultsUpdating {
let searchController = UISearchController(searchResultsController: nil)
let spells = [
"Riddikulus", "Obliviate", "Sectumsempra", "Avada Kedavra",
"Alohomora", "Lumos", "Expelliarmus", "Wingardium Leviosa",
"Accio", "Expecto Patronum"
]
lazy var storage = SingleSectionEquatableStorage(items: spells, differ: ChangesetDiffer())
override func viewDidLoad() {
super.viewDidLoad()
manager = DTTableViewManager(storage: storage)
manager.register(UITableViewCell.self, for: String.self) { cell, model, _ in
cell.textLabel?.text = model
}
searchController.searchResultsUpdater = self
navigationItem.hidesSearchBarWhenScrolling = false
navigationItem.searchController = searchController
}
func updateSearchResults(for searchController: UISearchController) {
guard let query = searchController.searchBar.text, !query.isEmpty else {
storage.setItems(spells)
return
}
storage.setItems(spells.filter { $0.lowercased().contains(searchController.searchBar.text?.lowercased() ?? "") })
}
}
|
mit
|
366303066bb3b81904c9a5f1aac71092
| 35.349206 | 121 | 0.681223 | 4.598394 | false | false | false | false |
hagmas/APNsKit
|
APNsKit/PushViewController.playground/Sources/PushViewController.swift
|
1
|
1825
|
import Foundation
import UIKit
import APNsKit
public class PushViewController: UIViewController {
let pushButton = UIButton(type: .system)
let connection: Connection
let request: APNsRequest
public init?(p12FileName: String, passPhrase: String, request: APNsRequest) {
do {
let connection = try Connection(p12FileName: p12FileName, passPhrase: passPhrase)
self.connection = connection
self.request = request
super.init(nibName: nil, bundle: nil)
} catch {
print("Failed to create connection: \(error)")
return nil
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func loadView() {
super.loadView()
view.backgroundColor = UIColor.white
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
pushButton.setTitle( "⚡️Push⚡️", for: .normal)
pushButton.titleLabel?.font = UIFont.systemFont(ofSize: 30.0)
pushButton.sizeToFit()
pushButton.translatesAutoresizingMaskIntoConstraints = false
pushButton.addTarget(self, action: #selector(pushed), for: .touchUpInside)
view.addSubview(pushButton)
pushButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
pushButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
func pushed() {
connection.send(request: request) {
switch $0 {
case .success:
print("Succeeded!")
case .failure(let errorCode, let message):
print("Failed to push! \(errorCode), \(message)")
}
}
}
}
|
mit
|
7eb1314e8002f7e68b280de88c228f64
| 32.036364 | 93 | 0.614199 | 4.964481 | false | false | false | false |
away4m/Vendors
|
Vendors/Extensions/FileManager.swift
|
1
|
16859
|
//
// FileManager.swift
// Pods
//
// Created by away4m on 12/30/16.
//
//
import Foundation
/// BFKit errors enum.
///
/// - jsonSerialization: JSONSerialization error.
/// - errorLoadingSound: Could not load sound error.
/// - pathNotExist: Path not exist error.
/// - pathNotAllowed: Path not allowed error.
public enum BFKitError: Error {
case jsonSerialization
case errorLoadingSound
case pathNotExist
case pathNotAllowed
}
// MARK: - FileManager extension
/// This extension adds some useful functions to FileManager.
public extension FileManager {
/// SwifterSwift: Read from a JSON file at a given path.
///
/// - Parameters:
/// - path: JSON file path.
/// - options: JSONSerialization reading options.
/// - Returns: Optional dictionary.
/// - Throws: Throws any errors thrown by Data creation or JSON serialization.
public func jsonFromFile(
atPath path: String,
readingOptions: JSONSerialization.ReadingOptions = .allowFragments
) throws -> [String: Any]? {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let json = try JSONSerialization.jsonObject(with: data, options: readingOptions)
return json as? [String: Any]
}
/// SwifterSwift: Read from a JSON file with a given filename.
///
/// - Parameters:
/// - filename: File to read.
/// - bundleClass: Bundle where the file is associated.
/// - readingOptions: JSONSerialization reading options.
/// - Returns: Optional dictionary.
/// - Throws: Throws any errors thrown by Data creation or JSON serialization.
public func jsonFromFile(
withFilename filename: String,
at bundleClass: AnyClass? = nil,
readingOptions: JSONSerialization.ReadingOptions = .allowFragments
) throws -> [String: Any]? {
// https://stackoverflow.com/questions/24410881/reading-in-a-json-file-using-swift
// To handle cases that provided filename has an extension
let name = filename.components(separatedBy: ".")[0]
let bundle = bundleClass != nil ? Bundle(for: bundleClass!) : Bundle.main
if let path = bundle.path(forResource: name, ofType: "json") {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let json = try JSONSerialization.jsonObject(with: data, options: readingOptions)
return json as? [String: Any]
}
return nil
}
// MARK: - Variables
/// Path type enum.
///
/// - mainBundle: Main bundle path.
/// - library: Library path.
/// - documents: Documents path.
/// - cache: Cache path.
public enum PathType: Int {
case mainBundle
case library
case documents
case cache
case tmp
case applicationSupport
}
// MARK: - Functions
/// Get the path for a PathType.
///
/// - Parameter path: Path type.
/// - Returns: Returns the path type String.
public func pathFor(_ path: PathType) -> String? {
var pathString: String?
switch path {
case .mainBundle:
pathString = mainBundlePath()
case .library:
pathString = libraryPath()
case .documents:
pathString = documentsPath()
case .cache:
pathString = cachePath()
case .applicationSupport:
pathString = applicationSupportPath()
case .tmp:
pathString = NSTemporaryDirectory()
}
return pathString
}
/// Save a file with given content.
///
/// - Parameters:
/// - file: File to be saved.
/// - path: File path.
/// - content: Content to be saved.
/// - Throws: write(toFile:, atomically:, encoding:) errors.
public func save(file: String, in path: PathType, content: String) throws {
guard let path = FileManager.default.pathFor(path) else {
return
}
try content.write(toFile: path.appendingPathComponent(file), atomically: true, encoding: .utf8)
}
/// Read a file an returns the content as String.
///
/// - Parameters:
/// - file: File to be read.
/// - path: File path.
/// - Returns: Returns the content of the file a String.
/// - Throws: Throws String(contentsOfFile:, encoding:) errors.
public func read(file: String, from path: PathType) throws -> String? {
guard let path = FileManager.default.pathFor(path) else {
return nil
}
return try String(contentsOfFile: path.appendingPathComponent(file), encoding: .utf8)
}
/// Save an object into a PLIST with given filename.
///
/// - Parameters:
/// - object: Object to save into PLIST.
/// - path: Path of PLIST.
/// - filename: PLIST filename.
/// - Returns: Returns true if the operation was successful, otherwise false.
@discardableResult
public func savePlist(object: Any, in path: PathType, filename: String) -> Bool {
let path = checkPlist(path: path, filename: filename)
if path.exist {
return NSKeyedArchiver.archiveRootObject(object, toFile: path.path)
}
return false
}
/// Load an object from a PLIST with given filename.
///
/// - Parameters:
/// - path: Path of PLIST.
/// - filename: PLIST filename.
/// - Returns: Returns the loaded object.
public func readPlist(from path: PathType, filename: String) -> Any? {
let path = checkPlist(path: path, filename: filename)
if path.exist {
return NSKeyedUnarchiver.unarchiveObject(withFile: path.path)
}
return nil
}
/// Check if plist exist.
///
/// - Parameters:
/// - path: Path of plist.
/// - filename: Plist filename.
/// - Returns: Returns if plist exists and path.
private func checkPlist(path: PathType, filename: String) -> (exist: Bool, path: String) {
guard let path = FileManager.default.pathFor(path), let finalPath = path.appendingPathComponent(filename).appendingPathExtension("plist") else {
return (false, "")
}
return (true, finalPath)
}
/// Get Main Bundle path for a filename.
///
/// - Parameter file: Filename
/// - Returns: Returns the path as a String.
public func mainBundlePath(file: String = "") -> String? {
return Bundle.main.path(forResource: file.deletingPathExtension, ofType: file.pathExtension)
}
/// Get Documents path for a filename.
///
/// - Parameter file: Filename
/// - Returns: Returns the path as a String.
public func documentsPath(file: String = "") -> String? {
guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
return nil
}
return documentsURL.path.appendingPathComponent(file)
}
/// Get Library path for a filename.
///
/// - Parameter file: Filename
/// - Returns: Returns the path as a String.
public func libraryPath(file: String = "") -> String? {
guard let libraryURL = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first else {
return nil
}
return libraryURL.path.appendingPathComponent(file)
}
/// Get Cache path for a filename.
///
/// - Parameter file: Filename
/// - Returns: Returns the path as a String.
public func cachePath(file: String = "") -> String? {
guard let cacheURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
return nil
}
return cacheURL.path.appendingPathComponent(file)
}
/// Get Application Support path for a filename.
///
/// - Parameter file: Filename
/// - Returns: Returns the path as a String.
public func applicationSupportPath(file: String = "") -> String? {
guard let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else {
return nil
}
return applicationSupportURL.path.appendingPathComponent(file)
}
/// Returns the file size.
///
/// - Parameters:
/// - file: Filename.
/// - path: Path of the file.
/// - Returns: Returns the file size.
/// - Throws: Throws FileManager.default.attributesOfItem(atPath: ) errors.
public func size(file: String, from path: PathType) throws -> Float? {
if !file.characters.isEmpty {
guard let path = FileManager.default.pathFor(path) else {
return nil
}
let finalPath = path.appendingPathComponent(file)
if FileManager.default.fileExists(atPath: finalPath) {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: finalPath)
return fileAttributes[FileAttributeKey.size] as? Float
}
}
return nil
}
/// Delete a file with the given filename.
///
/// - Parameters:
/// - file: File to delete.
/// - path: Path of the file.
/// - Throws: Throws FileManager.default.removeItem(atPath: ) errors.
public func delete(file: String, from path: PathType) throws {
if !file.characters.isEmpty {
guard let path = FileManager.default.pathFor(path) else {
throw BFKitError.pathNotExist
}
if FileManager.default.fileExists(atPath: path.appendingPathComponent(file)) {
try FileManager.default.removeItem(atPath: path.appendingPathComponent(file))
}
}
}
/// Move a file from a path to another.
///
/// - Parameters:
/// - file: Filename to move.
/// - origin: Origin path of the file.
/// - destination: Destination path of the file.
/// - Returns: Returns true if the operation was successful, otherwise false.
/// - Throws: Throws FileManager.default.moveItem(atPath:, toPath:) and BFKitError errors.
public func move(file: String, from origin: PathType, to destination: PathType) throws {
let paths = try check(file: file, origin: origin, destination: destination)
if paths.fileExist {
try FileManager.default.moveItem(atPath: paths.origin, toPath: paths.destination)
}
}
/// Copy a file into another path.
///
/// - Parameters:
/// - file: Filename to copy.
/// - origin: Origin path
/// - destination: Destination path
/// - Returns: Returns true if the operation was successful, otherwise false.
/// - Throws: Throws FileManager.default.copyItem(atPath:, toPath:) and BFKitError errors.
public func copy(file: String, from origin: PathType, to destination: PathType) throws {
let paths = try check(file: file, origin: origin, destination: destination)
if paths.fileExist {
try FileManager.default.copyItem(atPath: paths.origin, toPath: paths.destination)
}
}
/// Check is orign path, destination path and file exists.
///
/// - Parameters:
/// - file: File.
/// - origin: Origin path.
/// - destination: Destination path.
/// - Returns: Returns a tuple with origin, destination and if file exist.
/// - Throws: Throws BFKitError errors.
private func check(file: String, origin: PathType, destination: PathType) throws -> (origin: String, destination: String, fileExist: Bool) {
guard let originPath = FileManager.default.pathFor(origin), let destinationPath = FileManager.default.pathFor(destination) else {
throw BFKitError.pathNotExist
}
guard destination != .mainBundle else {
throw BFKitError.pathNotAllowed
}
let finalOriginPath = originPath.appendingPathComponent(file)
let finalDestinationPath = destinationPath.appendingPathComponent(file)
if FileManager.default.fileExists(atPath: finalOriginPath) {
return (finalOriginPath, finalDestinationPath, true)
}
return (finalOriginPath, finalDestinationPath, false)
}
/// Rename a file with another filename.
///
/// - Parameters:
/// - file: Filename to rename.
/// - origin: Origin path.
/// - newName: New filename.
/// - Returns: Returns true if the operation was successful, otherwise false.
/// - Throws: Throws FileManager.default.copyItem(atPath:, toPath:), FileManager.default.removeItem(atPath:, toPath:) and BFKitError errors.
public func rename(file: String, in origin: PathType, to newName: String) throws {
guard let originPath = FileManager.default.pathFor(origin) else {
throw BFKitError.pathNotExist
}
let finalOriginPath = originPath.appendingPathComponent(file)
if FileManager.default.fileExists(atPath: finalOriginPath) {
let destinationPath: String = finalOriginPath.replacingOccurrences(of: file, with: newName)
try FileManager.default.copyItem(atPath: finalOriginPath, toPath: destinationPath)
try FileManager.default.removeItem(atPath: finalOriginPath)
}
}
/// Set settings for object and key. The file will be saved in the Library path if not exist.
///
/// - Parameters:
/// - filename: Settings filename. "-Settings" will be automatically added.
/// - object: Object to set.
/// - objKey: Object key.
/// - Returns: Returns true if the operation was successful, otherwise false.
/// - Throws: Throws BFKitError errors.
@discardableResult
public func setSettings(filename: String, object: Any, forKey objKey: String) -> Bool {
guard var path = FileManager.default.pathFor(.applicationSupport) else {
return false
}
path = path.appendingPathComponent("\(filename)-Settings.plist")
var loadedPlist: NSMutableDictionary
if FileManager.default.fileExists(atPath: path) {
loadedPlist = NSMutableDictionary(contentsOfFile: path)!
} else {
loadedPlist = NSMutableDictionary()
}
loadedPlist[objKey] = object
return loadedPlist.write(toFile: path, atomically: true)
}
/// Get settings for key.
///
/// - Parameters:
/// - filename: Settings filename. "-Settings" will be automatically added.
/// - forKey: Object key.
/// - Returns: Returns the object for the given key.
public func getSettings(filename: String, forKey: String) -> Any? {
guard var path = FileManager.default.pathFor(.applicationSupport) else {
return nil
}
path = path.appendingPathComponent("\(filename)-Settings.plist")
var loadedPlist: NSMutableDictionary
if FileManager.default.fileExists(atPath: path) {
loadedPlist = NSMutableDictionary(contentsOfFile: path)!
} else {
return nil
}
return loadedPlist.object(forKey: forKey)
}
class func folderSize(folderPath: String) -> UInt64 {
var fileSize: UInt64 = 0
do {
// @see http://stackoverflow.com/questions/2188469/calculate-the-size-of-a-folder
let filesArray: [String] = try FileManager.default.subpathsOfDirectory(atPath: folderPath) as [String]
for fileName in filesArray {
let filePath = folderPath.appendingPathComponent(fileName)
let fileDictionary: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(atPath: filePath)
fileSize += fileDictionary[FileAttributeKey.size] as! UInt64
}
} catch {
trace(error)
}
return fileSize
}
class func each(folderPath: String, recursive: Bool = false, _ each: (String, [FileAttributeKey: Any]) -> Void) {
var fileSize: UInt64 = 0
do {
// @see http://stackoverflow.com/questions/2188469/calculate-the-size-of-a-folder
var filesArray: [String] = []
if recursive {
filesArray = try FileManager.default.subpathsOfDirectory(atPath: folderPath) as [String]
} else {
filesArray = try FileManager.default.contentsOfDirectory(atPath: folderPath) // .map({ folderPath.appendingPathComponent($0) })
}
for fileName in filesArray {
let filePath = folderPath.appendingPathComponent(fileName)
let fileDictionary: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(atPath: filePath)
each(filePath, fileDictionary)
}
} catch {
traceError(error)
}
}
}
|
mit
|
3d22a5a3c8c60a3caa465b095f5109c9
| 35.65 | 152 | 0.625601 | 4.79085 | false | false | false | false |
NorgannasAddOns/ColorDial
|
ColorDial/Picker.swift
|
1
|
10712
|
//
// Picker.swift
// ColorDial
//
// Created by Kenneth Allan on 7/12/2015.
// Copyright © 2015 Kenneth Allan. All rights reserved.
//
import Cocoa
class Picker: NSView {
let pickerSize: CGFloat = 149.0 // Must be odd number
let blockSize: Int = 11 // Must be odd number
var parent: ViewController!
var circle: NSBezierPath!
var image: CGImage!
var imageRep: NSBitmapImageRep!
var centerColor: NSColor!
var pixels: [PixelData]!
var picking: Bool = false
var scaleFactor: CGFloat = 0.0
var delegate: ColorSupplyDelegate?
/**
* Courtesy HumanFriendly:
* http://blog.human-friendly.com/drawing-images-from-pixel-data-in-swift
* Modified to work with Swift 2 and NSImage
*
* {{{
*/
internal struct PixelData {
var a: UInt8 = 255
var r: UInt8 = 0
var g: UInt8 = 0
var b: UInt8 = 0
}
fileprivate let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
fileprivate let bitmapInfo: CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
internal func imageFromARGB32Bitmap(_ pixels: [PixelData], width: Int, height: Int) -> NSImage {
let bitsPerComponent: Int = 8
let bitsPerPixel: Int = 32
let pixelSize = MemoryLayout<PixelData>.size
assert(pixels.count == Int(width * height))
var data = pixels // Copy to mutable []
let dataCopy = Data(bytes: &data, count: data.count * pixelSize)
let providerRef = CGDataProvider(
data: dataCopy as CFData
)
let cgimage = CGImage(
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bitsPerPixel: bitsPerPixel,
bytesPerRow: width * pixelSize,
space: rgbColorSpace,
bitmapInfo: bitmapInfo,
provider: providerRef!,
decode: nil,
shouldInterpolate: true,
intent: CGColorRenderingIntent.defaultIntent
)
return NSImage(cgImage: cgimage!, size: NSSize(width: width, height: height))
}
// }}}
required init?(coder: NSCoder) {
super.init(coder: coder)!
}
override func awakeFromNib() {
setItemPropertiesToDefault()
}
/**
* Draws a block of blockSize x blockSize around the pixel at x, y.
*/
func drawBlock(_ x: Int, y: Int, c: NSColor, blockSize: Int) {
let r = UInt8(c.redComponent * 255)
let g = UInt8(c.greenComponent * 255)
let b = UInt8(c.blueComponent * 255)
let offs = Int(floor(CGFloat(blockSize) / 2))
let size = Int(pickerSize)
for p in -offs ... offs {
for q in -offs ... offs {
let bx = x + p
let by = y + q
if (bx < 0 || by < 0) { continue }
if (bx >= size || by >= size) { continue }
let pos = by * size + bx
pixels[pos].r = r
pixels[pos].g = g
pixels[pos].b = b
}
}
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if (image == nil) { return }
objc_sync_enter(self)
let cmid = Int(round(imageRep.size.width/2))
let half = Int(round(pickerSize / 2))
let limit = Int(ceil(pickerSize / CGFloat(blockSize)))
let mid = Int(floor(CGFloat(limit) / 2))
let offs = Int(floor(CGFloat(blockSize) / 2))
for x in -mid ..< mid {
for y in -mid ..< mid {
guard let c = imageRep.colorAt(x: cmid + x + offsX, y: cmid + y + offsY) else {
continue
}
if (x == 0 && y == 0) {
centerColor = c
continue
}
drawBlock(
half + blockSize * x, // + (x<0 ? offs : -offs),
y: half + blockSize * y, // + (y<0 ? offs : -offs),
c: c,
blockSize: blockSize
)
}
}
objc_sync_exit(self)
drawBlock(
half,
y: half,
c: centerColor,
blockSize: blockSize + offs
)
if let delegate = self.delegate {
if (!centerColor.isEqual(to: lastColor)) {
delegate.colorSampled(centerColor)
lastColor = centerColor
}
}
let scaled = imageFromARGB32Bitmap(pixels, width: Int(pickerSize), height: Int(pickerSize))
//parent.eyeDropper.image = scaled
NSColor(patternImage: scaled).setFill()
circle.fill()
NSColor.black.setStroke()
circle.lineWidth = 2
circle.stroke()
NSColor.white.setStroke()
circle.lineWidth = 1
circle.stroke()
circle.move(to: NSPoint(x: 2, y: half))
circle.line(to: NSPoint(x: half - offs, y: half))
circle.move(to: NSPoint(x: Int(pickerSize) - 2, y: half))
circle.line(to: NSPoint(x: half + offs, y: half))
circle.move(to: NSPoint(x: half, y: 2))
circle.line(to: NSPoint(x: half, y: half - offs))
circle.move(to: NSPoint(x: half, y: Int(pickerSize) - 2))
circle.line(to: NSPoint(x: half, y: half + offs))
}
@objc func timerDidFire(_ timer: Timer!) {
if (window!.isVisible) {
handleMouseMovement()
}
}
func changeShapeToSquare() {
circle = NSBezierPath(roundedRect: NSRect(x: 1, y: 1, width: pickerSize - 2, height: pickerSize - 2), xRadius: 5, yRadius: 5)
setNeedsDisplay(self.bounds)
}
func setItemPropertiesToDefault() {
circle = NSBezierPath(ovalIn: NSRect(x: 1, y: 1, width: pickerSize - 2, height: pickerSize - 2))
Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(Picker.timerDidFire(_:)), userInfo: nil, repeats: true)
frame = NSRect(x: 0, y: 0, width: pickerSize, height: pickerSize)
let t = NSTrackingArea(
rect: frame,
options: [
NSTrackingArea.Options.activeAlways,
NSTrackingArea.Options.mouseEnteredAndExited,
NSTrackingArea.Options.mouseMoved
],
owner: self,
userInfo: nil
)
self.addTrackingArea(t)
pixels = [PixelData](repeating: PixelData(), count: Int(pickerSize * pickerSize))
setNeedsDisplay(frame)
}
var downInView: Bool = false
var lastColor: NSColor!
var lastX: CGFloat = 0
var lastY: CGFloat = 0
var offsX: Int = 0
var offsY: Int = 0
func handleMouseMovement() {
if (!picking) {
return
}
let m = NSEvent.mouseLocation
let half = pickerSize / 2.0
let nx = m.x - half
let ny = m.y - half
window!.setFrame(NSRect(
x: nx,
y: ny,
width: pickerSize,
height: pickerSize),
display: true,
animate: false
)
let limit = Int(ceil(pickerSize / CGFloat(blockSize)))
let halflimit = limit / 2
let carbonPoint = carbonScreenPointFromCocoaScreenPoint(NSPoint(x: m.x, y: m.y))
let s = NSRect(x: Int(carbonPoint.x) - halflimit, y: Int(carbonPoint.y) - halflimit, width: limit, height: limit)
if scaleFactor == 2.0 {
if m.x > lastX {
offsX = 0
} else if m.x < lastX {
offsX = 1
}
if m.y > lastY {
offsY = 1
} else if m.y < lastY {
offsY = 0
}
} else {
offsX = 0
offsY = 0
}
lastX = m.x
lastY = m.y
image = CGWindowListCreateImage(s, CGWindowListOption.optionOnScreenBelowWindow, CGWindowID(window!.windowNumber), CGWindowImageOption.bestResolution)
objc_sync_enter(self)
imageRep = NSBitmapImageRep(cgImage: image!)
objc_sync_exit(self)
setNeedsDisplay(frame)
}
override func mouseMoved(with theEvent: NSEvent) {
handleMouseMovement()
}
override func mouseExited(with theEvent: NSEvent) {
handleMouseMovement()
}
override func mouseDown(with theEvent: NSEvent) {
downInView = false
let click = self.convert(theEvent.locationInWindow, from: nil)
if (circle.contains(click)) {
downInView = true
}
}
func closePicker() {
NSCursor.unhide()
window!.orderOut(window!)
picking = false
}
override func mouseUp(with theEvent: NSEvent) {
if (downInView) {
downInView = false
let click = self.convert(theEvent.locationInWindow, from: nil)
if (circle.contains(click)) {
if !theEvent.modifierFlags.contains(NSEvent.ModifierFlags.command) {
closePicker()
}
if let delegate = self.delegate {
delegate.colorSupplied(centerColor, sender: nil)
}
}
}
}
func carbonScreenPointFromCocoaScreenPoint(_ cocoaPoint: NSPoint) -> NSPoint {
//debugPrint("Convert")
for screen in NSScreen.screens {
/*debugPrint(
String(format: "Test if %0.1f, %0.1f inside %0.1f, %0.1f @ %0.1f x %0.1f",
cocoaPoint.x, cocoaPoint.y,
screen.frame.origin.x, screen.frame.origin.y, screen.frame.size.width, screen.frame.size.height
)
)*/
let sr = NSRect(x: screen.frame.origin.x, y: screen.frame.origin.y - 1, width: screen.frame.size.width, height: screen.frame.size.height + 2)
if sr.contains(cocoaPoint) {
let screenHeight = screen.frame.size.height
let convertY = screenHeight + screen.frame.origin.y - cocoaPoint.y - 1
//debugPrint(String(format: " Converting y to %0.1f + %0.1f - %0.1f - 1 = %0.1f", screenHeight, screen.frame.origin.y, cocoaPoint.y, convertY))
scaleFactor = screen.backingScaleFactor
return NSPoint(x: cocoaPoint.x, y: convertY)
}
}
return NSPoint(x: 0, y: 0)
}
}
|
agpl-3.0
|
e2488c197dc061540e6ecf56eb60383d
| 30.59587 | 160 | 0.527215 | 4.313733 | false | false | false | false |
longjianjiang/Drizzling
|
Drizzling/Drizzling/Controller/LJAskUseLocationViewController.swift
|
1
|
1858
|
//
// LJAskUseLocationViewController.swift
// Drizzling
//
// Created by longjianjiang on 2017/10/19.
// Copyright © 2017年 Jiang. All rights reserved.
//
import UIKit
import MapKit
class LJAskUseLocationViewController: UIViewController {
@IBOutlet weak var msgLabel: UILabel!
@IBOutlet weak var yesBtn: UIButton!
@IBOutlet weak var noBtn: UIButton!
@IBAction func didClickBtn(_ sender: UIButton) {
let defaults = UserDefaults.standard
if sender == yesBtn {
LJLocationManager.shared.askLocation()
LJLocationManager.shared.authorizationDelegate = self
} else {
view.window?.rootViewController = LJAskNotificationViewController()
}
defaults.setValue(LJConstants.UserDefaultsValue.chooseLocation, forKey: LJConstants.UserDefaultsKey.askLocation)
}
override func viewDidLoad() {
super.viewDidLoad()
msgLabel.numberOfLines = 0
msgLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
msgLabel.text = "Allow us to access your location to give you hour-by-hour weather forecast"
yesBtn.layer.cornerRadius = 20
yesBtn.layer.borderWidth = 1.0
yesBtn.layer.borderColor = UIColor.white.cgColor
yesBtn.setTitle("Sounds great", for: .normal)
noBtn.setTitle("No, thanks", for: .normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension LJAskUseLocationViewController: LJLocationManagerAuthorizationDelegate {
func locationManager(_ manager: LJLocationManager, userDidChooseLocation status: CLAuthorizationStatus) {
if status == .notDetermined {
return
}
view.window?.rootViewController = LJAskNotificationViewController()
}
}
|
apache-2.0
|
d91afd0356fcc4d8fc1bc28cffc777a4
| 30.440678 | 120 | 0.677089 | 5.152778 | false | false | false | false |
vermont42/Conjugar
|
Conjugar/ConjugationDataSource.swift
|
1
|
3699
|
//
// ConjugationDataSource.swift
// Conjugar
//
// Created by Joshua Adams on 1/15/18.
// Copyright © 2018 Josh Adams. All rights reserved.
//
import UIKit
enum ConjugationRow {
case tense(Tense)
case conjugation(Tense, PersonNumber, String)
}
class ConjugationDataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
let rowCount: Int
let verb: String
weak var table: UITableView?
var rows: [ConjugationRow] = []
init(verb: String, table: UITableView, secondSingularBrowse: SecondSingularBrowse) {
self.verb = verb
self.table = table
let tenses = Tense.conjugatedTenses
rowCount = tenses.reduce(0, { $0 + $1.conjugationCount(secondSingularBrowse: secondSingularBrowse) }) + tenses.count
super.init()
tenses.forEach { tense in
self.rows.append(.tense(tense))
if tense.hasYoForm {
let yoResult = Conjugator.shared.conjugate(infinitive: verb, tense: tense, personNumber: .firstSingular)
switch yoResult {
case let .success(value):
self.rows.append(.conjugation(tense, .firstSingular, value))
default:
fatalError("No yo form found for tense \(tense.displayName).")
}
}
let tuResult = Conjugator.shared.conjugate(infinitive: verb, tense: tense, personNumber: .secondSingularTú)
let tuConjugation: String
switch tuResult {
case let .success(value):
tuConjugation = value
default:
fatalError("No tú form found for tense \(tense.displayName).")
}
let vosResult = Conjugator.shared.conjugate(infinitive: verb, tense: tense, personNumber: .secondSingularVos)
let vosConjugation: String
switch vosResult {
case let .success(value):
vosConjugation = value
default:
fatalError("No vos form found for tense \(tense.displayName).")
}
switch secondSingularBrowse {
case .tu:
self.rows.append(.conjugation(tense, .secondSingularTú, tuConjugation))
case .vos:
self.rows.append(.conjugation(tense, .secondSingularVos, vosConjugation))
case .both:
self.rows.append(.conjugation(tense, .secondSingularTú, tuConjugation))
self.rows.append(.conjugation(tense, .secondSingularVos, vosConjugation))
}
[PersonNumber.thirdSingular, .firstPlural, .secondPlural, .thirdPlural].forEach { personNumber in
let result = Conjugator.shared.conjugate(infinitive: verb, tense: tense, personNumber: personNumber)
switch result {
case let .success(value):
self.rows.append(.conjugation(tense, personNumber, value))
default:
fatalError("No \(personNumber.pronoun) form found.")
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rowCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch rows[indexPath.row] {
case .tense(let tense):
guard let cell = table?.dequeueReusableCell(withIdentifier: TenseCell.identifier) as? TenseCell else {
fatalError("Failed to dequeue cell for tense \(tense).")
}
cell.configure(tense: tense.titleCaseName)
return cell
case .conjugation(let tense, let personNumber, let conjugation):
guard let cell = table?.dequeueReusableCell(withIdentifier: ConjugationCell.identifier) as? ConjugationCell else {
fatalError("Failed to dequeue cell for tense \(tense), personNumber \(personNumber), and conjugation \(conjugation).")
}
cell.configure(tense: tense, personNumber: personNumber, conjugation: conjugation)
return cell
}
}
}
|
agpl-3.0
|
026bd25d418a76e76c8a26486b148968
| 37.082474 | 126 | 0.684624 | 4.330598 | false | false | false | false |
chatea/BulletinBoard
|
BulletinBoard/MsgCollection/LabelCollectionViewItem.swift
|
1
|
840
|
//
import Foundation
import AppKit
class LabelObject: NSObject {
var title:String
init(title:String) {
self.title = title
}
}
class LabelCollectionViewItem: NSCollectionViewItem {
// MARK: properties
var labelObject:LabelObject? {
return representedObject as? LabelObject
}
override var selected: Bool {
didSet {
(self.view as! LabelCollectionViewItemView).selected = selected
}
}
override var highlightState: NSCollectionViewItemHighlightState {
didSet {
(self.view as! LabelCollectionViewItemView).highlightState = highlightState
}
}
// MARK: outlets
@IBOutlet weak var label: NSTextField!
// MARK: NSResponder
override func mouseDown(theEvent: NSEvent) {
if theEvent.clickCount == 2 {
print("Double click \(labelObject!.title)")
} else {
super.mouseDown(theEvent)
}
}
}
|
apache-2.0
|
603115ee2e0a8342ad13575619095565
| 15.8 | 78 | 0.716667 | 3.716814 | false | false | false | false |
iDevelopper/PBRevealViewController
|
Example3Swift/Example3Swift/RightViewController.swift
|
1
|
3042
|
//
// RightViewController.swift
// Example3Swift
//
// Created by Patrick BODET on 07/08/2016.
// Copyright © 2016 iDevelopper. All rights reserved.
//
import UIKit
class RightViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//tableView.backgroundColor = UIColor.clear
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// Configure the cell...
cell.backgroundColor = UIColor.clear
cell.textLabel!.text = "Item \((indexPath as NSIndexPath).row)"
return cell
}
// MARK: - Table view delegate
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController = storyboard.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController
switch (indexPath as NSIndexPath).row {
case 0:
self.revealViewController().toggleAnimationType = PBRevealToggleAnimationType.none
mainViewController.image = UIImage(named: "Sunset1")
case 1:
self.revealViewController().toggleAnimationType = PBRevealToggleAnimationType.crossDissolve
mainViewController.image = UIImage(named: "Sunset2")
case 2:
self.revealViewController().toggleAnimationType = PBRevealToggleAnimationType.pushSideView
mainViewController.image = UIImage(named: "Sunset3")
case 3:
self.revealViewController().toggleAnimationType = PBRevealToggleAnimationType.spring
mainViewController.image = UIImage(named: "Sunset4")
case 4:
self.revealViewController().toggleAnimationType = PBRevealToggleAnimationType.custom
mainViewController.image = UIImage(named: "Sunset5")
default: break
}
let nc = UINavigationController(rootViewController: mainViewController)
revealViewController().pushMainViewController(nc, animated:true)
}
}
|
mit
|
e56cc662fa01617e0b016fef763cedf9
| 33.954023 | 130 | 0.660309 | 5.705441 | false | false | false | false |
adrfer/swift
|
test/1_stdlib/Runtime.swift
|
1
|
43726
|
// 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
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
#if _runtime(_ObjC)
import ObjectiveC
#endif
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 = BooleanType
typealias P2 = CustomStringConvertible
protocol Q1 {}
// A small struct that can be stored inline in an opaque buffer.
struct StructConformsToP1 : BooleanType, Q1 {
var boolValue: Bool {
return true
}
}
// A small struct that can be stored inline in an opaque buffer.
struct Struct2ConformsToP1<T : BooleanType> : BooleanType, 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 : BooleanType, Q1 {
var boolValue: Bool {
return true
}
}
class Class2ConformsToP1<T : BooleanType> : BooleanType, 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)
}
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 ], &output)
expectEqual("▿ 2 elements\n - [0]: 42\n - [1]: 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"), &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 _MirrorType implementation gets memory management right.
var output = ""
dump(StructWithDefaultMirror("\(456)"), &output)
expectEqual("▿ a.StructWithDefaultMirror\n - s: 456\n", output)
}
// Structs have no identity and thus no object identifier
expectEmpty(_reflect(StructWithDefaultMirror("")).objectIdentifier)
// The default mirror provides no quick look object
expectEmpty(_reflect(StructWithDefaultMirror("")).quickLookObject)
expectEqual(.Struct, _reflect(StructWithDefaultMirror("")).disposition)
}
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, &output)
let expected =
"▿ a.GenericStructWithDefaultMirror<Swift.Int, Swift.Array<Swift.Optional<protocol<>>>>\n" +
" - first: 123\n" +
" ▿ second: 3 elements\n" +
" ▿ [0]: abc\n" +
" - Some: abc\n" +
" ▿ [1]: 456\n" +
" - Some: 456\n" +
" ▿ [2]: 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, &output)
let expected =
"▿ 2 elements\n" +
" - [0]: a.NoPayloadEnumWithDefaultMirror.A\n" +
" - [1]: 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, &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, &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, &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, &output)
let expected =
"▿ 3 elements\n" +
" - [0]: a.SinglePayloadNonGenericEnumWithDefaultMirror.Cat\n" +
" - [1]: a.SinglePayloadNonGenericEnumWithDefaultMirror.Dog\n" +
" ▿ [2]: 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, &output)
let expected =
"▿ 3 elements\n" +
" - [0]: a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Well\n" +
" - [1]: a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Faucet\n" +
" ▿ [2]: a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Pipe\n" +
" ▿ Pipe: (2 elements)\n" +
" - .0: 408\n" +
" ▿ .1: 1 element\n" +
" - [0]: 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, &output)
let expected =
"▿ 4 elements\n" +
" - [0]: a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Plus\n" +
" - [1]: a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.SE30\n" +
" ▿ [2]: a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Classic\n" +
" - Classic: 16\n" +
" ▿ [3]: 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, &output)
let expected =
"▿ 5 elements\n" +
" - [0]: a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacWrite\n" +
" - [1]: a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacPaint\n" +
" - [2]: a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.FileMaker\n" +
" ▿ [3]: a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.ClarisWorks\n" +
" ▿ ClarisWorks: a.Floppy #0\n" +
" - capacity: 800\n" +
" ▿ [4]: 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, &output)
let expected =
"▿ 5 elements\n" +
" - [0]: a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacWrite\n" +
" - [1]: a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacPaint\n" +
" - [2]: a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.FileMaker\n" +
" ▿ [3]: a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.ClarisWorks\n" +
" - ClarisWorks: true\n" +
" ▿ [4]: 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, &output)
let expected =
"▿ 6 elements\n" +
" - [0]: a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIe\n" +
" - [1]: a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIgs\n" +
" ▿ [2]: a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Centris\n" +
" - Centris: 4096\n" +
" ▿ [3]: a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Quadra\n" +
" - Quadra: 160MB\n" +
" - [4]: a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBook170\n" +
" - [5]: 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, &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))")
}
/// A type that provides its own mirror.
struct BrilliantMirror : _MirrorType {
let _value: Brilliant
init (_ _value: Brilliant) {
self._value = _value
}
var value: Any {
return _value
}
var valueType: Any.Type {
return value.dynamicType
}
var objectIdentifier: ObjectIdentifier? {
return ObjectIdentifier(_value)
}
var count: Int {
return 3
}
subscript(i: Int) -> (String, _MirrorType) {
switch i {
case 0:
return ("first", _reflect(_value.first))
case 1:
return ("second", _reflect(_value.second))
case 2:
return ("self", self)
case _:
_preconditionFailure("child index out of bounds")
}
}
var summary: String {
return "Brilliant(\(_value.first), \(_value.second))"
}
var quickLookObject: PlaygroundQuickLook? {
return nil
}
var disposition: _MirrorDisposition {
return .Container
}
}
class Brilliant : _Reflectable {
let first: Int
let second: String
init(_ fst: Int, _ snd: String) {
self.first = fst
self.second = snd
}
func _getMirror() -> _MirrorType {
return BrilliantMirror(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"), &output)
let expected =
"▿ Brilliant(123, four five six) #0\n" +
" - first: 123\n" +
" - second: four five six\n" +
" ▿ self: Brilliant(123, four five six) #0\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), &output, maxDepth: 0)
expectEqual("▹ Brilliant(123, four five six) #0\n", output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), &output, maxItems: 3)
let expected =
"▿ Brilliant(123, four five six) #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"), &output, maxItems: 2)
let expected =
"▿ Brilliant(123, four five six) #0\n" +
" - first: 123\n" +
" (2 more children)\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), &output, maxItems: 1)
let expected =
"▿ Brilliant(123, four five six) #0\n" +
" (3 children)\n"
expectEqual(expected, output)
}
expectEqual(.Container, _reflect(Brilliant(123, "four five six")).disposition)
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 ordering is transitive
expectEqual(
[ ObjectIdentifier(a), ObjectIdentifier(b), ObjectIdentifier(c) ].sort(),
[ ObjectIdentifier(c), ObjectIdentifier(b), ObjectIdentifier(a) ].sort())
}
}
Reflection.test("CustomMirrorIsInherited") {
do {
var output = ""
dump(Irradiant(), &output)
let expected =
"▿ Brilliant(400, ) #0\n" +
" - first: 400\n" +
" - second: \n" +
" ▿ self: Brilliant(400, ) #0\n"
expectEqual(expected, output)
}
}
protocol SomeNativeProto {}
extension Int: SomeNativeProto {}
Reflection.test("MetatypeMirror") {
do {
var output = ""
let concreteMetatype = Int.self
dump(concreteMetatype, &output)
let expectedInt = "- Swift.Int #0\n"
expectEqual(expectedInt, output)
let anyMetatype: Any.Type = Int.self
output = ""
dump(anyMetatype, &output)
expectEqual(expectedInt, output)
let nativeProtocolMetatype: SomeNativeProto.Type = Int.self
output = ""
dump(nativeProtocolMetatype, &output)
expectEqual(expectedInt, output)
expectEqual(_reflect(concreteMetatype).objectIdentifier!,
_reflect(anyMetatype).objectIdentifier!)
expectEqual(_reflect(concreteMetatype).objectIdentifier!,
_reflect(nativeProtocolMetatype).objectIdentifier!)
let concreteClassMetatype = SomeClass.self
let expectedSomeClass = "- a.SomeClass #0\n"
output = ""
dump(concreteClassMetatype, &output)
expectEqual(expectedSomeClass, output)
let nativeProtocolConcreteMetatype = SomeNativeProto.self
let expectedNativeProtocolConcrete = "- a.SomeNativeProto #0\n"
output = ""
dump(nativeProtocolConcreteMetatype, &output)
expectEqual(expectedNativeProtocolConcrete, output)
}
}
Reflection.test("TupleMirror") {
do {
var output = ""
let tuple =
(Brilliant(384, "seven six eight"), StructWithDefaultMirror("nine"))
dump(tuple, &output)
let expected =
"▿ (2 elements)\n" +
" ▿ .0: Brilliant(384, seven six eight) #0\n" +
" - first: 384\n" +
" - second: seven six eight\n" +
" ▿ self: Brilliant(384, seven six eight) #0\n" +
" ▿ .1: a.StructWithDefaultMirror\n" +
" - s: nine\n"
expectEqual(expected, output)
expectEmpty(_reflect(tuple).quickLookObject)
expectEqual(.Tuple, _reflect(tuple).disposition)
}
do {
// A tuple of stdlib types with mirrors.
var output = ""
let tuple = (1, 2.5, false, "three")
dump(tuple, &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, &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("ObjectIdentity") {
// Check that the primitive _MirrorType implementation produces appropriately
// unique identifiers for class instances.
let x = DullClass()
let y = DullClass()
checkEquatable(
true, _reflect(x).objectIdentifier!, _reflect(x).objectIdentifier!)
checkEquatable(
false, _reflect(x).objectIdentifier!, _reflect(y).objectIdentifier!)
expectEmpty(_reflect(x).quickLookObject)
expectEqual(.Class, _reflect(x).disposition)
}
Reflection.test("String/Mirror") {
do {
var output = ""
dump("", &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}", &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, &output)
let expected =
"▿ \u{61}\u{304b}\u{3099}\n" +
" - [0]: 97\n" +
" - [1]: 227\n" +
" - [2]: 129\n" +
" - [3]: 139\n" +
" - [4]: 227\n" +
" - [5]: 130\n" +
" - [6]: 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, &output)
let expected =
"▿ \u{61}\u{304b}\u{3099}\u{1f425}\n" +
" - [0]: 97\n" +
" - [1]: 12363\n" +
" - [2]: 12441\n" +
" - [3]: 55357\n" +
" - [4]: 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, &output)
let expected =
"▿ \u{61}\u{304b}\u{3099}\u{1f425}\n" +
" - [0]: \u{61}\n" +
" - [1]: \u{304b}\n" +
" - [2]: \u{3099}\n" +
" - [3]: \u{1f425}\n"
expectEqual(expected, output)
}
Reflection.test("Character/Mirror") {
do {
// U+0061 LATIN SMALL LETTER A
let input: Character = "\u{61}"
var output = ""
dump(input, &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, &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, &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, &output)
let expected =
"- \u{61}\n"
expectEqual(expected, output)
}
do {
// U+304B HIRAGANA LETTER KA
let input: UnicodeScalar = "\u{304b}"
var output = ""
dump(input, &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, &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, &output)
let expected =
"- \u{1f425}\n"
expectEqual(expected, output)
}
}
Reflection.test("Bool") {
do {
var output = ""
dump(false, &output)
let expected =
"- false\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(true, &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, &output)
let expected =
"- nan\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Float.infinity, &output)
let expected =
"- inf\n"
expectEqual(expected, output)
}
do {
var input: Float = 42.125
var output = ""
dump(input, &output)
let expected =
"- 42.125\n"
expectEqual(expected, output)
}
}
Reflection.test("Double") {
do {
var output = ""
dump(Double.NaN, &output)
let expected =
"- nan\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Double.infinity, &output)
let expected =
"- inf\n"
expectEqual(expected, output)
}
do {
var input: Double = 42.125
var output = ""
dump(input, &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(), &output)
expectEqual(expected, output)
}
do {
let expected =
"▿ a.EightByteFieldNamesClass #0\n" +
" - abcdef: 42\n"
var output = ""
dump(EightByteFieldNamesClass(), &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("COpaquePointer/null") {
// Don't crash on null pointers. rdar://problem/19708338
var sequence = COpaquePointer()
var mirror = _reflect(sequence)
var child = mirror[0]
expectEqual("(Opaque Value)", child.1.summary)
}
Reflection.test("StaticString/Mirror") {
do {
var output = ""
dump("" as StaticString, &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, &output)
let expected =
"- \u{61}\u{304b}\u{3099}\u{1f425}\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("_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)
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
|
f4e80af33f25a009d40788a90b9dc1f3
| 26.313087 | 158 | 0.654417 | 3.749914 | false | false | false | false |
CeranPaul/SketchCurves
|
SketchGen/CoordinateSystem.swift
|
1
|
6036
|
//
// CoordinateSystem.swift
// SketchCurves
//
// Created by Paul on 6/6/16.
// Copyright © 2018 Ceran Digital Media. All rights reserved. See LICENSE.md
//
import Foundation
/// Three coordinates and three orthogonal axes
open class CoordinateSystem {
/// Can be changed with 'relocate' function
var origin: Point3D
// To assure the property of being mutually orthogonal
var axisX: Vector3D
var axisY: Vector3D
var axisZ: Vector3D
/// Construct an equivalent to the global CSYS.
/// Origin can be changed by static function 'relocate'.
/// - See: 'testFidelity1' under CoordinateSystemTests
public init() {
self.origin = Point3D(x: 0.0, y: 0.0, z: 0.0)
self.axisX = Vector3D(i: 1.0, j: 0.0, k: 0.0)
self.axisY = Vector3D(i: 0.0, j: 1.0, k: 0.0)
self.axisZ = Vector3D(i: 0.0, j: 0.0, k: 1.0)
}
/// Construct from a point and three vectors
/// - Parameters:
/// - spot: The origin of the CSYS
/// - alpha: A unit vector representing an axis
/// - beta: Another unit vector - orthogonal to others
/// - gamma: Final unit vector
/// - Throws:
/// - NonUnitDirectionError for any bad input vector
/// - NonOrthogonalCSYSError if the inputs, as a set, aren't good
/// - See: 'testFidelity2' under CoordinateSystemTests
public init(spot: Point3D, alpha: Vector3D, beta: Vector3D, gamma: Vector3D) throws {
self.origin = spot
guard (alpha.isUnit()) else { throw NonUnitDirectionError(dir: alpha) }
self.axisX = alpha
guard (beta.isUnit()) else { throw NonUnitDirectionError(dir: beta) }
self.axisY = beta
guard (gamma.isUnit()) else { throw NonUnitDirectionError(dir: gamma) }
self.axisZ = gamma
guard (CoordinateSystem.isMutOrtho(uno: axisX, dos: axisY, tres: axisZ)) else { throw NonOrthogonalCSYSError() }
}
/// Generate from two vectors and a point.
/// - Parameters:
/// - spot: Point to serve as the origin
/// - direction1: A Vector3D
/// - direction2: A Vector3D that is not parallel or opposite to direction1
/// - useFirst: Use the first input vector as the reference direction?
/// - verticalRef: Does the reference direction represent vertical or horizontal in the local plane?
/// - Throws:
/// - NonUnitDirectionError for any bad input vector
/// - See: 'testFidelity3' under CoordinateSystemTests
public init(spot: Point3D, direction1: Vector3D, direction2: Vector3D, useFirst: Bool, verticalRef: Bool) throws {
guard (direction1.isUnit()) else { throw NonUnitDirectionError(dir: direction1) }
guard (direction2.isUnit()) else { throw NonUnitDirectionError(dir: direction2) }
var outOfPlane = try Vector3D.crossProduct(lhs: direction1, rhs: direction2)
outOfPlane.normalize()
self.axisZ = outOfPlane
if useFirst {
if verticalRef {
self.axisY = direction1
self.axisX = try! Vector3D.crossProduct(lhs: self.axisY, rhs: self.axisZ)
} else {
self.axisX = direction1
self.axisY = try! Vector3D.crossProduct(lhs: self.axisZ, rhs: self.axisX)
}
} else {
if verticalRef {
self.axisY = direction2
self.axisX = try! Vector3D.crossProduct(lhs: self.axisY, rhs: self.axisZ)
} else {
self.axisX = direction2
self.axisY = try! Vector3D.crossProduct(lhs: self.axisZ, rhs: self.axisX)
}
}
self.origin = spot
}
public func getOrigin() -> Point3D {
return origin
}
public func getAxisX() -> Vector3D {
return axisX
}
public func getAxisY() -> Vector3D {
return axisY
}
public func getAxisZ() -> Vector3D {
return axisZ
}
/// Check to see that these three vectors are mutually orthogonal
/// - Parameters:
/// - uno: Unit vector to serve as an axis
/// - dos: Another unit vector
/// - tres: The final unit vector
/// Returns: Simple flag
/// - See: 'testIsMutOrtho' under CoordinateSystemTests
public static func isMutOrtho(uno: Vector3D, dos: Vector3D, tres: Vector3D) -> Bool {
let dot12 = Vector3D.dotProduct(lhs: uno, rhs: dos)
let flag1 = abs(dot12) < Vector3D.EpsilonV
let dot23 = Vector3D.dotProduct(lhs: dos, rhs: tres)
let flag2 = abs(dot23) < Vector3D.EpsilonV
let dot31 = Vector3D.dotProduct(lhs: tres, rhs: uno)
let flag3 = abs(dot31) < Vector3D.EpsilonV
return flag1 && flag2 && flag3
}
/// Create from an existing CSYS, but use a different origin
/// - Parameters:
/// - startingCSYS: Desired set of orientations
/// - betterOrigin: New location
/// - See: 'testRelocate' under CoordinateSystemTests
public static func relocate(startingCSYS: CoordinateSystem, betterOrigin: Point3D) -> CoordinateSystem {
let sparkling = try! CoordinateSystem(spot: betterOrigin, alpha: startingCSYS.axisX, beta: startingCSYS.axisY, gamma: startingCSYS.axisZ)
return sparkling
}
}
/// Check for them being identical
public func == (lhs: CoordinateSystem, rhs: CoordinateSystem) -> Bool {
let flagOrig = (lhs.getOrigin() == rhs.getOrigin())
let flagX = (lhs.getAxisX() == rhs.getAxisX())
let flagY = (lhs.getAxisY() == rhs.getAxisY())
let flagZ = (lhs.getAxisZ() == rhs.getAxisZ())
return flagOrig && flagX && flagY && flagZ
}
|
apache-2.0
|
070944b4c75c421e41ecff6e2128e975
| 31.798913 | 145 | 0.58227 | 3.949607 | false | true | false | false |
xwu/swift
|
test/IRGen/objc_async_metadata.swift
|
3
|
1662
|
// RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -disable-availability-checking %s -emit-ir | %FileCheck %s
// REQUIRES: OS=macosx
// REQUIRES: concurrency
// REQUIRES: objc_interop
import Foundation
// CHECK: [[ENCODE_ASYNC_STRING:@.*]] = private unnamed_addr constant [28 x i8] c"v24@0:8@?<v@?@\22NSString\22>16\00"
// CHECK: [[ENCODE_ASYNC_THROWS_STRING:@.*]] = private unnamed_addr constant [38 x i8] c"v24@0:8@?<v@?@\22NSString\22@\22NSError\22>16\00"
// CHECK: @_INSTANCE_METHODS__TtC19objc_async_metadata7MyClass = internal constant
// CHECK-SAME: methodWithCompletionHandler:
// CHECK-SAME: [[ENCODE_ASYNC_STRING]]
// CHECK-SAME: throwingMethodWithCompletionHandler:
// CHECK-SAME: [[ENCODE_ASYNC_THROWS_STRING]]
class MyClass: NSObject {
@objc func method() async -> String { "" }
@objc func throwingMethod() async throws -> String { "" }
}
// CHECK: [[ENCODE_ASYNC_STRING_PROTO:@.*]] = private unnamed_addr constant [15 x i8] c"v32@0:8@16@?24\00"
// CHECK-LABEL: @_PROTOCOL_INSTANCE_METHODS__TtP19objc_async_metadata7MyProto_ = internal constant
// CHECK-SAME: _selector_data(myProtoRequirement:completionHandler:)
// CHECK-SAME: [15 x i8]* [[ENCODE_ASYNC_STRING_PROTO]]
// CHECK: [[ENCODE_ASYNC_STRING_PROTO_TYPE:@.*]] = private unnamed_addr constant [41 x i8] c"v32@0:8@\22NSString\2216@?<v@?@\22NSString\22>24\00"
// CHECK-LABEL: @_PROTOCOL_METHOD_TYPES__TtP19objc_async_metadata7MyProto_ = internal constant
// CHECK-SAME: [41 x i8]* [[ENCODE_ASYNC_STRING_PROTO_TYPE]]
@objc protocol MyProto {
@objc func myProtoRequirement(_ x: String) async -> String
}
|
apache-2.0
|
f07c3c7120aebadd8d8651403d576e00
| 45.166667 | 145 | 0.705776 | 3.1537 | false | false | false | false |
xwu/swift
|
stdlib/private/StdlibUnittest/StdlibCoreExtras.swift
|
1
|
8366
|
//===--- StdlibCoreExtras.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 SwiftPrivate
import SwiftPrivateLibcExtras
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import CRT
#endif
#if _runtime(_ObjC)
import Foundation
#endif
//
// These APIs don't really belong in a unit testing library, but they are
// useful in tests, and stdlib does not have such facilities yet.
//
func findSubstring(_ haystack: Substring, _ needle: String) -> String.Index? {
return findSubstring(haystack._ephemeralString, needle)
}
func findSubstring(_ string: String, _ substring: String) -> String.Index? {
if substring.isEmpty {
return string.startIndex
}
#if _runtime(_ObjC)
return string.range(of: substring)?.lowerBound
#else
// FIXME(performance): This is a very non-optimal algorithm, with a worst
// case of O((n-m)*m). When non-objc String has a match function that's better,
// this should be removed in favor of using that.
// Operate on unicode scalars rather than codeunits.
let haystack = string.unicodeScalars
let needle = substring.unicodeScalars
for matchStartIndex in haystack.indices {
var matchIndex = matchStartIndex
var needleIndex = needle.startIndex
while true {
if needleIndex == needle.endIndex {
// if we hit the end of the search string, we found the needle
return matchStartIndex
}
if matchIndex == haystack.endIndex {
// if we hit the end of the string before finding the end of the needle,
// we aren't going to find the needle after that.
return nil
}
if needle[needleIndex] == haystack[matchIndex] {
// keep advancing through both the string and search string on match
matchIndex = haystack.index(after: matchIndex)
needleIndex = haystack.index(after: needleIndex)
} else {
// no match, go back to finding a starting match in the string.
break
}
}
}
return nil
#endif
}
#if !os(Windows)
public func createTemporaryFile(
_ fileNamePrefix: String, _ fileNameSuffix: String, _ contents: String
) -> String {
#if _runtime(_ObjC)
let tempDir: NSString = NSTemporaryDirectory() as NSString
var fileName = tempDir.appendingPathComponent(
fileNamePrefix + "XXXXXX" + fileNameSuffix)
#else
var fileName = fileNamePrefix + "XXXXXX" + fileNameSuffix
#endif
let fd = _stdlib_mkstemps(
&fileName, CInt(fileNameSuffix.utf8.count))
if fd < 0 {
fatalError("mkstemps() returned an error")
}
var stream = _FDOutputStream(fd: fd)
stream.write(contents)
if close(fd) != 0 {
fatalError("close() return an error")
}
return fileName
}
#endif
public final class Box<T> {
public init(_ value: T) { self.value = value }
public var value: T
}
infix operator <=>
public func <=> <T: Comparable>(lhs: T, rhs: T) -> ExpectedComparisonResult {
return lhs < rhs
? .lt
: lhs > rhs ? .gt : .eq
}
public struct TypeIdentifier : Hashable, Comparable {
public var value: Any.Type
public init(_ value: Any.Type) {
self.value = value
}
public var hashValue: Int { return objectID.hashValue }
public func hash(into hasher: inout Hasher) {
hasher.combine(objectID)
}
internal var objectID : ObjectIdentifier {
return ObjectIdentifier(value)
}
public static func < (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool {
return lhs.objectID < rhs.objectID
}
public static func == (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool {
return lhs.objectID == rhs.objectID
}
}
extension TypeIdentifier
: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return String(describing: value)
}
public var debugDescription: String {
return "TypeIdentifier(\(description))"
}
}
enum FormNextPermutationResult {
case success
case formedFirstPermutation
}
extension MutableCollection
where
Self : BidirectionalCollection,
Iterator.Element : Comparable
{
mutating func _reverseSubrange(_ subrange: Range<Index>) {
if subrange.isEmpty { return }
var f = subrange.lowerBound
var l = index(before: subrange.upperBound)
while f < l {
swapAt(f, l)
formIndex(after: &f)
formIndex(before: &l)
}
}
mutating func formNextPermutation() -> FormNextPermutationResult {
if isEmpty {
// There are 0 elements, only one permutation is possible.
return .formedFirstPermutation
}
do {
var i = startIndex
formIndex(after: &i)
if i == endIndex {
// There is only element, only one permutation is possible.
return .formedFirstPermutation
}
}
var i = endIndex
formIndex(before: &i)
var beforeI = i
formIndex(before: &beforeI)
var elementAtI = self[i]
var elementAtBeforeI = self[beforeI]
while true {
if elementAtBeforeI < elementAtI {
// Elements at `i..<endIndex` are in non-increasing order. To form the
// next permutation in lexicographical order we need to replace
// `self[i-1]` with the next larger element found in the tail, and
// reverse the tail. For example:
//
// i-1 i endIndex
// V V V
// 6 2 8 7 4 1 [ ] // Input.
// 6 (4) 8 7 (2) 1 [ ] // Exchanged self[i-1] with the
// ^--------^ // next larger element
// // from the tail.
// 6 4 (1)(2)(7)(8)[ ] // Reversed the tail.
// <-------->
var j = endIndex
repeat {
formIndex(before: &j)
} while !(elementAtBeforeI < self[j])
swapAt(beforeI, j)
_reverseSubrange(i..<endIndex)
return .success
}
if beforeI == startIndex {
// All elements are in non-increasing order. Reverse to form the first
// permutation, where all elements are sorted (in non-increasing order).
reverse()
return .formedFirstPermutation
}
i = beforeI
formIndex(before: &beforeI)
elementAtI = elementAtBeforeI
elementAtBeforeI = self[beforeI]
}
}
}
/// Generate all permutations.
public func forAllPermutations(_ size: Int, _ body: ([Int]) -> Void) {
var data = Array(0..<size)
repeat {
body(data)
} while data.formNextPermutation() != .formedFirstPermutation
}
/// Generate all permutations.
public func forAllPermutations<S : Sequence>(
_ sequence: S, _ body: ([S.Element]) -> Void
) {
let data = Array(sequence)
forAllPermutations(data.count) {
(indices: [Int]) in
body(indices.map { data[$0] })
return ()
}
}
public func cartesianProduct<C1 : Collection, C2 : Collection>(
_ c1: C1, _ c2: C2
) -> [(C1.Element, C2.Element)] {
var result: [(C1.Element, C2.Element)] = []
for e1 in c1 {
for e2 in c2 {
result.append((e1, e2))
}
}
return result
}
/// Return true if the standard library was compiled in a debug configuration.
public func _isStdlibDebugConfiguration() -> Bool {
#if SWIFT_STDLIB_DEBUG
return true
#else
return false
#endif
}
// Return true if the Swift runtime available is at least 5.1
public func _hasSwift_5_1() -> Bool {
if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) {
return true
}
return false
}
@frozen
public struct LinearCongruentialGenerator: RandomNumberGenerator {
@usableFromInline
internal var _state: UInt64
@inlinable
public init(seed: UInt64) {
_state = seed
for _ in 0 ..< 10 { _ = next() }
}
@inlinable
public mutating func next() -> UInt64 {
_state = 2862933555777941757 &* _state &+ 3037000493
return _state
}
}
#if !SWIFT_ENABLE_REFLECTION
public func dump<T, TargetStream: TextOutputStream>(_ value: T, to target: inout TargetStream) {
target.write("(reflection not available)")
}
#endif
|
apache-2.0
|
3017919aec4d5d1dd8bc995cffc3ac47
| 26.519737 | 96 | 0.641406 | 4.071046 | false | false | false | false |
RMizin/PigeonMessenger-project
|
FalconMessenger/Authentication/UserProfile/UserProfileDataDatabaseUpdater.swift
|
1
|
3144
|
//
// UserProfileDataDatabaseUpdater.swift
// Pigeon-project
//
// Created by Roman Mizin on 4/4/18.
// Copyright © 2018 Roman Mizin. All rights reserved.
//
import UIKit
import Firebase
final class UserProfileDataDatabaseUpdater: NSObject {
typealias UpdateUserProfileCompletionHandler = (_ success: Bool) -> Void
func updateUserProfile(with image: UIImage, completion: @escaping UpdateUserProfileCompletionHandler) {
guard let currentUserID = Auth.auth().currentUser?.uid else { return }
let userReference = Database.database().reference().child("users").child(currentUserID)
let thumbnailImage = createImageThumbnail(image)
var images = [(image: UIImage, quality: CGFloat, key: String)]()
images.append((image: image, quality: 0.5, key: "photoURL"))
images.append((image: thumbnailImage, quality: 1, key: "thumbnailPhotoURL"))
let photoUpdatingGroup = DispatchGroup()
for _ in images { photoUpdatingGroup.enter() }
photoUpdatingGroup.notify(queue: DispatchQueue.main, execute: {
completion(true)
})
for imageElement in images {
uploadAvatarForUserToFirebaseStorageUsingImage(imageElement.image, quality: imageElement.quality) { (url) in
userReference.updateChildValues([imageElement.key: url], withCompletionBlock: { (_, _) in
photoUpdatingGroup.leave()
})
}
}
}
typealias DeleteCurrentPhotoCompletionHandler = (_ success: Bool) -> Void
func deleteCurrentPhoto(completion: @escaping DeleteCurrentPhotoCompletionHandler) {
guard currentReachabilityStatus != .notReachable, let currentUser = Auth.auth().currentUser?.uid else {
completion(false)
return
}
let userReference = Database.database().reference().child("users").child(currentUser)
userReference.observeSingleEvent(of: .value, with: { (snapshot) in
guard let userData = snapshot.value as? [String: AnyObject] else { completion(false); return }
guard let photoURL = userData["photoURL"] as? String,
let thumbnailPhotoURL = userData["thumbnailPhotoURL"] as? String,
photoURL != "",
thumbnailPhotoURL != "" else {
completion(true)
return
}
let storage = Storage.storage()
let photoURLStorageReference = storage.reference(forURL: photoURL)
let thumbnailPhotoURLStorageReference = storage.reference(forURL: thumbnailPhotoURL)
let imageRemovingGroup = DispatchGroup()
imageRemovingGroup.enter()
imageRemovingGroup.enter()
imageRemovingGroup.notify(queue: DispatchQueue.main, execute: {
completion(true)
})
photoURLStorageReference.delete(completion: { (_) in
userReference.updateChildValues(["photoURL": ""], withCompletionBlock: { (_, _) in
imageRemovingGroup.leave()
})
})
thumbnailPhotoURLStorageReference.delete(completion: { (_) in
userReference.updateChildValues(["thumbnailPhotoURL": ""], withCompletionBlock: { (_, _) in
imageRemovingGroup.leave()
})
})
}, withCancel: { (_) in
completion(false)
})
}
}
|
gpl-3.0
|
05e87951b90ba0af3cf2f13222de13de
| 34.314607 | 114 | 0.684378 | 4.80581 | false | false | false | false |
wj2061/ios7ptl-swift3.0
|
ch19-UIDynamics/TearOff/TearOff/ViewController.swift
|
1
|
3420
|
//
// ViewController.swift
// TearOff
//
// Created by wj on 15/11/19.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
let kShapeDimension:CGFloat = 100.0
let kSliceCount:Int = 6
class ViewController: UIViewController {
var animator:UIDynamicAnimator!
let defaultBehavior = DefaultBehavior()
override func viewDidLoad() {
super.viewDidLoad()
animator = UIDynamicAnimator(referenceView: view)
let frame = CGRect(x: 0, y: 0, width: kShapeDimension, height: kShapeDimension)
let dragView = DraggableView(frame: frame, animator: animator)
dragView.center = CGPoint(x: view.center.x/4, y: view.center.y/4)
dragView.alpha = 0.4
view.addSubview(dragView)
animator.addBehavior(defaultBehavior)
let tearOffBehavior = TearOffBehavior(view: dragView, anchor: dragView.center) { (tornView, newPinView) -> Void in
tornView.alpha = 1
self.defaultBehavior.addItem(tornView)
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.trash(_:)))
tap.numberOfTapsRequired = 2
tornView.addGestureRecognizer(tap)
}
animator.addBehavior(tearOffBehavior)
}
func trash(_ gesture:UITapGestureRecognizer){
print("trash")
let gview = gesture.view!
let subviews = sliceView(gview, rows: 6, columns: 6)
let trashAnimator = UIDynamicAnimator(referenceView: view)
let dBehaviour = DefaultBehavior()
for subview in subviews{
view.addSubview(subview)
dBehaviour.addItem(subview)
let push = UIPushBehavior(items: [subview], mode: .instantaneous)
push.pushDirection = CGVector(dx: CGFloat(arc4random())/CGFloat(RAND_MAX) - 0.5, dy: CGFloat(arc4random())/CGFloat(RAND_MAX) - 0.5)
trashAnimator.addBehavior(push)
UIView.animate(withDuration: 1, animations: { () -> Void in
subview.alpha = 0
}, completion: { (_) -> Void in
subview.removeFromSuperview()
trashAnimator.removeBehavior(push)
})
}
defaultBehavior.removeItem(gview)
gview.removeFromSuperview()
}
func sliceView(_ view:UIView,rows:Int,columns:Int)->[UIView]{
UIGraphicsBeginImageContext(view.bounds.size)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()?.cgImage
UIGraphicsEndImageContext()
var views = [UIView]()
let width = image!.width
let height = image!.height
for row in 0..<rows{
for column in 0..<columns{
let rect = CGRect(x: CGFloat( column*(width/columns) ),
y: CGFloat( row * (height/rows)),
width: CGFloat(width/columns),
height: CGFloat(height/rows))
let subImage = image!.cropping(to: rect)
let imageView = UIImageView(image: UIImage(cgImage: subImage!))
imageView.frame = rect.offsetBy(dx: view.frame.minX, dy: view.frame.minY)
views.append(imageView)
}
}
return views
}
}
|
mit
|
05ce7ab2e40abd9d97033d7b9d5166d2
| 36.141304 | 143 | 0.590577 | 4.752434 | false | false | false | false |
huangboju/Moots
|
Examples/SwiftUI/SwiftUI-Apple/InterfacingWithUIKit/Complete/Landmarks/Landmarks/Supporting Views/BadgeBackground.swift
|
2
|
2260
|
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
A view that displays the background of a badge.
*/
import SwiftUI
struct BadgeBackground: View {
var body: some View {
GeometryReader { geometry in
Path { path in
var width: CGFloat = min(geometry.size.width, geometry.size.height)
let height = width
let xScale: CGFloat = 0.832
let xOffset = (width * (1.0 - xScale)) / 2.0
width *= xScale
path.move(
to: CGPoint(
x: xOffset + width * 0.95,
y: height * (0.20 + HexagonParameters.adjustment)
)
)
HexagonParameters.points.forEach {
path.addLine(
to: CGPoint(
x: xOffset + width * $0.useWidth.0 * $0.xFactors.0,
y: height * $0.useHeight.0 * $0.yFactors.0
)
)
path.addQuadCurve(
to: CGPoint(
x: xOffset + width * $0.useWidth.1 * $0.xFactors.1,
y: height * $0.useHeight.1 * $0.yFactors.1
),
control: CGPoint(
x: xOffset + width * $0.useWidth.2 * $0.xFactors.2,
y: height * $0.useHeight.2 * $0.yFactors.2
)
)
}
}
.fill(LinearGradient(
gradient: Gradient(
colors: [Self.gradientStart, Self.gradientEnd]),
startPoint: UnitPoint(x: 0.5, y: 0),
endPoint: UnitPoint(x: 0.5, y: 0.6)))
.aspectRatio(1, contentMode: .fit)
}
}
static let gradientStart = Color(red: 239.0 / 255, green: 120.0 / 255, blue: 221.0 / 255)
static let gradientEnd = Color(red: 239.0 / 255, green: 172.0 / 255, blue: 120.0 / 255)
}
struct BadgeBackground_Previews: PreviewProvider {
static var previews: some View {
BadgeBackground()
}
}
|
mit
|
832861cd48227513be45174a735091c3
| 35.419355 | 93 | 0.440655 | 4.516 | false | false | false | false |
huangboju/QMUI.swift
|
QMUI.swift/Demo/Modules/Demos/UIKit/QDButtonViewController.swift
|
1
|
1929
|
//
// QDButtonViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/9.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
class QDButtonViewController: QDCommonListViewController {
override func initDataSource() {
dataSource = ["QMUIButton",
"QMUILinkButton",
"QMUIGhostButton",
"QMUIFillButton",
"QMUINavigationButton",
"QMUIToolbarButton"]
}
override func didSelectCell(_ title: String) {
var viewController: UIViewController?
if title == "QMUIButton" {
viewController = QDNormalButtonViewController()
}
if title == "QMUILinkButton" {
viewController = QDLinkButtonViewController()
}
if title == "QMUIGhostButton" {
viewController = QDGhostButtonViewController()
}
if title == "QMUIFillButton" {
viewController = QDFillButtonViewController()
}
if title == "QMUINavigationButton" {
viewController = QDNavigationButtonViewController()
}
if title == "QMUIToolbarButton" {
viewController = QDToolBarButtonViewController()
}
if let viewController = viewController {
viewController.title = title
navigationController?.pushViewController(viewController, animated: true)
}
}
override var canBecomeFirstResponder: Bool {
return true
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if motion == .motionShake {
let viewController = QDButtonEdgeInsetsViewController()
let navController = QDNavigationController(rootViewController: viewController)
self.present(navController, animated: true, completion: nil)
}
}
}
|
mit
|
ad4ee2f3a19ba698d8233186621c4678
| 31 | 90 | 0.601563 | 5.597668 | false | false | false | false |
huonw/swift
|
stdlib/public/SDK/Dispatch/Data.swift
|
1
|
13783
|
//===----------------------------------------------------------------------===//
//
// 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 _SwiftDispatchOverlayShims
public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable {
public typealias Iterator = DispatchDataIterator
public typealias Index = Int
public typealias Indices = DefaultIndices<DispatchData>
public static let empty: DispatchData = DispatchData(data: _swift_dispatch_data_empty())
public enum Deallocator {
/// Use `free`
case free
/// Use `munmap`
case unmap
/// A custom deallocator
case custom(DispatchQueue?, @convention(block) () -> Void)
fileprivate var _deallocator: (DispatchQueue?, @convention(block) () -> Void) {
switch self {
case .free: return (nil, _swift_dispatch_data_destructor_free())
case .unmap: return (nil, _swift_dispatch_data_destructor_munmap())
case .custom(let q, let b): return (q, b)
}
}
}
fileprivate var __wrapped: __DispatchData
/// Initialize a `Data` with copied memory content.
///
/// - parameter bytes: A pointer to the memory. It will be copied.
/// - parameter count: The number of bytes to copy.
@available(swift, deprecated: 4, message: "Use init(bytes: UnsafeRawBufferPointer) instead")
public init(bytes buffer: UnsafeBufferPointer<UInt8>) {
__wrapped = buffer.baseAddress == nil ? _swift_dispatch_data_empty()
: _swift_dispatch_data_create(buffer.baseAddress!, buffer.count, nil,
_swift_dispatch_data_destructor_default()) as! __DispatchData
}
/// Initialize a `Data` with copied memory content.
///
/// - parameter bytes: A pointer to the memory. It will be copied.
/// - parameter count: The number of bytes to copy.
public init(bytes buffer: UnsafeRawBufferPointer) {
__wrapped = buffer.baseAddress == nil ? _swift_dispatch_data_empty()
: _swift_dispatch_data_create(buffer.baseAddress!, buffer.count, nil,
_swift_dispatch_data_destructor_default()) as! __DispatchData
}
/// Initialize a `Data` without copying the bytes.
///
/// - parameter bytes: A pointer to the bytes.
/// - parameter count: The size of the bytes.
/// - parameter deallocator: Specifies the mechanism to free the indicated buffer.
@available(swift, deprecated: 4, message: "Use init(bytesNoCopy: UnsafeRawBufferPointer, deallocater: Deallocator) instead")
public init(bytesNoCopy bytes: UnsafeBufferPointer<UInt8>, deallocator: Deallocator = .free) {
let (q, b) = deallocator._deallocator
__wrapped = bytes.baseAddress == nil ? _swift_dispatch_data_empty()
: _swift_dispatch_data_create(bytes.baseAddress!, bytes.count, q, b) as! __DispatchData
}
/// Initialize a `Data` without copying the bytes.
///
/// - parameter bytes: A pointer to the bytes.
/// - parameter count: The size of the bytes.
/// - parameter deallocator: Specifies the mechanism to free the indicated buffer.
public init(bytesNoCopy bytes: UnsafeRawBufferPointer, deallocator: Deallocator = .free) {
let (q, b) = deallocator._deallocator
__wrapped = bytes.baseAddress == nil ? _swift_dispatch_data_empty()
: _swift_dispatch_data_create(bytes.baseAddress!, bytes.count, q, b) as! __DispatchData
}
internal init(data: __DispatchData) {
__wrapped = data
}
public var count: Int {
return __dispatch_data_get_size(__wrapped)
}
public func withUnsafeBytes<Result, ContentType>(
body: (UnsafePointer<ContentType>) throws -> Result) rethrows -> Result
{
var ptr: UnsafeRawPointer?
var size = 0
let data = __dispatch_data_create_map(__wrapped, &ptr, &size)
let contentPtr = ptr!.bindMemory(
to: ContentType.self, capacity: size / MemoryLayout<ContentType>.stride)
defer { _fixLifetime(data) }
return try body(contentPtr)
}
public func enumerateBytes(
block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Int, _ stop: inout Bool) -> Void)
{
_swift_dispatch_data_apply(__wrapped) { (_, offset: Int, ptr: UnsafeRawPointer, size: Int) in
let bytePtr = ptr.bindMemory(to: UInt8.self, capacity: size)
let bp = UnsafeBufferPointer(start: bytePtr, count: size)
var stop = false
block(bp, offset, &stop)
return stop ? 0 : 1
}
}
/// Append bytes to the data.
///
/// - parameter bytes: A pointer to the bytes to copy in to the data.
/// - parameter count: The number of bytes to copy.
@available(swift, deprecated: 4, message: "Use append(_: UnsafeRawBufferPointer) instead")
public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) {
let data = _swift_dispatch_data_create(bytes, count, nil, _swift_dispatch_data_destructor_default()) as! __DispatchData
self.append(DispatchData(data: data))
}
/// Append bytes to the data.
///
/// - parameter bytes: A pointer to the bytes to copy in to the data.
/// - parameter count: The number of bytes to copy.
public mutating func append(_ bytes: UnsafeRawBufferPointer) {
// Nil base address does nothing.
guard bytes.baseAddress != nil else { return }
let data = _swift_dispatch_data_create(bytes.baseAddress!, bytes.count, nil, _swift_dispatch_data_destructor_default()) as! __DispatchData
self.append(DispatchData(data: data))
}
/// Append data to the data.
///
/// - parameter data: The data to append to this data.
public mutating func append(_ other: DispatchData) {
let data = __dispatch_data_create_concat(__wrapped, other.__wrapped)
__wrapped = data
}
/// Append a buffer of bytes to the data.
///
/// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`.
public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
self.append(UnsafeRawBufferPointer(buffer))
}
private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: Range<Index>) {
var copiedCount = 0
if range.isEmpty { return }
let rangeSize = range.count
__dispatch_data_apply(__wrapped) { (_, offset: Int, ptr: UnsafeRawPointer, size: Int) in
if offset >= range.endIndex { return false } // This region is after endIndex
let copyOffset = range.startIndex > offset ? range.startIndex - offset : 0 // offset of first byte, in this region
if copyOffset >= size { return true } // This region is before startIndex
let count = Swift.min(rangeSize - copiedCount, size - copyOffset)
memcpy(pointer + copiedCount, ptr + copyOffset, count)
copiedCount += count
return copiedCount < rangeSize
}
}
/// Copy the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
/// - parameter count: The number of bytes to copy.
/// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes.
@available(swift, deprecated: 4, message: "Use copyBytes(to: UnsafeMutableRawBufferPointer, count: Int) instead")
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) {
_copyBytesHelper(to: pointer, from: 0..<count)
}
/// Copy the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. The buffer must be large
/// enough to hold `count` bytes.
/// - parameter count: The number of bytes to copy.
public func copyBytes(to pointer: UnsafeMutableRawBufferPointer, count: Int) {
assert(count <= pointer.count, "Buffer too small to copy \(count) bytes")
guard pointer.baseAddress != nil else { return }
_copyBytesHelper(to: pointer.baseAddress!, from: 0..<count)
}
/// Copy a subset of the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
/// - parameter range: The range in the `Data` to copy.
/// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes.
@available(swift, deprecated: 4, message: "Use copyBytes(to: UnsafeMutableRawBufferPointer, from: Range<Index>) instead")
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) {
_copyBytesHelper(to: pointer, from: range)
}
/// Copy a subset of the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. The buffer must be large
/// enough to hold `count` bytes.
/// - parameter range: The range in the `Data` to copy.
public func copyBytes(to pointer: UnsafeMutableRawBufferPointer, from range: Range<Index>) {
assert(range.count <= pointer.count, "Buffer too small to copy \(range.count) bytes")
guard pointer.baseAddress != nil else { return }
_copyBytesHelper(to: pointer.baseAddress!, from: range)
}
/// Copy the contents of the data into a buffer.
///
/// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer.
/// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called.
/// - parameter buffer: A buffer to copy the data into.
/// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied.
/// - returns: Number of bytes copied into the destination buffer.
public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int {
let cnt = count
guard cnt > 0 else { return 0 }
let copyRange : Range<Index>
if let r = range {
guard !r.isEmpty else { return 0 }
precondition(r.startIndex >= 0)
precondition(r.startIndex < cnt, "The range is outside the bounds of the data")
precondition(r.endIndex >= 0)
precondition(r.endIndex <= cnt, "The range is outside the bounds of the data")
copyRange = r.startIndex..<(r.startIndex + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count))
} else {
copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt)
}
guard !copyRange.isEmpty else { return 0 }
_copyBytesHelper(to: buffer.baseAddress!, from: copyRange)
return copyRange.count
}
/// Sets or returns the byte at the specified index.
public subscript(index: Index) -> UInt8 {
var offset = 0
let subdata = __dispatch_data_copy_region(__wrapped, index, &offset)
var ptr: UnsafeRawPointer?
var size = 0
let map = __dispatch_data_create_map(subdata, &ptr, &size)
defer { _fixLifetime(map) }
return ptr!.load(fromByteOffset: index - offset, as: UInt8.self)
}
public subscript(bounds: Range<Int>) -> Slice<DispatchData> {
return Slice(base: self, bounds: bounds)
}
/// Return a new copy of the data in a specified range.
///
/// - parameter range: The range to copy.
public func subdata(in range: Range<Index>) -> DispatchData {
let subrange = __dispatch_data_create_subrange(
__wrapped, range.startIndex, range.endIndex - range.startIndex)
return DispatchData(data: subrange)
}
public func region(location: Int) -> (data: DispatchData, offset: Int) {
var offset: Int = 0
let data = __dispatch_data_copy_region(__wrapped, location, &offset)
return (DispatchData(data: data), offset)
}
public var startIndex: Index {
return 0
}
public var endIndex: Index {
return count
}
public func index(before i: Index) -> Index {
return i - 1
}
public func index(after i: Index) -> Index {
return i + 1
}
/// An iterator over the contents of the data.
///
/// The iterator will increment byte-by-byte.
public func makeIterator() -> DispatchData.Iterator {
return DispatchDataIterator(_data: self)
}
}
public struct DispatchDataIterator : IteratorProtocol, Sequence {
public typealias Element = UInt8
/// Create an iterator over the given DispatchData
public init(_data: DispatchData) {
var ptr: UnsafeRawPointer?
self._count = 0
self._data = __dispatch_data_create_map(
_data as __DispatchData, &ptr, &self._count)
self._ptr = ptr
self._position = _data.startIndex
// The only time we expect a 'nil' pointer is when the data is empty.
assert(self._ptr != nil || self._count == self._position)
}
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
public mutating func next() -> DispatchData.Element? {
if _position == _count { return nil }
let element = _ptr.load(fromByteOffset: _position, as: UInt8.self)
_position = _position + 1
return element
}
internal let _data: __DispatchData
internal var _ptr: UnsafeRawPointer!
internal var _count: Int
internal var _position: DispatchData.Index
}
extension DispatchData {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> __DispatchData {
return __wrapped
}
public static func _forceBridgeFromObjectiveC(_ input: __DispatchData, result: inout DispatchData?) {
result = DispatchData(data: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: __DispatchData, result: inout DispatchData?) -> Bool {
result = DispatchData(data: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: __DispatchData?) -> DispatchData {
var result: DispatchData?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
|
apache-2.0
|
004d784be2e2b1c0c988729a3f57ce17
| 38.38 | 230 | 0.702895 | 3.830739 | false | false | false | false |
swizzlr/Either
|
EitherTests/EitherTypeTests.swift
|
1
|
844
|
// Copyright (c) 2014 Rob Rix. All rights reserved.
import Either
import XCTest
final class EitherTypeTests: XCTestCase {
func testEqualityOverLeft() {
XCTAssertTrue(Either<Int, Int>.left(1) == Either<Int, Int>.left(1))
XCTAssertFalse(Either<Int, Int>.left(1) == Either<Int, Int>.left(2))
}
func testEqualityOverRight() {
XCTAssertTrue(Either<Int, Int>.right(1) == Either<Int, Int>.right(1))
XCTAssertFalse(Either<Int, Int>.right(1) == Either<Int, Int>.right(2))
}
func testInequalityOverLeft() {
XCTAssertTrue(Either<Int, Int>.left(1) != Either<Int, Int>.left(2))
XCTAssertFalse(Either<Int, Int>.left(1) != Either<Int, Int>.left(1))
}
func testInequalityOverRight() {
XCTAssertFalse(Either<Int, Int>.right(1) != Either<Int, Int>.right(1))
XCTAssertTrue(Either<Int, Int>.right(1) != Either<Int, Int>.right(2))
}
}
|
mit
|
69459bdef4afe9c541e4fb5a94681e45
| 31.461538 | 72 | 0.694313 | 3.02509 | false | true | false | false |
IamAlchemist/Animations
|
Animations/UINTSpringAnimation.swift
|
2
|
4535
|
//
// UINTSprintAnimation.swift
// DemoAnimations
//
// Created by wizard on 5/28/16.
// Copyright © 2016 Alchemist. All rights reserved.
//
import UIKit
func CGPointSubtract(p1 : CGPoint, _ p2: CGPoint) -> CGPoint {
return CGPointMake(p1.x - p2.x, p1.y - p2.y)
}
func CGPointAdd(p1 : CGPoint, _ p2: CGPoint) -> CGPoint {
return CGPointMake(p1.x + p2.x, p1.y + p2.y)
}
func CGPointMultiply(point :CGPoint, _ multiplier: CGFloat) -> CGPoint {
return CGPointMake(point.x * multiplier, point.y * multiplier)
}
func CGPointLength(point: CGPoint) -> CGFloat {
return CGFloat(sqrt(point.x * point.x + point.y * point.y))
}
class UINTSpringAnimation : NSObject, ArtificialAnimation {
var velocity : CGPoint
private var target : CGPoint
private var view : UIView
private let frictionConstant : CGFloat = 20
private let springConstant : CGFloat = 300
class func animationWithView(view: UIView, target: CGPoint, velocity:CGPoint) -> UINTSpringAnimation {
return UINTSpringAnimation(view: view, target: target, velocity: velocity)
}
private init(view: UIView, target: CGPoint, velocity: CGPoint) {
self.view = view
self.target = target
self.velocity = velocity
super.init()
}
// ------------------------------
// 首先让我们看一下我们需要知道的基础物理知识,这样我们才能实现出刚才使用 UIKit 力学实现的那种弹簧动画效果。为了简化问题,虽然引入第二个维度也是很直接的,但我们在这里只关注一维的情况 (在我们的例子中就是这样的情况)。
//
// 我们的目标是依据控制面板当前的位置和上一次动画后到现在为止经过的时间,来计算它的新位置。我们可以把它表示成这样:
//
// y = y0 + Δy
// 位置的偏移量可以通过速度和时间的函数来表达:
//
// Δy = v ⋅ Δt
// 这个速度可以通过前一次的速度加上速度偏移量算出来,这个速度偏移量是由力在 view 上的作用引起的。
//
// v = v0 + Δv
// 速度的变化可以通过作用在这个 view 上的冲量计算出来:
//
// Δv = (F ⋅ Δt) / m
// 现在,让我们看一下作用在这个界面上的力。为了得到弹簧效果,我们必须要将摩擦力和弹力结合起来:
//
// F = F_spring + F_friction
// 弹力的计算方法我们可以从任何一本教科书中得到 (编者注:简单的胡克定律):
//
// F_spring = k ⋅ x
// k 是弹簧的劲度系数,x 是 view 到目标结束位置的距离 (也就是弹簧的长度)。因此,我们可以把它写成这样:
//
// F_spring = k ⋅ abs(y_target - y0)
// 摩擦力和 view 的速度成正比:
//
// F_friction = μ ⋅ v
// μ 是一个简单的摩擦系数。你可以通过别的方式来计算摩擦力,但是这个方法能很好地做出我们想要的动画效果。
//
// 将上面的表达式放在一起,我们就可以算出作用在界面上的力:
//
// F = k ⋅ abs(y_target - y0) + μ ⋅ v
// 为了实现起来更简单点些,我们将 view 的质量设为 1,这样我们就能计算在位置上的变化:
//
// Δy = (v0 + (k ⋅ abs(y_target - y0) + μ ⋅ v) ⋅ Δt) ⋅ Δt
func animationTick(dt: CFTimeInterval, inout finished: Bool) {
let time = CGFloat(dt)
// friction force = velocity * friction constant
let frictionForce = CGPointMultiply(velocity, frictionConstant);
// spring force = (target point - current position) * spring constant
let springForce = CGPointMultiply(CGPointSubtract(target, view.center), springConstant);
// force = spring force - friction force
let force = CGPointSubtract(springForce, frictionForce);
// velocity = current velocity + force * time / mass
velocity = CGPointAdd(velocity, CGPointMultiply(force, time));
// position = current position + velocity * time
view.center = CGPointAdd(view.center, CGPointMultiply(velocity, time));
let speed = CGPointLength(velocity)
let distanceToGoal = CGPointLength(CGPointSubtract(target, view.center))
if (speed < 0.05 && distanceToGoal < 1) {
view.center = target
finished = true
}
}
}
|
mit
|
51043e557f98acd5642731a7ef6ae2c2
| 32.122642 | 121 | 0.612931 | 3.174503 | false | false | false | false |
LetItPlay/iOSClient
|
blockchainapp/PlayerTableViewCell.swift
|
1
|
5169
|
import UIKit
import SnapKit
class PlayerTableViewCell: UITableViewCell {
static let cellID: String = "PlayerTrackCellID"
let trackImageView: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = 6
imageView.contentMode = .scaleAspectFill
imageView.layer.masksToBounds = true
return imageView
}()
let trackNameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
label.textColor = .black
label.numberOfLines = 2
label.lineBreakMode = .byTruncatingTail
return label
}()
let channelNameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14, weight: .regular)
label.textColor = UIColor.black.withAlphaComponent(0.6)
return label
}()
let timeLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14, weight: .regular)
label.textColor = UIColor.black.withAlphaComponent(0.6)
label.textAlignment = .right
return label
}()
let reserveTimeLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14, weight: .regular)
label.textColor = UIColor.black.withAlphaComponent(0.6)
label.textAlignment = .right
return label
}()
var dataLabels: [IconLabelType: IconedLabel] = [:]
weak var track: AudioTrack? = nil {
didSet {
if let iconUrl = track?.imageURL {
trackImageView.sd_setImage(with: iconUrl)
} else {
trackImageView.image = nil
}
trackNameLabel.attributedText = SmallTrackTableViewCell.trackText(text: track?.name ?? "")
channelNameLabel.text = track?.author
// self.timeLabel.text = (track?.publishedAt ?? Date()).formatString()
// dataLabels[.listens]?.setData(data: Int64(track?.listenCount ?? 0))
dataLabels[.time]?.setData(data: Int64(track?.length ?? 0))
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(trackImageView)
trackImageView.snp.makeConstraints { (make) in
make.left.equalToSuperview().inset(16)
// make.centerY.equalToSuperview()
make.top.equalToSuperview().inset(12)
make.width.equalTo(60)
make.height.equalTo(60)
}
self.contentView.addSubview(channelNameLabel)
channelNameLabel.snp.makeConstraints { (make) in
make.left.equalTo(trackImageView.snp.right).inset(-14)
make.top.equalTo(trackImageView)
make.height.equalTo(18)
}
self.contentView.addSubview(timeLabel)
timeLabel.snp.makeConstraints { (make) in
make.right.equalToSuperview().inset(16)
make.centerY.equalTo(channelNameLabel)
make.left.equalTo(channelNameLabel.snp.right).inset(-10)
make.width.equalTo(80)
}
self.contentView.addSubview(trackNameLabel)
trackNameLabel.snp.makeConstraints { (make) in
make.left.equalTo(channelNameLabel)
make.top.equalTo(channelNameLabel.snp.bottom).inset(2)
make.right.equalToSuperview().inset(16)
}
let timeCount = IconedLabel(type: .time)
// let listensCount = IconedLabel(type: .listens)
let playingIndicator = IconedLabel(type: .playingIndicator)
self.contentView.addSubview(timeCount)
timeCount.snp.makeConstraints { (make) in
make.top.equalTo(trackNameLabel.snp.bottom).inset(-6)
make.left.equalTo(trackNameLabel)
// make.bottom.equalToSuperview().inset(12)
}
// self.contentView.addSubview(listensCount)
// listensCount.snp.makeConstraints { (make) in
// make.left.equalTo(timeCount.snp.right).inset(-10)
// make.centerY.equalTo(timeCount)
// }
self.contentView.addSubview(playingIndicator)
playingIndicator.snp.makeConstraints { (make) in
make.left.equalTo(timeCount.snp.right).inset(-10)
make.centerY.equalTo(timeCount)
}
playingIndicator.isHidden = true
self.dataLabels = [.time: timeCount, .playingIndicator: playingIndicator]
self.separatorInset.left = 90
self.selectionStyle = .none
let view = UIView()
view.backgroundColor = AppColor.Element.tomato.withAlphaComponent(0.2)
self.contentView.addSubview(view)
view.snp.makeConstraints { (make) in
make.left.equalToSuperview().inset(90)
make.right.equalToSuperview()
make.bottom.equalToSuperview()
make.height.equalTo(1)
}
}
static func trackText(text: String) -> NSAttributedString {
let para = NSMutableParagraphStyle()
para.lineBreakMode = .byWordWrapping
para.minimumLineHeight = 22
para.maximumLineHeight = 22
return NSAttributedString.init(string: text, attributes: [.font: UIFont.systemFont(ofSize: 14, weight: .medium), .paragraphStyle: para])
}
static func height(text: String, width: CGFloat) -> CGFloat {
let rect = self.trackText(text: text)
.boundingRect(with: CGSize.init(width: width - 60 - 14 - 16 - 16, height: 9999),
options: .usesLineFragmentOrigin,
context: nil)
return min(rect.height, 44) + 31 + 32
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
3d16a391fcb6d87871a5521e6f9e782f
| 29.767857 | 138 | 0.724318 | 3.619748 | false | false | false | false |
yoichitgy/SwinjectMVVMExample_ForBlog
|
Carthage/Checkouts/Himotoki/Sources/KeyPath.swift
|
3
|
1270
|
//
// KeyPath.swift
// Himotoki
//
// Created by Syo Ikeda on 6/5/15.
// Copyright (c) 2015 Syo Ikeda. All rights reserved.
//
public struct KeyPath: Equatable {
public let components: [String]
public init(_ key: String) {
self.init([key])
}
public init(_ components: [String]) {
self.components = components
}
}
public func == (lhs: KeyPath, rhs: KeyPath) -> Bool {
return lhs.components == rhs.components
}
extension KeyPath: CustomStringConvertible {
public var description: String {
return "KeyPath(\(components))"
}
}
extension KeyPath: StringLiteralConvertible {
public typealias UnicodeScalarLiteralType = StringLiteralType
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(value)
}
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
}
extension KeyPath: ArrayLiteralConvertible {
public typealias Element = String
public init(arrayLiteral elements: String...) {
self.init(elements)
}
}
|
mit
|
bc3d93c54684df0b989752e218277707
| 22.518519 | 91 | 0.686614 | 4.810606 | false | false | false | false |
austinzheng/swift
|
stdlib/public/core/Filter.swift
|
5
|
11249
|
//===--- Filter.swift -----------------------------------------*- 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
//
//===----------------------------------------------------------------------===//
/// A sequence whose elements consist of the elements of some base
/// sequence that also satisfy a given predicate.
///
/// - Note: `s.lazy.filter { ... }`, for an arbitrary sequence `s`,
/// is a `LazyFilterSequence`.
@_fixed_layout // lazy-performance
public struct LazyFilterSequence<Base: Sequence> {
@usableFromInline // lazy-performance
internal var _base: Base
/// The predicate used to determine which elements produced by
/// `base` are also produced by `self`.
@usableFromInline // lazy-performance
internal let _predicate: (Base.Element) -> Bool
/// Creates an instance consisting of the elements `x` of `base` for
/// which `isIncluded(x) == true`.
@inlinable // lazy-performance
public // @testable
init(_base base: Base, _ isIncluded: @escaping (Base.Element) -> Bool) {
self._base = base
self._predicate = isIncluded
}
}
extension LazyFilterSequence {
/// An iterator over the elements traversed by some base iterator that also
/// satisfy a given predicate.
///
/// - Note: This is the associated `Iterator` of `LazyFilterSequence`
/// and `LazyFilterCollection`.
@_fixed_layout // lazy-performance
public struct Iterator {
/// The underlying iterator whose elements are being filtered.
public var base: Base.Iterator { return _base }
@usableFromInline // lazy-performance
internal var _base: Base.Iterator
@usableFromInline // lazy-performance
internal let _predicate: (Base.Element) -> Bool
/// Creates an instance that produces the elements `x` of `base`
/// for which `isIncluded(x) == true`.
@inlinable // lazy-performance
internal init(_base: Base.Iterator, _ isIncluded: @escaping (Base.Element) -> Bool) {
self._base = _base
self._predicate = isIncluded
}
}
}
extension LazyFilterSequence.Iterator: IteratorProtocol, Sequence {
public typealias Element = Base.Element
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@inlinable // lazy-performance
public mutating func next() -> Element? {
while let n = _base.next() {
if _predicate(n) {
return n
}
}
return nil
}
}
extension LazyFilterSequence: Sequence {
public typealias Element = Base.Element
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@inlinable // lazy-performance
public __consuming func makeIterator() -> Iterator {
return Iterator(_base: _base.makeIterator(), _predicate)
}
@inlinable
public func _customContainsEquatableElement(_ element: Element) -> Bool? {
// optimization to check the element first matches the predicate
guard _predicate(element) else { return false }
return _base._customContainsEquatableElement(element)
}
}
extension LazyFilterSequence: LazySequenceProtocol { }
/// A lazy `Collection` wrapper that includes the elements of an
/// underlying collection that satisfy a predicate.
///
/// - Note: The performance of accessing `startIndex`, `first`, any methods
/// that depend on `startIndex`, or of advancing an index depends
/// on how sparsely the filtering predicate is satisfied, and may not offer
/// the usual performance given by `Collection`. Be aware, therefore, that
/// general operations on `LazyFilterCollection` instances may not have the
/// documented complexity.
public typealias LazyFilterCollection<T: Collection> = LazyFilterSequence<T>
extension LazyFilterCollection: Collection {
public typealias SubSequence = LazyFilterCollection<Base.SubSequence>
// Any estimate of the number of elements that pass `_predicate` requires
// iterating the collection and evaluating each element, which can be costly,
// is unexpected, and usually doesn't pay for itself in saving time through
// preventing intermediate reallocations. (SR-4164)
@inlinable // lazy-performance
public var underestimatedCount: Int { return 0 }
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Base.Index
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
///
/// - Complexity: O(*n*), where *n* is the ratio between unfiltered and
/// filtered collection counts.
@inlinable // lazy-performance
public var startIndex: Index {
var index = _base.startIndex
while index != _base.endIndex && !_predicate(_base[index]) {
_base.formIndex(after: &index)
}
return index
}
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// `endIndex` is always reachable from `startIndex` by zero or more
/// applications of `index(after:)`.
@inlinable // lazy-performance
public var endIndex: Index {
return _base.endIndex
}
// TODO: swift-3-indexing-model - add docs
@inlinable // lazy-performance
public func index(after i: Index) -> Index {
var i = i
formIndex(after: &i)
return i
}
@inlinable // lazy-performance
public func formIndex(after i: inout Index) {
// TODO: swift-3-indexing-model: _failEarlyRangeCheck i?
var index = i
_precondition(index != _base.endIndex, "Can't advance past endIndex")
repeat {
_base.formIndex(after: &index)
} while index != _base.endIndex && !_predicate(_base[index])
i = index
}
@inline(__always)
@inlinable // lazy-performance
internal func _advanceIndex(_ i: inout Index, step: Int) {
repeat {
_base.formIndex(&i, offsetBy: step)
} while i != _base.endIndex && !_predicate(_base[i])
}
@inline(__always)
@inlinable // lazy-performance
internal func _ensureBidirectional(step: Int) {
// FIXME: This seems to be the best way of checking whether _base is
// forward only without adding an extra protocol requirement.
// index(_:offsetBy:limitedBy:) is chosen becuase it is supposed to return
// nil when the resulting index lands outside the collection boundaries,
// and therefore likely does not trap in these cases.
if step < 0 {
_ = _base.index(
_base.endIndex, offsetBy: step, limitedBy: _base.startIndex)
}
}
@inlinable // lazy-performance
public func distance(from start: Index, to end: Index) -> Int {
// The following line makes sure that distance(from:to:) is invoked on the
// _base at least once, to trigger a _precondition in forward only
// collections.
_ = _base.distance(from: start, to: end)
var _start: Index
let _end: Index
let step: Int
if start > end {
_start = end
_end = start
step = -1
}
else {
_start = start
_end = end
step = 1
}
var count = 0
while _start != _end {
count += step
formIndex(after: &_start)
}
return count
}
@inlinable // lazy-performance
public func index(_ i: Index, offsetBy n: Int) -> Index {
var i = i
let step = n.signum()
// The following line makes sure that index(_:offsetBy:) is invoked on the
// _base at least once, to trigger a _precondition in forward only
// collections.
_ensureBidirectional(step: step)
for _ in 0 ..< abs(numericCast(n)) {
_advanceIndex(&i, step: step)
}
return i
}
@inlinable // lazy-performance
public func formIndex(_ i: inout Index, offsetBy n: Int) {
i = index(i, offsetBy: n)
}
@inlinable // lazy-performance
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
var i = i
let step = n.signum()
// The following line makes sure that index(_:offsetBy:limitedBy:) is
// invoked on the _base at least once, to trigger a _precondition in
// forward only collections.
_ensureBidirectional(step: step)
for _ in 0 ..< abs(numericCast(n)) {
if i == limit {
return nil
}
_advanceIndex(&i, step: step)
}
return i
}
@inlinable // lazy-performance
public func formIndex(
_ i: inout Index, offsetBy n: Int, limitedBy limit: Index
) -> Bool {
if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) {
i = advancedIndex
return true
}
i = limit
return false
}
/// Accesses the element at `position`.
///
/// - Precondition: `position` is a valid position in `self` and
/// `position != endIndex`.
@inlinable // lazy-performance
public subscript(position: Index) -> Element {
return _base[position]
}
@inlinable // lazy-performance
public subscript(bounds: Range<Index>) -> SubSequence {
return SubSequence(_base: _base[bounds], _predicate)
}
@inlinable
public func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? {
guard _predicate(element) else { return .some(nil) }
return _base._customLastIndexOfEquatableElement(element)
}
}
extension LazyFilterCollection: LazyCollectionProtocol { }
extension LazyFilterCollection : BidirectionalCollection
where Base : BidirectionalCollection {
@inlinable // lazy-performance
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
@inlinable // lazy-performance
public func formIndex(before i: inout Index) {
// TODO: swift-3-indexing-model: _failEarlyRangeCheck i?
var index = i
_precondition(index != _base.startIndex, "Can't retreat before startIndex")
repeat {
_base.formIndex(before: &index)
} while !_predicate(_base[index])
i = index
}
}
extension LazySequenceProtocol {
/// Returns the elements of `self` that satisfy `isIncluded`.
///
/// - Note: The elements of the result are computed on-demand, as
/// the result is used. No buffering storage is allocated and each
/// traversal step invokes `predicate` on one or more underlying
/// elements.
@inlinable // lazy-performance
public __consuming func filter(
_ isIncluded: @escaping (Elements.Element) -> Bool
) -> LazyFilterSequence<Self.Elements> {
return LazyFilterSequence(_base: self.elements, isIncluded)
}
}
extension LazyFilterSequence {
@available(swift, introduced: 5)
public __consuming func filter(
_ isIncluded: @escaping (Element) -> Bool
) -> LazyFilterSequence<Base> {
return LazyFilterSequence(_base: _base) {
isIncluded($0) && self._predicate($0)
}
}
}
|
apache-2.0
|
50e4cdcbb6ce9f1dddaff640c2fee407
| 31.605797 | 89 | 0.663615 | 4.308311 | false | false | false | false |
bsorrentino/slidesOnTV
|
slides/FavoritesCommandView.swift
|
1
|
1348
|
//
// FavoriteCommandsView.swift
// slides
//
// Created by softphone on 26/06/2017.
// Copyright © 2017 soulsoftware. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class FavoritesCommandView: UIView {
@IBOutlet weak var downloadProgressView: UIProgressView!
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
/*
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
// MARK: FOCUS MANAGEMENT
/*
private var _preferredFocusIndex:Int = 0
override var preferredFocusEnvironments : [UIFocusEnvironment] {
return [ commandButton[_preferredFocusIndex] ]
}
override func shouldUpdateFocus(in context: UIFocusUpdateContext) -> Bool {
print( "\(String(describing: type(of: self))).shouldUpdateFocus: \(describing(context.focusHeading))" )
if context.focusHeading == .up || context.focusHeading == .down {
_preferredFocusIndex = 0
}
else if context.focusHeading == .left || context.focusHeading == .right {
let tag = context.previouslyFocusedView?.tag
_preferredFocusIndex = (tag == 0 ) ? 1 : 0;
}
return true
}
*/
}
|
mit
|
8d8a49bab465d993f7ca1cadf71b6815
| 25.411765 | 111 | 0.619154 | 4.613014 | false | false | false | false |
bigtreenono/NSPTools
|
RayWenderlich/Introduction to Swift/7 . Functions/DemoFunctionsPlayground.playground/section-1.swift
|
1
|
1266
|
// Playground - noun: a place where people can play
import UIKit
func count(#targetNumber:Int) ->() {
for n in 0 ... targetNumber {
println(n)
}
}
count(targetNumber:10)
func countTo(targetNumber:Int,by:Int = 2, #dividedBy:Int) {
for var i = 0; i < targetNumber; i += by {
println(i)
}
}
countTo(10, by:5, dividedBy:2)
func bizzaroCase(inout text:String) -> String {
text += "!"
var result = ""
for (index, element) in enumerate(text) {
var letter = String(element)
if index % 2 == 0 {
result += letter.uppercaseString
} else {
result += letter.lowercaseString
}
}
return result
}
var hello = "Hello World"
bizzaroCase(&hello)
hello
func bizzaroCase2(text:String...) -> [String] {
var results = [String]()
for item in text {
var result = ""
for (index, element) in enumerate(item) {
var letter = String(element)
if index % 2 == 0 {
result += letter.uppercaseString
} else {
result += letter.lowercaseString
}
}
results.append(result)
}
return results
}
var text = "He thrusts his fist against the post and still insists that he sees ghosts."
var text2 = "She sells seashells by the seashore."
let bizzaro = bizzaroCase2(text)
bizzaro
|
mit
|
1007cd158160b2ef01c98bc9223c3ddc
| 18.78125 | 88 | 0.628752 | 3.376 | false | false | false | false |
TarangKhanna/Inspirator
|
WorkoutMotivation/TextFieldViewController.swift
|
2
|
2671
|
//
// TextFieldViewController.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/15/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
class TextFieldViewController: UIViewController {
@IBOutlet var textField1: MKTextField!
@IBOutlet var textField2: MKTextField!
@IBOutlet var textField3: MKTextField!
@IBOutlet var textField4: MKTextField!
@IBOutlet var textField5: MKTextField!
@IBOutlet var textField6: MKTextField!
override func viewDidLoad() {
// No border, no shadow, floatPlaceHolderDisabled
textField1.layer.borderColor = UIColor.clearColor().CGColor
textField1.placeholder = "Placeholder"
textField1.tintColor = UIColor.grayColor()
// No border, shadow, floatPlaceHolderDisabled
textField2.layer.borderColor = UIColor.clearColor().CGColor
textField2.placeholder = "Repo name"
textField2.backgroundColor = UIColor(hex: 0xE0E0E0)
textField2.tintColor = UIColor.grayColor()
// Border, no shadow, floatPlaceHolderDisabled
textField3.layer.borderColor = UIColor.MKColor.Grey.CGColor
textField3.rippleLayerColor = UIColor.MKColor.Amber
textField3.tintColor = UIColor.MKColor.DeepOrange
textField3.rippleLocation = .Left
// No border, no shadow, floatingPlaceholderEnabled
textField4.layer.borderColor = UIColor.clearColor().CGColor
textField4.floatingPlaceholderEnabled = true
textField4.placeholder = "Github"
textField4.tintColor = UIColor.MKColor.Blue
textField4.rippleLocation = .Right
textField4.cornerRadius = 0
textField4.bottomBorderEnabled = true
// No border, shadow, floatingPlaceholderEnabled
textField5.layer.borderColor = UIColor.clearColor().CGColor
textField5.floatingPlaceholderEnabled = true
textField5.placeholder = "Email account"
textField5.rippleLayerColor = UIColor.MKColor.LightBlue
textField5.tintColor = UIColor.MKColor.Blue
textField5.backgroundColor = UIColor(hex: 0xE0E0E0)
// Border, floatingPlaceholderEnabled
textField6.floatingPlaceholderEnabled = true
textField6.cornerRadius = 1.0
textField6.placeholder = "Description"
textField6.layer.borderColor = UIColor.MKColor.Green.CGColor
textField6.rippleLayerColor = UIColor.MKColor.LightGreen
textField6.tintColor = UIColor.MKColor.LightGreen
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true)
}
}
|
apache-2.0
|
7da23e0df6229ef590541574ba5219f7
| 38.880597 | 116 | 0.697866 | 4.761141 | false | false | false | false |
tomizimobile/AsyncDisplayKit
|
examples_extra/Shop/Shop/Scenes/Product/ProductViewController.swift
|
11
|
1421
|
//
// ProductViewController.swift
// Shop
//
// Created by Dimitri on 10/11/2016.
// Copyright © 2016 Dimitri. All rights reserved.
//
import UIKit
class ProductViewController: ASViewController<ASTableNode> {
// MARK: - Variables
let product: Product
private var tableNode: ASTableNode {
return node
}
// MARK: - Object life cycle
init(product: Product) {
self.product = product
super.init(node: ASTableNode())
tableNode.delegate = self
tableNode.dataSource = self
tableNode.backgroundColor = UIColor.primaryBackgroundColor()
tableNode.view.separatorStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View life cycle
override func viewDidLoad() {
super.viewDidLoad()
self.setupTitle()
}
}
extension ProductViewController: ASTableDataSource, ASTableDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: ASTableView, nodeForRowAt indexPath: IndexPath) -> ASCellNode {
let node = ProductCellNode(product: self.product)
return node
}
}
extension ProductViewController {
func setupTitle() {
self.title = self.product.title
}
}
|
bsd-3-clause
|
4646ff8dba3f41d50c1e7556e21cedb0
| 21.903226 | 95 | 0.63662 | 4.749164 | false | false | false | false |
dataich/TypetalkSwift
|
Carthage/Checkouts/OAuth2/Sources/iOS/OAuth2WebViewController.swift
|
1
|
7531
|
//
// OAuth2WebViewController.swift
// OAuth2
//
// Created by Pascal Pfiffner on 7/15/14.
// Copyright 2014 Pascal Pfiffner
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#if os(iOS)
import UIKit
import WebKit
#if !NO_MODULE_IMPORT
import Base
#endif
/**
A simple iOS web view controller that allows you to display the login/authorization screen.
*/
open class OAuth2WebViewController: UIViewController, WKNavigationDelegate {
/// Handle to the OAuth2 instance in play, only used for debug lugging at this time.
var oauth: OAuth2?
/// The URL to load on first show.
open var startURL: URL? {
didSet(oldURL) {
if nil != startURL && nil == oldURL && isViewLoaded {
load(url: startURL!)
}
}
}
/// The URL string to intercept and respond to.
var interceptURLString: String? {
didSet(oldURL) {
if let interceptURLString = interceptURLString {
if let url = URL(string: interceptURLString) {
interceptComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)
}
else {
oauth?.logger?.debug("OAuth2", msg: "Failed to parse URL \(interceptURLString), discarding")
self.interceptURLString = nil
}
}
else {
interceptComponents = nil
}
}
}
var interceptComponents: URLComponents?
/// Closure called when the web view gets asked to load the redirect URL, specified in `interceptURLString`. Return a Bool indicating
/// that you've intercepted the URL.
var onIntercept: ((URL) -> Bool)?
/// Called when the web view is about to be dismissed. The Bool indicates whether the request was (user-)canceled.
var onWillDismiss: ((_ didCancel: Bool) -> Void)?
/// Assign to override the back button, shown when it's possible to go back in history. Will adjust target/action accordingly.
open var backButton: UIBarButtonItem? {
didSet {
if let backButton = backButton {
backButton.target = self
backButton.action = #selector(OAuth2WebViewController.goBack(_:))
}
}
}
var showCancelButton = true
var cancelButton: UIBarButtonItem?
/// Our web view.
var webView: WKWebView?
/// An overlay view containing a spinner.
var loadingView: UIView?
init() {
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - View Handling
override open func loadView() {
edgesForExtendedLayout = .all
extendedLayoutIncludesOpaqueBars = true
automaticallyAdjustsScrollViewInsets = true
super.loadView()
view.backgroundColor = UIColor.white
if showCancelButton {
cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(OAuth2WebViewController.cancel(_:)))
navigationItem.rightBarButtonItem = cancelButton
}
// create a web view
let web = WKWebView()
web.translatesAutoresizingMaskIntoConstraints = false
web.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal
web.navigationDelegate = self
view.addSubview(web)
let views = ["web": web]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[web]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[web]|", options: [], metrics: nil, views: views))
webView = web
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let web = webView, !web.canGoBack {
if nil != startURL {
load(url: startURL!)
}
else {
web.loadHTMLString("There is no `startURL`", baseURL: nil)
}
}
}
func showHideBackButton(_ show: Bool) {
if show {
let bb = backButton ?? UIBarButtonItem(barButtonSystemItem: .rewind, target: self, action: #selector(OAuth2WebViewController.goBack(_:)))
navigationItem.leftBarButtonItem = bb
}
else {
navigationItem.leftBarButtonItem = nil
}
}
func showLoadingIndicator() {
// TODO: implement
}
func hideLoadingIndicator() {
// TODO: implement
}
func showErrorMessage(_ message: String, animated: Bool) {
NSLog("Error: \(message)")
}
// MARK: - Actions
open func load(url: URL) {
let _ = webView?.load(URLRequest(url: url))
}
@objc func goBack(_ sender: AnyObject?) {
let _ = webView?.goBack()
}
@objc func cancel(_ sender: AnyObject?) {
dismiss(asCancel: true, animated: (nil != sender) ? true : false)
}
override open func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
dismiss(asCancel: false, animated: flag, completion: completion)
}
func dismiss(asCancel: Bool, animated: Bool, completion: (() -> Void)? = nil) {
webView?.stopLoading()
if nil != self.onWillDismiss {
self.onWillDismiss!(asCancel)
}
super.dismiss(animated: animated, completion: completion)
}
// MARK: - Web View Delegate
open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
guard let onIntercept = onIntercept else {
decisionHandler(.allow)
return
}
let request = navigationAction.request
// we compare the scheme and host first, then check the path (if there is any). Not sure if a simple string comparison
// would work as there may be URL parameters attached
if let url = request.url, url.scheme == interceptComponents?.scheme && url.host == interceptComponents?.host {
let haveComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)
if let hp = haveComponents?.path, let ip = interceptComponents?.path, hp == ip || ("/" == hp + ip) {
if onIntercept(url) {
decisionHandler(.cancel)
}
else {
decisionHandler(.allow)
}
return
}
}
decisionHandler(.allow)
}
open func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
if "file" != webView.url?.scheme {
showLoadingIndicator()
}
}
open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if let scheme = interceptComponents?.scheme, "urn" == scheme {
if let path = interceptComponents?.path, path.hasPrefix("ietf:wg:oauth:2.0:oob") {
if let title = webView.title, title.hasPrefix("Success ") {
oauth?.logger?.debug("OAuth2", msg: "Creating redirect URL from document.title")
let qry = title.replacingOccurrences(of: "Success ", with: "")
if let url = URL(string: "http://localhost/?\(qry)") {
_ = onIntercept?(url)
return
}
oauth?.logger?.warn("OAuth2", msg: "Failed to create a URL with query parts \"\(qry)\"")
}
}
}
hideLoadingIndicator()
showHideBackButton(webView.canGoBack)
}
open func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
if NSURLErrorDomain == error._domain && NSURLErrorCancelled == error._code {
return
}
// do we still need to intercept "WebKitErrorDomain" error 102?
if nil != loadingView {
showErrorMessage(error.localizedDescription, animated: true)
}
}
}
#endif
|
mit
|
e792410d7b04090f1f64575c3bad57b1
| 28.649606 | 165 | 0.69911 | 3.944997 | false | false | false | false |
alvaromb/EventBlankApp
|
EventBlank/EventBlank/ViewControllers/Web/WebViewController.swift
|
3
|
4522
|
//
// WebViewController.swift
// EventBlank
//
// Created by Marin Todorov on 6/21/15.
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import UIKit
import WebKit
import Reachability
//TODO: check the safari vc in iOS9 if iOS9 adoption rate is real high
class WebViewController: UIViewController, WKNavigationDelegate {
var initialURL: NSURL! //set from previous controller
private var webView = WKWebView()
var loadingIndicator = UIView()
override func viewDidLoad() {
super.viewDidLoad()
self.title = initialURL.absoluteString
webView.frame = view.bounds
webView.frame.size.height -= ((UIApplication.sharedApplication().windows.first! as! UIWindow).rootViewController! as! UITabBarController).tabBar.frame.size.height
webView.navigationDelegate = self
view.insertSubview(webView, belowSubview: loadingIndicator)
//setup loading indicator
loadingIndicator.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 0.15)
loadingIndicator.userInteractionEnabled = false
loadingIndicator.hidden = true
navigationController?.navigationBar.addSubview(loadingIndicator)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//observe the progress
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)
loadInitialURL()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
//remove observer
webView.stopLoading()
webView.removeObserver(self, forKeyPath: "estimatedProgress")
loadingIndicator.removeFromSuperview()
}
func loadInitialURL() {
//not connected message
let reach = Reachability(hostName: initialURL!.host)
if !reach.isReachable() {
//show the message
view.addSubview(MessageView(text: "It certainly looks like you are not connected to the Internet right now..."))
//show a reload button
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "loadInitialURL")
return
}
MessageView.removeViewFrom(view)
navigationItem.rightBarButtonItem = nil
//load the target url
let request = NSURLRequest(URL: initialURL!)
webView.loadRequest(request)
setLoadingIndicatorAnimating(true)
}
func setLoadingIndicatorAnimating(animating: Bool) {
loadingIndicator.hidden = !animating
if animating {
loadingIndicator.frame = CGRect(x: 0, y: 0, width: 30, height: navigationController!.navigationBar.bounds.size.height)
}
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if keyPath == "estimatedProgress" {
if loadingIndicator.hidden {
loadingIndicator.hidden = false
}
self.title = webView.title ?? webView.URL?.absoluteString
UIView.animateWithDuration(0.25, delay: 0.0, options: .CurveEaseOut, animations: {
self.loadingIndicator.frame = CGRect(
x: 0, y: 0,
width: self.navigationController!.navigationBar.bounds.size.width * CGFloat(self.webView.estimatedProgress),
height: self.navigationController!.navigationBar.bounds.size.height)
}, completion: {_ in
if self.webView.estimatedProgress > 0.95 {
mainQueue {
//hide the loading indicator
UIView.animateWithDuration(0.2, animations: {
self.loadingIndicator.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 1.0, alpha: 0.15)
}, completion: {_ in
self.setLoadingIndicatorAnimating(false)
self.loadingIndicator.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 0.15)
})
}
}
})
}
}
}
|
mit
|
b54aa69fdbdfe67628528645b9957ffa
| 36.683333 | 170 | 0.601504 | 5.514634 | false | false | false | false |
younata/RSSClient
|
TethysKitSpecs/Models/SubscriptionSpec.swift
|
1
|
3656
|
import Quick
import Nimble
@testable import TethysKit
final class SubscriptionSpec: QuickSpec {
override func spec() {
var subject: Publisher<Int>!
beforeEach {
subject = Publisher<Int>()
}
describe("-then(:)") {
var received: [SubscriptionUpdate<Int>] = []
var observer: Observer!
beforeEach {
received = []
observer = Observer()
let memoryManagementReactor = IncrementOnDealloc(observed: observer)
subject.subscription.then {
memoryManagementReactor.doSomething()
received.append($0)
}
}
it("it does not call the callbacks") {
expect(received).to(beEmpty())
}
it("has a value of nil") {
expect(subject.subscription.value).to(beNil())
}
describe("when updated") {
beforeEach {
subject.update(with: 20)
}
it("calls the callbacks") {
expect(received).to(equal([.update(20)]))
}
it("immediately calls any additional callbacks that might be added") {
var moreReceived = [SubscriptionUpdate<Int>]()
subject.subscription.then { moreReceived.append($0) }
expect(moreReceived).to(equal([.update(20)]))
}
it("sets the subscription's value") {
expect(subject.subscription.value).to(equal(20))
}
describe("making more updates") {
beforeEach {
subject.update(with: 30)
}
it("calls the callbacks") {
expect(received).to(equal([.update(20), .update(30)]))
}
it("updates the subscription's value") {
expect(subject.subscription.value).to(equal(30))
}
it("additional callbacks now only received the latest value") {
var moreReceived = [SubscriptionUpdate<Int>]()
subject.subscription.then { moreReceived.append($0) }
expect(moreReceived).to(equal([.update(30)]))
}
}
describe("when finished") {
beforeEach {
subject.finish()
}
it("makes one last call, notifying the user that the subscription has petered out") {
expect(received).to(equal([.update(20), .finished]))
}
it("stops holding on to the callback blocks") {
expect(observer.count).to(equal(1), description: "Expected the block to have been deallocated")
}
it("notes to those who ask that it's finished") {
expect(subject.subscription.isFinished).to(beTrue())
expect(subject.isFinished).to(beTrue())
}
}
}
}
}
}
private class Observer {
private(set) var count = 0
init() {}
func observe() {
count += 1
}
}
private class IncrementOnDealloc {
private let observed: Observer
init(observed: Observer) {
self.observed = observed
}
func doSomething() {
}
deinit {
self.observed.observe()
}
}
|
mit
|
24cdbd2408019e348f019ff61bd20953
| 27.787402 | 119 | 0.467724 | 5.581679 | false | false | false | false |
stowy/LayoutKit
|
Sources/Layout.swift
|
5
|
5452
|
// Copyright 2016 LinkedIn Corp.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import CoreGraphics
/**
A protocol for types that layout view frames.
### Basic layouts
Many UIs can be expressed by composing the basic layouts that LayoutKit provides:
- `LabelLayout`
- `InsetLayout`
- `SizeLayout`
- `StackLayout`
If your UI can not be expressed by composing these basic layouts,
then you can create a custom layout. Custom layouts are recommended but not required to conform
to the `ConfigurableLayout` protocol due to the type safety and default implementation that it adds.
### Layout algorithm
Layout is performed in two steps:
1. `measurement(within:)`
2. `arrangement(within:measurement:)`.
`arrangement(origin:width:height:)` is a convenience method for doing both passes in one function call.
### Threading
Layouts MUST be thread-safe.
*/
public protocol Layout {
/**
Measures the minimum size of the layout and its sublayouts.
It MAY be run on a background thread.
- parameter maxSize: The maximum size available to the layout.
- returns: The minimum size required by the layout and its sublayouts given a maximum size.
The size of the layout MUST NOT exceed `maxSize`.
*/
func measurement(within maxSize: CGSize) -> LayoutMeasurement
/**
Returns the arrangement of frames for the layout inside a given rect.
The frames SHOULD NOT overflow rect, otherwise they may overlap with adjacent layouts.
The layout MAY choose to not use the entire rect (and instead align itself in some way inside of the rect),
but the caller SHOULD NOT reallocate unused space to other layouts because this could break the layout's desired alignment and padding.
Space allocation SHOULD happen during the measure pass.
MAY be run on a background thread.
- parameter rect: The rectangle that the layout must position itself in.
- parameter measurement: A measurement which has size less than or equal to `rect.size` and greater than or equal to `measurement.maxSize`.
- returns: A complete set of frames for the layout.
*/
func arrangement(within rect: CGRect, measurement: LayoutMeasurement) -> LayoutArrangement
/**
Indicates whether a View object needs to be created for this layout.
Layouts that just position their sublayouts can return false here.
*/
var needsView: Bool { get }
/**
Returns a new UIView for the layout.
It is not called on a layout if the layout is using a recycled view.
MUST be run on the main thread.
*/
func makeView() -> View
/**
Configures the given view.
MUST be run on the main thread.
*/
func configure(baseTypeView: View)
/**
The flexibility of the layout.
If a layout has a single sublayout, it SHOULD inherit the flexiblity of its sublayout.
If a layout has no sublayouts (e.g. LabelLayout), it SHOULD allow its flexibility to be configured.
All layouts SHOULD provide a default flexiblity.
TODO: figure out how to assert if inflexible layouts are compressed.
*/
var flexibility: Flexibility { get }
/**
An identifier for the view that is produced by this layout.
If this layout is applied to an existing view hierarchy, and if there is a view with an identical viewReuseId,
then that view will be reused for the new layout. If there is more than one view with the same viewReuseId, then an arbitrary one will be reused.
*/
var viewReuseId: String? { get }
}
public extension Layout {
/**
Convenience function that measures and positions the layout given exact width and/or height constraints.
- parameter origin: The returned layout will be positioned at origin. Defaults to CGPointZero.
- parameter width: The exact width that the layout should consume.
If nil, the layout is given exactly the size that it requested during the measure pass.
- parameter height: The exact height that the layout should consume.
If nil, the layout is given exactly the size that it requested during the measure pass.
*/
final func arrangement(origin: CGPoint = .zero, width: CGFloat? = nil, height: CGFloat? = nil) -> LayoutArrangement {
// let start = CFAbsoluteTimeGetCurrent()
let maxSize = CGSize(width: width ?? CGFloat.greatestFiniteMagnitude, height: height ?? CGFloat.greatestFiniteMagnitude)
let measurement = self.measurement(within: maxSize)
// let measureEnd = CFAbsoluteTimeGetCurrent()
var rect = CGRect(origin: origin, size: measurement.size)
rect.size.width = width ?? rect.size.width
rect.size.height = height ?? rect.size.height
let arrangement = self.arrangement(within: rect, measurement: measurement)
// let layoutEnd = CFAbsoluteTimeGetCurrent()
// NSLog("layout: \((layoutEnd-start).ms) (measure: \((measureEnd-start).ms) + layout: \((layoutEnd-measureEnd).ms))")
return arrangement
}
}
|
apache-2.0
|
45c7275e0badea310dedf10cb7df594a
| 39.686567 | 150 | 0.711299 | 4.799296 | false | false | false | false |
DanielAsher/Side-Menu.iOS
|
SideMenu/MenuTransitionAnimator.swift
|
2
|
2317
|
//
// Copyright © 2014 Yalantis
// Licensed under the MIT license: http://opensource.org/licenses/MIT
// Latest version can be found at http://github.com/yalantis/Side-Menu.iOS
//
import UIKit
class MenuTransitionAnimator: NSObject {
enum Mode { case Presentation, Dismissal }
private let mode: Mode
private let duration = 0.5
private let angle: CGFloat = 2
init(_ mode: Mode) {
self.mode = mode
}
private func animatePresentation(context: UIViewControllerContextTransitioning) {
let host = context.viewControllerForKey(UITransitionContextFromViewControllerKey)!
let menu = context.viewControllerForKey(UITransitionContextToViewControllerKey)!
let view = menu.view
view.frame = CGRectMake(0, 0, menu.preferredContentSize.width, host.view.bounds.height)
view.autoresizingMask = [.FlexibleRightMargin, .FlexibleHeight]
view.translatesAutoresizingMaskIntoConstraints = true
context.containerView()!.addSubview(view)
animateMenu(menu as! Menu, startAngle: angle, endAngle: 0) {
context.completeTransition(true)
}
}
private func animateDismissal(context: UIViewControllerContextTransitioning) {
if let menu = context.viewControllerForKey(UITransitionContextFromViewControllerKey) {
animateMenu(menu as! Menu, startAngle: 0, endAngle: angle) {
menu.view.removeFromSuperview()
context.completeTransition(true)
}
}
}
private func animateMenu(menu: Menu, startAngle: CGFloat, endAngle: CGFloat, completion: () -> Void) {
let animator = MenuItemsAnimator(views: menu.menuItems, startAngle: startAngle, endAngle: endAngle)
animator.duration = duration
animator.completion = completion
animator.start()
}
}
extension MenuTransitionAnimator: UIViewControllerAnimatedTransitioning {
func animateTransition(context: UIViewControllerContextTransitioning) {
switch mode {
case .Presentation:
animatePresentation(context)
case .Dismissal:
animateDismissal(context)
}
}
func transitionDuration(context: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
}
|
mit
|
adfe8885575aca1bfea37a497476c042
| 34.646154 | 107 | 0.687824 | 5.475177 | false | false | false | false |
AnthonyOliveri/bms-clientsdk-swift-push
|
Source/BMSConstants.swift
|
2
|
2565
|
/*
* Copyright 2016 IBM Corp.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
internal var DUMP_TRACE:Bool = true
internal let QUERY_PARAM_SUBZONE = "="
internal let STAGE1 = "stage1"
internal let BLUEMIX_DOMAIN = "bluemix.net"
internal let IMFPUSH_ACTION_DELETE = "action=delete"
internal let IMFPUSH_CONTENT_TYPE_JSON = "application/json; charset = UTF-8"
internal let IMFPUSH_CONTENT_TYPE_KEY = "Content-Type"
internal let IMFPUSH_DEVICE_ID = "deviceId"
internal let IMFPUSH_DEVICES = "devices"
//internal let IMFPUSH_USER_ID = "pushUser"
internal let IMFPUSH_USERID = "userId"
internal let IMFPUSH_CLIENT_SECRET = "clientSecret"
internal let IMFPUSH_TOKEN = "token"
internal let IMFPUSH_PLATFORM = "platform"
internal let IMFPUSH_TAGS = "tags"
internal let IMFPUSH_TAGNAME = "tagName"
internal let IMFPUSH_TAGNAMES = "tagNames"
internal let IMFPUSH_TAGSNOTFOUND = "tagsNotFound"
internal let IMFPUSH_NAME = "name"
internal let IMFPUSH_SUBSCRIPTIONS = "subscriptions"
internal let IMFPUSH_SUBSCRIBED = "subscribed"
internal let IMFPUSH_SUBSCRIPTIONEXISTS = "subscriptionExists"
internal let IMFPUSH_UNSUBSCRIBED = "unsubscribed"
internal let IMFPUSH_UNSUBSCRIPTIONS = "unsubscriptions"
internal let IMFPUSH_SUBSCRIPTIONNOTEXISTS = "subscriptionNotExists"
internal let IMFPUSH_OPEN = "open"
internal let IMFPUSH_RECEIVED = "received"
internal let IMFPUSH_SEEN = "seen"
internal let IMFPUSH_ACKNOWLEDGED = "acknowledged"
internal let IMFPUSH_APP_MANAGER = "IMFPushAppManager"
internal let IMFPUSH_CLIENT = "IMFPushClient"
internal let IMFPUSH_DISPLAYNAME = "displayName"
internal let IMFPUSH_X_REWRITE_DOMAIN = "X-REWRITE-DOMAIN"
internal let IMFPUSH_PUSH_WORKS_SERVER_CONTEXT = "imfpush/v1/apps"
internal let KEY_METADATA_TYPE = "$type";
internal let TAG_CATEGORY_EVENT = "event";
internal let KEY_METADATA_CATEGORY = "$category";
internal let KEY_METADATA_USER_METADATA = "$userMetadata";
internal let IMFPUSH_STATUS = "status"
|
apache-2.0
|
8e62660ba54d4d346a1666253e4e4eea
| 26.258065 | 78 | 0.747929 | 3.472603 | false | false | false | false |
btanner/Eureka
|
Example/Example/Controllers/PlainTableViewExample.swift
|
4
|
932
|
//
// PlainTableViewExample.swift
// Example
//
// Created by Mathias Claassen on 3/15/18.
// Copyright © 2018 Xmartlabs. All rights reserved.
//
import Eureka
class PlainTableViewStyleController : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form +++
Section()
<<< TextRow() {
$0.title = "Name"
$0.value = "John Doe"
}
<<< TextRow() {
$0.title = "Username"
$0.value = "johndoe1"
}
<<< EmailRow() {
$0.title = "Email Address"
$0.value = "[email protected]"
}
<<< PasswordRow() {
$0.title = "Password"
$0.value = "johndoe9876"
}
// Remove excess separator lines on non-existent cells
tableView.tableFooterView = UIView()
}
}
|
mit
|
b4cc668515bd63f301cef651c5832aa2
| 20.651163 | 62 | 0.47261 | 4.350467 | false | false | false | false |
breadwallet/breadwallet-ios
|
breadwallet/src/ViewModels/WalletConnectionSettings.swift
|
1
|
4099
|
//
// WalletConnectionSettings.swift
// breadwallet
//
// Created by Ehsan Rezaie on 2019-08-28.
// Copyright © 2019 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import Foundation
import WalletKit
typealias WalletConnectionMode = WalletKit.WalletManagerMode
/// View model for the WalletConnectionSettingsViewController and WalletInfo.connectionModes model
class WalletConnectionSettings {
private let system: CoreSystem
private let kvStore: BRReplicatedKVStore
private var walletInfo: WalletInfo
init(system: CoreSystem, kvStore: BRReplicatedKVStore, walletInfo: WalletInfo) {
self.system = system
self.kvStore = kvStore
self.walletInfo = walletInfo
sanitizeAll()
}
static func defaultMode(for currency: Currency) -> WalletConnectionMode {
assert(currency.tokenType == .native)
switch currency.uid {
case Currencies.btc.uid:
return .api_only
case Currencies.bch.uid:
return .api_only
case Currencies.eth.uid:
return .api_only
default:
return .api_only
}
}
func mode(for currency: Currency) -> WalletConnectionMode {
//Force bch to always be api_only mode
guard currency.uid != Currencies.bch.uid else { return .api_only }
assert(currency.tokenType == .native)
if let serialization = walletInfo.connectionModes[currency.uid],
let mode = WalletManagerMode(serialization: serialization) {
return mode
} else {
// valid mode not found, set to default
assert(walletInfo.connectionModes[currency.uid] == nil, "invalid mode serialization found in kv-store")
let mode = WalletConnectionSettings.defaultMode(for: currency)
print("[KV] setting default mode for \(currency.uid): \(mode)")
walletInfo.connectionModes[currency.uid] = mode.serialization
save()
return mode
}
}
func set(mode: WalletConnectionMode, for currency: Currency) {
assert(currency.tokenType == .native)
assert(currency.isBitcoin || currency.isEthereum) //TODO:CRYPTO_V2
guard system.isModeSupported(mode, for: currency.network) || E.isRunningTests else { return assertionFailure() }
walletInfo.connectionModes[currency.uid] = mode.serialization
guard let wm = currency.wallet?.manager else { return assert(E.isRunningTests) }
system.setConnectionMode(mode, forWalletManager: wm)
save()
}
private func save() {
do {
guard let newWalletInfo = try kvStore.set(walletInfo) as? WalletInfo else { return assertionFailure() }
self.walletInfo = newWalletInfo
} catch let error {
print("[KV] error setting wallet info: \(error)")
}
}
/// clean up any invalid modes stored in KV-store
private func sanitizeAll() {
[Currencies.btc.instance,
Currencies.bch.instance,
Currencies.eth.instance]
.compactMap { $0 }
.forEach { sanitize(currency: $0) }
}
private func sanitize(currency: Currency) {
if let modeValue = walletInfo.connectionModes[currency.uid],
let mode = WalletConnectionMode(serialization: modeValue),
!system.isModeSupported(mode, for: currency.network) {
// replace unsupported mode with default
walletInfo.connectionModes[currency.uid] = nil
}
}
}
enum WalletManagerModeOverride: Int {
case none
case api
case p2p
var description: String {
switch self {
case .none:
return "none"
case .api:
return "api"
case .p2p:
return "p2p"
}
}
var mode: WalletConnectionMode? {
switch self {
case .none:
return nil
case .api:
return .api_only
case .p2p:
return .p2p_only
}
}
}
|
mit
|
340598ee0e6aa328bc4f4e2c0b9b9378
| 31.52381 | 120 | 0.624451 | 4.630508 | false | false | false | false |
t089/sajson
|
swift/sajson/Decodable/Foundation+_Decodable.swift
|
1
|
1819
|
//
// Foundation+Decodable.swift
// sajson
//
// Created by Tobias Haeberle on 06.07.17.
// Copyright © 2017 Chad Austin. All rights reserved.
//
import Foundation
#if !swift(>=3.2) // The decodable protocol is available in Swift 3.2.
extension Data: Decodable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
// It's more efficient to pre-allocate the buffer if we can.
if let count = container.count {
self.init(count: count)
// Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space.
// We don't want to write past the end of what we allocated.
for i in 0 ..< count {
let byte = try container.decode(UInt8.self)
self[i] = byte
}
} else {
self.init()
}
while !container.isAtEnd {
var byte = try container.decode(UInt8.self)
self.append(&byte, count: 1)
}
}
}
extension Date: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let timestamp = try container.decode(Double.self)
self.init(timeIntervalSinceReferenceDate: timestamp)
}
}
extension UUID: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let value = try container.decode(String.self)
guard let uuid = UUID(uuidString: value) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Expected UUID string but found \(value).")
}
self = uuid
}
}
#endif
|
mit
|
31982d785304067267f71a0e93d9db51
| 29.813559 | 160 | 0.611111 | 4.46683 | false | false | false | false |
See-Ku/SK4Toolkit
|
SK4Toolkit/core/SK4LazyTimer.swift
|
1
|
1222
|
//
// SK4LazyTimer.swift
// SK4Toolkit
//
// Created by See.Ku on 2016/03/27.
// Copyright (c) 2016 AxeRoad. All rights reserved.
//
import Foundation
/// 複数回呼び出されても、最後の1回だけ実行するタイマー
public class SK4LazyTimer: NSObject {
/// 実際に実行するまでの待機時間
var hold: NSTimeInterval = 1.0
/// 実行する処理
var exec: (() -> Void)?
/// 実行回数のカウンター
var counter: UInt64 = 0
/// タイマーを設定 ※Closureは[weak self]推奨
public func setup(hold hold: NSTimeInterval, exec: (() -> Void)?) {
self.hold = hold
self.exec = exec
}
/// タイマーをクリアー
public func clear() {
self.hold = 1.0
self.exec = nil
}
/// 実行を予約
public func fire() {
if exec != nil {
counter += 1
let num = NSNumber(unsignedLongLong: counter)
NSTimer.scheduledTimerWithTimeInterval(hold, target: self, selector: #selector(SK4LazyTimer.onTimer(_:)), userInfo: num, repeats: false)
}
}
/// 最新のタイマーであれば処理を実行
func onTimer(timer: NSTimer) {
if let num = timer.userInfo as? NSNumber {
if num.unsignedLongLongValue == counter {
exec?()
}
}
}
}
// eof
|
mit
|
70a60f7ad89e49b2135d61109cbba8a2
| 18.037037 | 139 | 0.654669 | 2.635897 | false | false | false | false |
aiwalle/LiveProject
|
LiveProject/Rank/Controller/LJWeeklyRankViewController.swift
|
1
|
1801
|
//
// LJWeeklyRankViewController.swift
// LiveProject
//
// Created by liang on 2017/10/26.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
let kLJWeeklyRankViewCell = "LJWeeklyRankViewCell"
class LJWeeklyRankViewController: LJDetailRankViewController {
fileprivate lazy var weeklyRankVM: LJWeeklyRankViewModel = LJWeeklyRankViewModel()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "LJWeeklyRankViewCell", bundle: nil), forCellReuseIdentifier: kLJWeeklyRankViewCell)
}
override init(rankType: LJRankType) {
super.init(rankType: rankType)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension LJWeeklyRankViewController {
override func loadData() {
weeklyRankVM.loadWeeklyRankData(rankType) {
self.tableView.reloadData()
}
}
}
extension LJWeeklyRankViewController {
func numberOfSections(in tableView: UITableView) -> Int {
return weeklyRankVM.weeklyRanks.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return weeklyRankVM.weeklyRanks[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kLJWeeklyRankViewCell) as! LJWeeklyRankViewCell
cell.weekly = weeklyRankVM.weeklyRanks[indexPath.section][indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 0 ? "主播周星榜" : "富豪周星榜"
}
}
|
mit
|
527fa0f7f724aa85fb1fe203f59c00d5
| 27.677419 | 126 | 0.699663 | 4.40099 | false | false | false | false |
tjw/swift
|
test/SILGen/closures.swift
|
1
|
43222
|
// RUN: %target-swift-frontend -module-name closures -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s
// RUN: %target-swift-frontend -module-name closures -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen %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]]
}
// FIXME(integers): the following checks should be updated for the new way +
// gets invoked. <rdar://problem/29939484>
// XCHECK: sil private @[[CLOSURE_NAME]] : $@convention(thin) (Int, @guaranteed { var Int }) -> Int
// XCHECK: bb0([[DOLLAR0:%[0-9]+]] : $Int, [[XBOX:%[0-9]+]] : ${ var Int }):
// XCHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]]
// XCHECK: [[PLUS:%[0-9]+]] = function_ref @$Ss1poiS2i_SitF{{.*}}
// XCHECK: [[LHS:%[0-9]+]] = load [trivial] [[XADDR]]
// XCHECK: [[RET:%[0-9]+]] = apply [[PLUS]]([[LHS]], [[DOLLAR0]])
// XCHECK: destroy_value [[XBOX]]
// XCHECK: 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: [[LOADED_CLASS:%.*]] = load [copy] [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty
// CHECK: [[BORROWED_LOADED_CLASS:%.*]] = begin_borrow [[LOADED_CLASS]]
// 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]] from [[LOADED_CLASS]]
// CHECK: destroy_value [[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: [[LOADED_COPY:%.*]] = load [copy] [[TMP]]
// GUARANTEED: [[BORROWED:%.*]] = begin_borrow [[LOADED_COPY]]
// GUARANTEED: end_borrow [[BORROWED]] from [[LOADED_COPY]]
// GUARANTEED: destroy_value [[LOADED_COPY]]
// 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: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_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: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_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]] from [[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: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_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]] from [[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: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_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]] from [[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: [[BORROWED_ARG_COPY_SUPERCAST:%.*]] = begin_borrow [[ARG_COPY_SUPERCAST]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_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: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_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: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @$S8closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[BORROWED_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]] from [[PB]]
// 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: [[BORROWED_ARG_COPY_SUPER:%.*]] = begin_borrow [[ARG_COPY_SUPER]]
// CHECK: [[METHOD:%.*]] = function_ref @$S8closures12ConcreteBaseC4swimyyF
// CHECK: apply [[METHOD]]([[BORROWED_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
|
9e1212ea9996753a005ed5c815ad403c
| 49.462617 | 296 | 0.605102 | 3.373106 | false | false | false | false |
Pluto-Y/SwiftyEcharts
|
SwiftyEcharts/Models/VisualMap/PiecewiseVisualMap.swift
|
1
|
17361
|
//
// PiecewiseVisualMap.swift
// SwiftyEcharts
//
// Created by Pluto-Y on 20/01/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
public final class PiecewiseVisualMap: VisualMap, Displayable, Borderable, Colorful, Textful, Formatted, Zable {
/// 类型为分段型。
public var type: String {
return "piecewise"
}
/// 对于连续型数据,自动平均切分成几段。默认为5段。 连续数据的范围需要 max 和 min 来指定。
/// 如果设置了 visualMap-piecewise.pieces 或者 visualMap-piecewise.categories,则 splitNumber 无效。
public var splitNumber: Int?
/// 自定义『分段式视觉映射组件(visualMapPiecewise)』的每一段的范围,以及每一段的文字,以及每一段的特别的样式。例如:
///
/// pieces: [
/// {min: 1500}, // 不指定 max,表示 max 为无限大(Infinity)。
/// {min: 900, max: 1500},
/// {min: 310, max: 1000},
/// {min: 200, max: 300},
/// {min: 10, max: 200, label: '10 到 200(自定义label)'},
/// {value: 123, label: '123(自定义特殊颜色)', color: 'grey'}, // 表示 value 等于 123 的情况。
/// {max: 5} // 不指定 min,表示 min 为无限大(-Infinity)。
/// ]
/// 或者,更精确得,可以使用 lt(小于,little than),gt(大于,greater than),lte(小于等于 lettle than or equals),gte(大于等于,greater than or equals)来表达边界:
///
/// pieces: [
/// {gt: 1500}, // (1500, Infinity]
/// {gt: 900, lte: 1500}, // (900, 1500]
/// {gt: 310, lte: 1000}, // (310, 1000]
/// {gt: 200, lte: 300}, // (200, 300]
/// {gt: 10, lte: 200, label: '10 到 200(自定义label)'}, // (10, 200]
/// {value: 123, label: '123(自定义特殊颜色)', color: 'grey'}, // [123, 123]
/// {lt: 5} // (-Infinity, 5)
/// ]
/// 注意,如果两个 piece 的区间重叠,则会自动进行去重。
/// 在每个 piece 中支持的 visualMap 属性有:
/// - symbol: 图元的图形类别。
/// - symbolSize: 图元的大小。
/// - color: 图元的颜色。
/// - colorAlpha: 图元的颜色的透明度。
/// - opacity: 图元以及其附属物(如文字标签)的透明度。
/// - colorLightness: 颜色的明暗度,参见 HSL。
/// - colorSaturation: 颜色的饱和度,参见 HSL。
/// - colorHue: 颜色的色调,参见 HSL。
///
/// 参见示例 : http://echarts.baidu.com/gallery/editor.html?c=doc-example/map-visualMap-pieces&edit=1&reset=1
///
/// (注:在 ECharts2 中,pieces 叫做 splitList。现在后者仍兼容,但推荐使用 pieces)
/// pieces 中的顺序,其实试试就知道。若要看详细的规则,参见 visualMap.inverse。
public var pieces: [Jsonable]?
// public var categories: []
/// 指定 visualMapPiecewise 组件的最小值。
/// 在 连续型数据自定义分段 模式(即 visualMap-piecewise.pieces 被使用)或 离散数据根据类别分段 模式(即 visualMap-piecewise.categories 被使用)时,max 和 min 不需指定。
/// 在 连续型数据平均分段 模式(即 (that is, when visualMap-piecewise.splitNumber 被使用时)需指定 min、max,如果不指定,则默认为 [0, 200](注意并不是默认为 series.data 的 dataMin 和 dataMax)。
public var min: Float?
/// 指定 visualMapPiecewise 组件的最大值。参见 visualMap-piecewise.splitNumber
/// 连续型数据自定义分段 模式(即 visualMap-piecewise.pieces 被使用)或 离散数据根据类别分段 模式(即 visualMap-piecewise.categories 被使用),max 和 min 不需指定。
/// 连续型数据平均分段 模式(即 (that is, when visualMap-piecewise.splitNumber 被使用时)需指定 min、max,如果不指定,则默认为 [0, 200](注意并不是默认为 series.data 的 dataMin 和 dataMax)。
public var max: Float?
/// 当 type 为 piecewise 且使用 min/max/splitNumber 时,此参数有效。当值为 true 时,界面上会额外多出一个『< min』的选块。
public var minOpen: Bool?
/// 当 type 为 piecewise 且使用 min/max/splitNumber 时,此参数有效。当值为 true 时,界面上会额外多出一个『> max』的选块。
public var maxOpen: Bool?
/// 选择模式,可以是:
/// - 'multiple'(多选)。
/// - 'single'(单选)。
public var selectedMode: SelectedMode?
/// 是否反转。
/// - 连续型数据平均分段 模式(即 (that is, when visualMap-piecewise.splitNumber 被使用时),数据排布规则,同 visualMap-continuous.inverse。
/// - 连续型数据自定义分段 模式(即 visualMap-piecewise.pieces 被使用)或 离散数据根据类别分段 模式(即 visualMap-piecewise.categories 被使用),每个块的排布位置,取决于 pieces 或 categories 列表的定义顺序,即:
/// - 当inverse为false时:
/// - 当 visualMap.orient 为 'vertical' 时,pieces[0] 或 categories[0]对应『上方』
/// - 当 visualMap.orient 为 'horizontal' 时,pieces[0] 或 categories[0] 对应『左方』。
/// - 当 inverse 为 true 时,与上面相反。
///
/// 其实没有那么复杂,使用时候,试试就知道了。
public var inverse: Bool?
/// 数据展示的小数精度。
/// - 连续型数据平均分段 模式(即 (that is, when visualMap-piecewise.splitNumber 被使用时),精度根据数据自动适应。
/// - 连续型数据自定义分段 模式(即 visualMap-piecewise.pieces 被使用)或 离散数据根据类别分段 模式(即 visualMap-piecewise.categories 被使用),精度默认为0(没有小数)。
public var precision: UInt?
/// 图形的宽度,即每个小块的宽度。
public var itemWidth: Float?
/// 图形的高度,即每个小块的高度。
public var itemHeight: Float?
/// 指定组件中图形(比如小方块)和文字的摆放关系,可选值为:
/// - 'auto' 自动决定。
/// - 'left' 图形在左文字在右。
/// - 'right' 图形在右文字在左。
public var align: Align?
/// 两端的文本,如['High', 'Low']。
///
/// 参见例子 : http://echarts.baidu.com/gallery/editor.html?c=doc-example/map-visualMap-piecewise-text&edit=1&reset=1
///
/// text 中的顺序,其实试试就知道。若要看详细的规则,参见 visualMap.inverse。
/// 兼容 ECharts2,当有 text 时,label不显示。
public var text: PiecewiseText?
/// 两端文字主体之间的距离,单位为px。参见 visualMap-piecewise.text
public var textGap: Float?
/// 是否显示每项的文本标签。默认情况是,如果 visualMap-piecewise.text 被使用则不显示文本标签,否则显示。
public var showLabel: Bool?
/// 每两个图元之间的间隔距离,单位为px。
public var itemGap: Float?
/// 默认的图形。
public var itemSymbol: Symbol?
/// 是否显示 visualMap-piecewise 组件。如果设置为 false,不会显示,但是数据映射的功能还存在。
public var show: Bool?
/// 指定用数据的『哪个维度』,映射到视觉元素上。『数据』即 series.data。 可以把 series.data 理解成一个二维数组,例如:
///
/// [
/// [12, 23, 43],
/// [12, 23, 43],
/// [43, 545, 65],
/// [92, 23, 33]
/// ]
///
/// 其中每个列是一个维度,即 dimension。 例如 dimension 为 1 时,取第二列(即 23,23,545,23),映射到视觉元素上。
/// 默认取 data 中最后一个维度。
public var dimension: Float?
/// 指定取哪个系列的数据,即哪个系列的 series.data。
/// 默认取所有系列。
public var seriesIndex: [UInt8]?
/// 打开 hoverLink 功能时,鼠标悬浮到 visualMap 组件上时,鼠标位置对应的数值 在 图表中对应的图形元素,会高亮。
/// 反之,鼠标悬浮到图表中的图形元素上时,在 visualMap 组件的相应位置会有三角提示其所对应的数值。
public var hoverLink: Bool?
public var inRange: [String: Jsonable]?
public var outRange: [String: Jsonable]?
/// visualMap 组件中,控制器 的 inRange outOfRange 设置。如果没有这个 controller 设置,控制器 会使用外层的 inRange outOfRange 设置;如果有这个 controller 设置,则会采用这个设置。适用于一些控制器视觉效果需要特殊定制或调整的场景。
public var controller: VisualMapController?
/// 所有图形的 zlevel 值。
/// zlevel用于 Canvas 分层,不同zlevel值的图形会放置在不同的 Canvas 中,Canvas 分层是一种常见的优化手段。我们可以把一些图形变化频繁(例如有动画)的组件设置成一个单独的zlevel。需要注意的是过多的 Canvas 会引起内存开销的增大,在手机端上需要谨慎使用以防崩溃。
/// zlevel 大的 Canvas 会放在 zlevel 小的 Canvas 的上面。
public var zlevel: Float?
/// 组件的所有图形的z值。控制图形的前后顺序。z值小的图形会被z值大的图形覆盖。
/// z相比zlevel优先级更低,而且不会创建新的 Canvas。
public var z: Float?
/// visualMap 组件离容器左侧的距离。
public var left: Position?
/// visualMap 组件离容器上侧的距离。
public var top: Position?
/// visualMap 组件离容器右侧的距离。
public var right: Position?
/// visualMap 组件离容器下侧的距离。
public var bottom: Position?
/// 如何放置 visualMap 组件,水平('horizontal')或者竖直('vertical')。
public var orient: Orient?
/// visualMap-piecewise内边距,单位px,默认各方向内边距为5,接受数组分别设定上右下左边距。
/// 使用示例:
///
/// // 设置内边距为 5
/// padding: 5
/// // 设置上下的内边距为 5,左右的内边距为 10
/// padding: [5, 10]
/// // 分别设置四个方向的内边距
/// padding: [
/// 5, // 上
/// 10, // 右
/// 5, // 下
/// 10, // 左
/// ]
public var padding: Padding?
/// 背景色。
public var backgroundColor: Color?
/// 边框颜色。
public var borderColor: Color?
/// 边框线宽,单位px。
public var borderWidth: Float?
/// 这个配置项,是为了兼容 ECharts2 而存在,ECharts3 中已经不推荐使用。它的功能已经移到了 visualMap-piecewise.inRange 和 visualMap-piecewise.outOfRange 中。
/// 如果要使用,则须注意,color属性中的顺序是由数值 大 到 小,但是 visualMap-piecewise.inRange 或 visualMap-piecewise.outOfRange 中 color 的顺序,总是由数值 小 到 大。二者不一致。
public var color: Color?
/// 文字样式
public var textStyle: TextStyle?
/// 标签的格式化工具。
/// 如果为string,表示模板,例如:aaaa{value}bbbb{value2}。其中 {value} 和 {value2} 是当前的范围边界值。
///
/// 如果为 Function,表示回调函数,形如:
/// formatter: function (value, value2) {
/// return 'aaaa' + value + 'bbbb' + value2; // 范围标签显示内容。
/// }
public var formatter: Formatter?
}
extension PiecewiseVisualMap: Enumable {
public enum Enums {
case splitNumber(Int), pieces([Jsonable]), min(Float), max(Float), minOpen(Bool), maxOpen(Bool), selectedMode(SelectedMode), inverse(Bool), precision(UInt), itemWidth(Float), itemHeight(Float), align(Align), text(PiecewiseText), textGap(Float), showLabel(Bool), itemGap(Float), itemSymbol(Symbol), show(Bool), dimension(Float), seriesIndex([UInt8]), hoverLink(Bool), inRange([String: Jsonable]), outRange([String: Jsonable]), controller(VisualMapController), zlevel(Float), z(Float), left(Position), top(Position), right(Position), bottom(Position), orient(Orient), padding(Padding), backgroundColor(Color), borderColor(Color), borderWidth(Float), color(Color), textStyle(TextStyle), formatter(Formatter)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .splitNumber(splitNumber):
self.splitNumber = splitNumber
case let .pieces(pieces):
self.pieces = pieces
case let .min(min):
self.min = min
case let .max(max):
self.max = max
case let .minOpen(minOpen):
self.minOpen = minOpen
case let .maxOpen(maxOpen):
self.maxOpen = maxOpen
case let .selectedMode(selectedMode):
self.selectedMode = selectedMode
case let .inverse(inverse):
self.inverse = inverse
case let .precision(precision):
self.precision = precision
case let .itemWidth(itemWidth):
self.itemWidth = itemWidth
case let .itemHeight(itemHeight):
self.itemHeight = itemHeight
case let .align(align):
self.align = align
case let .text(text):
self.text = text
case let .textGap(textGap):
self.textGap = textGap
case let .showLabel(showLabel):
self.showLabel = showLabel
case let .itemGap(itemGap):
self.itemGap = itemGap
case let .itemSymbol(itemSymbol):
self.itemSymbol = itemSymbol
case let .show(show):
self.show = show
case let .dimension(dimension):
self.dimension = dimension
case let .seriesIndex(seriesIndex):
self.seriesIndex = seriesIndex
case let .hoverLink(hoverLink):
self.hoverLink = hoverLink
case let .inRange(inRange):
self.inRange = inRange
case let .outRange(outRange):
self.outRange = outRange
case let .controller(controller):
self.controller = controller
case let .zlevel(zlevel):
self.zlevel = zlevel
case let .z(z):
self.z = z
case let .left(left):
self.left = left
case let .top(top):
self.top = top
case let .right(right):
self.right = right
case let .bottom(bottom):
self.bottom = bottom
case let .orient(orient):
self.orient = orient
case let .padding(padding):
self.padding = padding
case let .backgroundColor(backgroundColor):
self.backgroundColor = backgroundColor
case let .borderColor(borderColor):
self.borderColor = borderColor
case let .borderWidth(borderWidth):
self.borderWidth = borderWidth
case let .color(color):
self.color = color
case let .textStyle(textStyle):
self.textStyle = textStyle
case let .formatter(formatter):
self.formatter = formatter
}
}
}
}
extension PiecewiseVisualMap: Mappable {
public func mapping(_ map: Mapper) {
map["type"] = type
map["splitNumber"] = splitNumber
map["pieces"] = pieces
map["min"] = min
map["max"] = max
map["minOpen"] = minOpen
map["maxOpen"] = maxOpen
map["selectedMode"] = selectedMode
map["inverse"] = inverse
map["precision"] = precision
map["itemWidth"] = itemWidth
map["itemHeight"] = itemHeight
map["align"] = align
map["text"] = text
map["textGap"] = textGap
map["showLabel"] = showLabel
map["itemGap"] = itemGap
map["itemSymbol"] = itemSymbol
map["show"] = show
map["dimension"] = dimension
map["seriesIndex"] = seriesIndex
map["hoverLink"] = hoverLink
map["inRange"] = inRange
map["outRange"] = outRange
map["controller"] = controller
map["zlevel"] = zlevel
map["z"] = z
map["left"] = left
map["top"] = top
map["right"] = right
map["bottom"] = bottom
map["orient"] = orient
map["padding"] = padding
map["backgroundColor"] = backgroundColor
map["borderColor"] = borderColor
map["borderWidth"] = borderWidth
map["color"] = color
map["textStyle"] = textStyle
map["formatter"] = formatter
}
}
|
mit
|
1256f9b4f1ed8cee8b3f31120f55f8ea
| 41.149068 | 712 | 0.58687 | 3.386228 | false | false | false | false |
timothypmiller/Autocomplete
|
Autocomplete/CitiesViewController.swift
|
1
|
6963
|
//
// CitiesViewController.swift
// Autocomplete
//
// Created by Timothy P Miller on 2/18/15.
// Copyright (c) 2015 Timothy P Miller. All rights reserved.
//
import UIKit
class CitiesViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet var clearButtonItem: UIBarButtonItem?
let autocompleteManager: AutocompleteManager
var searchString: String?
var list: Array<String>?
var listTitle: String
required init(coder aDecoder: NSCoder) {
autocompleteManager = AutocompleteManager()
// From file
autocompleteManager.loadDataFrom(name: "world_cities", type: "txt")
// From URL
// autocompleteManager.loadDataFromURL(name: "<Can alternatively read file from a URL>")
list = autocompleteManager.recentsListSorted
listTitle = "Recents"
searchString = ""
super.init(coder: aDecoder)!
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "City Finder"
clearButtonItem?.isEnabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView?) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 1 {
return listTitle
}
return ""
}
override func tableView(_ tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else if section == 1 {
if let rows = list?.count {
return rows
}
}
return 0
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = indexPath.section
let row = indexPath.row
if section == 0 && row == 0 {
let reuseIdentifier = "SearchCell"
let cell: SearchTableViewCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! SearchTableViewCell
cell.searchTextField.delegate = self
return cell
} else if section == 1 {
let reuseIdentifier = "NameCell"
let cell: NameTableViewCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! NameTableViewCell
if let name = list?[indexPath.row] {
cell.nameLabel.text = name
}
return cell
}
return UITableViewCell()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 1 {
if let newSearchString = list?[indexPath.row] {
searchString = newSearchString
autocompleteManager.addToRecents(searchString!)
print("Number of recents: \(autocompleteManager.recentsList.count)")
self.performSegue(withIdentifier: "CitiesWebSearch", sender: self)
}
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == 1 {
if autocompleteManager.recentsList == list! {
return true
}
}
return false
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if indexPath.section == 1 {
if editingStyle == UITableViewCellEditingStyle.delete {
if autocompleteManager.recentsList == list! {
autocompleteManager.removeRecent(indexPath.row)
list = autocompleteManager.recentsListSorted
self.tableView.reloadSections(IndexSet(integer: 1), with: UITableViewRowAnimation.fade)
if list!.isEmpty {
clearButtonItem?.isEnabled = false
clearButtonItem?.title = "Clear"
}
}
}
}
}
@IBAction func editingDidChange(_ sender: UITextField) {
listTitle = "Recents"
let autocompleteField: UITextField = sender
if autocompleteField.text!.isEmpty {
list = autocompleteManager.recentsListSorted
if !list!.isEmpty {
clearButtonItem?.isEnabled = true
clearButtonItem?.title = "Clear"
}
} else {
listTitle = "Cities"
clearButtonItem?.isEnabled = false
// There is no hidden property for this type of button
clearButtonItem?.title = ""
// Use the built in filtering to match starting text
list = autocompleteManager.updateListMatchPrefix(autocompleteField.text!)
// May also pass your own filter as a closure
// list = autocompleteManager.updateList({ $0.lowercaseString.hasPrefix(autocompleteField.text.lowercaseString) })
}
self.tableView.reloadSections(IndexSet(integer: 1), with: UITableViewRowAnimation.fade)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let newSearchString: String = list?.first {
searchString = newSearchString
autocompleteManager.addToRecents(searchString!)
self.performSegue(withIdentifier: "CitiesWebSearch", sender: self)
}
return true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("Searching for: \(searchString)")
let webViewController = segue.destination as! WebViewController
let searchComponents = searchString!.components(separatedBy: ",")
let city = searchComponents[0].trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let country = searchComponents[1].trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
// Format for Wikipedia and encode
let urlString = "https://en.wikipedia.org/wiki/"
var urlPath = urlString + city + ",_" + country
urlPath = urlPath.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
webViewController.urlPath = urlPath
}
@IBAction func clearRecents(_ sender: AnyObject) {
print("Clear recents")
autocompleteManager.clearRecents()
list = autocompleteManager.recentsListSorted
clearButtonItem!.isEnabled = false
self.tableView.reloadSections(IndexSet(integer: 1), with: UITableViewRowAnimation.fade)
}
}
|
mit
|
ee4d71b4c45aa7c15a3ad8b33eb72136
| 36.037234 | 146 | 0.618842 | 5.754545 | false | false | false | false |
shahmishal/swift
|
test/SILGen/capture_order.swift
|
1
|
6268
|
// RUN: %target-swift-emit-silgen %s -verify
/// We emit an invalid forward capture as an 'undef'; make sure
/// we cover the various possible cases.
public func captureBeforeDefLet(amount: Int) -> () -> Int {
func getter() -> Int { // expected-error {{closure captures 'modifiedAmount' before it is declared}}
return modifiedAmount // expected-note {{captured here}}
}
let closure = getter
let modifiedAmount = amount // expected-note{{captured value declared here}}
// FIXME: Bogus warning!
// expected-warning@-2 {{initialization of immutable value 'modifiedAmount' was never used; consider replacing with assignment to '_' or removing it}}
return closure
}
public func captureBeforeDefVar(amount: Int) -> () -> Int {
func incrementor() -> Int { // expected-error {{closure captures 'currentTotal' before it is declared}}
currentTotal += amount // expected-note {{captured here}}
return currentTotal
}
let closure = incrementor
var currentTotal = 0 // expected-note{{captured value declared here}}
// FIXME: Bogus warning!
// expected-warning@-2 {{variable 'currentTotal' was written to, but never read}}
currentTotal = 1
return closure
}
public func captureBeforeDefWeakVar(obj: AnyObject) -> () -> AnyObject? {
func getter() -> AnyObject? { // expected-error {{closure captures 'weakObj' before it is declared}}
return weakObj // expected-note {{captured here}}
}
let closure = getter
weak var weakObj: AnyObject? = obj // expected-note{{captured value declared here}}
// FIXME: Bogus warning!
// expected-warning@-2 {{variable 'weakObj' was written to, but never read}}
return closure
}
public func captureBeforeDefUnownedLet(obj: AnyObject) -> () -> AnyObject? {
func getter() -> AnyObject? { // expected-error {{closure captures 'unownedObj' before it is declared}}
return unownedObj // expected-note {{captured here}}
}
let closure = getter
unowned let unownedObj: AnyObject = obj // expected-note{{captured value declared here}}
// FIXME: Bogus warning!
// expected-warning@-2 {{immutable value 'unownedObj' was never used; consider replacing with '_' or removing it}}
return closure
}
public func captureBeforeDefUnownedVar(obj: AnyObject) -> () -> AnyObject? {
func getter() -> AnyObject? { // expected-error {{closure captures 'unownedObj' before it is declared}}
return unownedObj // expected-note {{captured here}}
}
let closure = getter
unowned var unownedObj: AnyObject = obj // expected-note{{captured value declared here}}
// FIXME: Bogus warning!
// expected-warning@-2 {{variable 'unownedObj' was never used; consider replacing with '_' or removing it}}
return closure
}
/// Examples of transitive capture
func pingpong() {
func ping() -> Int {
return pong()
}
func pong() -> Int {
return ping()
}
_ = ping()
}
func transitiveForwardCapture() {
func ping() -> Int { // expected-error {{closure captures 'x' before it is declared}}
return pong()
}
_ = ping()
var x = 1 // expected-note {{captured value declared here}}
func pong() -> Int {
x += 1 // expected-note {{captured here}}
return ping()
}
}
func transitiveForwardCapture2() {
func ping() -> Int { // expected-error {{closure captures 'x' before it is declared}}
_ = pong()
}
_ = ping()
var x = 1 // expected-note {{captured value declared here}}
func pong() -> Int {
_ = pung()
}
func pung() -> Int {
x += 1 // expected-note {{captured here}}
return ping()
}
}
func transitiveForwardCapture3() {
var y = 2
func ping() -> Int { // expected-error {{closure captures 'x' before it is declared}}
_ = pong()
}
_ = ping()
var x = 1 // expected-note {{captured value declared here}}
func pung() -> Int {
x += 1 // expected-note {{captured here}}
return ping()
}
func pong() -> Int {
y += 2
_ = pung()
}
}
func captureInClosure() {
let x = { (i: Int) in // expected-error {{closure captures 'currentTotal' before it is declared}}
currentTotal += i // expected-note {{captured here}}
}
var currentTotal = 0 // expected-note {{captured value declared here}}
// FIXME: Bogus warning!
// expected-warning@-2 {{initialization of variable 'currentTotal' was never used; consider replacing with assignment to '_' or removing it}}
_ = x
}
/// Regression tests
func sr3210_crash() {
defer { // expected-error {{'defer' block captures 'b' before it is declared}}
print("\(b)") // expected-note {{captured here}}
}
return
let b = 2 // expected-note {{captured value declared here}}
// expected-warning@-1 {{code after 'return' will never be executed}}
// FIXME: Bogus warning!
// expected-warning@-3 {{initialization of immutable value 'b' was never used; consider replacing with assignment to '_' or removing it}}
}
func sr3210() {
defer {
print("\(b)")
}
let b = 2
// FIXME: Bogus warning!
// expected-warning@-2 {{initialization of immutable value 'b' was never used; consider replacing with assignment to '_' or removing it}}
}
class SR4812 {
public func foo() {
let bar = { [weak self] in
// expected-error@-1 {{closure captures 'bar' before it is declared}}
// expected-note@-2 {{captured value declared here}}
// expected-warning@-3 {{variable 'self' was written to, but never read}}
bar2()
}
func bar2() {
bar() // expected-note {{captured here}}
}
bar()
}
}
func timeout(_ f: @escaping () -> Void) {
f()
}
func sr10687() {
timeout { // expected-error {{closure captures 'x' before it is declared}}
proc()
}
let x = 0 // expected-note {{captured value declared here}}
func proc() {
_ = x // expected-note {{captured here}}
}
}
class rdar40600800 {
func foo() {
let callback = { // expected-error {{closure captures 'callback' before it is declared}}
// expected-note@-1 {{captured value declared here}}
innerFunction()
}
func innerFunction() {
let closure = { // expected-note {{captured here}}
// FIXME: Bogus warning!
// expected-warning@-2 {{initialization of immutable value 'closure' was never used; consider replacing with assignment to '_' or removing it}}
callback()
}
}
}
}
|
apache-2.0
|
1ff782a49ad5cd392d80a9e709001877
| 30.029703 | 152 | 0.652361 | 3.994901 | false | false | false | false |
swift-lang/swift-k
|
tests/stdlib-v2/io/009-IO-serialization-CSV.swift
|
2
|
373
|
// This CSV business is just broken by design
import "stdlib.v2";
type file;
type struct {
string a;
int b;
float c;
boolean d;
}
struct s;
s.a = "a_string";
s.b = 1;
s.c = 2.1;
s.d = true;
file f;
f = write(s, format = "CSV");
struct t;
t = read(f, format = "CSV");
assertEqual(s.a, t.a);
assertEqual(s.b, t.b);
assertEqual(s.c, t.c);
assertEqual(s.d, t.d);
|
apache-2.0
|
092aa61164e56a96fcc7da6eaeb2118e
| 10.65625 | 45 | 0.600536 | 2.181287 | false | false | false | false |
lukejmann/FBLA2017
|
FBLA2017/GroupsTableViewController.swift
|
1
|
5164
|
//
// GroupsTableViewController.swift
// FBLA2017
//
// Created by Luke Mann on 5/6/17.
// Copyright © 2017 Luke Mann. All rights reserved.
//
import UIKit
import FirebaseDatabase
import ChameleonFramework
import Presentr
import FirebaseAuth
//View Controller to control the group selection view table
class GroupsTableViewController: UITableViewController {
var cells=[GroupsTableViewCell]()
var currentSelectedCell: GroupsTableViewCell?
var nameToUpload: String?
@IBOutlet weak var chooseButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
chooseButton.setTitleColor(UIColor.flatNavyBlueDark, for: .normal)
loadCells()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cells.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let sourceCell = cells[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for:indexPath) as! GroupsTableViewCell
cell.groupName = sourceCell.groupName
cell.groupPath = sourceCell.groupPath
cell.groupNameLabel.text = cell.groupName
cells[indexPath.row]=cell
return cells[indexPath.row]
}
func loadCells() {
let ref = FIRDatabase.database().reference().child("groups")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
let maxCells = snapshots.count
for snapshot in snapshots {
if let path = snapshot.key as? String, let name = snapshot.value as? String {
let cell = GroupsTableViewCell()
cell.groupPath = path
cell.groupName = name
self.cells.append(cell)
if self.cells.count >= maxCells {
self.refreshTable()
}
}
}
}
// ...
}) { (error) in
ErrorGenerator.presentError(view: self, type: "Groups", error: error)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = cells[indexPath.row]
cell.checkMark.isHidden = false
if cell != currentSelectedCell {
currentSelectedCell?.checkMark.isHidden = true
currentSelectedCell = cell
}}
func refreshTable() {
self.tableView.reloadData()
viewDidAppear(false)
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
@IBAction func chooseButtonPressed() {
if currentSelectedCell != nil {
currentUser.groupPath = (currentSelectedCell?.groupPath)!
currentUser.loadGroup()
let ref = FIRDatabase.database().reference().child(currentGroup).child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("displayName")
ref.setValue(nameToUpload)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "MainView")
UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false, completion: nil)
UIApplication.shared.keyWindow?.rootViewController = viewController
}
}
}
extension GroupsTableViewController:MakeGroupDelegate {
func toMainView() {
if let nameToUpload = nameToUpload {
let ref = FIRDatabase.database().reference().child(currentGroup).child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("displayName")
ref.setValue(nameToUpload)
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "MainView")
UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false, completion: nil)
UIApplication.shared.keyWindow?.rootViewController = viewController
}
@IBAction func addGroupButtonPressed(_ sender: Any) {
let width = ModalSize.fluid(percentage: 0.7)
let height = ModalSize.fluid(percentage: 0.3)
let center = ModalCenterPosition.center
let presentationType = PresentationType.custom(width: width, height: height, center: center
)
let dynamicSizePresenter = Presentr(presentationType: presentationType)
let dynamicVC = storyboard!.instantiateViewController(withIdentifier: "MakeGroup") as! MakeGroupPopoverViewController
dynamicVC.delegate = self
customPresentViewController(dynamicSizePresenter, viewController: dynamicVC, animated: true, completion: nil)
}
}
|
mit
|
d767a6dd634b0e7aebbc0fd1e004ec0c
| 35.104895 | 155 | 0.645749 | 5.273749 | false | false | false | false |
Motsai/neblina-motiondemo-swift
|
src/GraphSegment.swift
|
4
|
2966
|
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A `UIView` subclass that represents a segment of data in a `GraphView`.
*/
import UIKit
import simd
class GraphSegment: UIView {
// MARK: Properties
static let capacity = 32
private(set) var dataPoints = [double3]()
private let startPoint: double3
private let valueRanges: [ClosedRange<Double>]
static let lineColors: [UIColor] = [.red, .green, .blue]
var gridLinePositions = [CGFloat]()
var isFull: Bool {
return dataPoints.count >= GraphSegment.capacity
}
// MARK: Initialization
init(startPoint: double3, valueRanges: [ClosedRange<Double>]) {
self.startPoint = startPoint
self.valueRanges = valueRanges
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func add(_ values: double3) {
guard dataPoints.count < GraphSegment.capacity else { return }
dataPoints.append(values)
setNeedsDisplay()
}
// MARK: UIView
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
// Fill the background.
if let backgroundColor = backgroundColor?.cgColor {
context.setFillColor(backgroundColor)
context.fill(rect)
}
// Draw static lines.
context.drawGraphLines(in: bounds.size)
// Plot lines for the 3 sets of values.
context.setShouldAntialias(false)
context.translateBy(x: 0, y: bounds.size.height / 2.0)
for lineIndex in 0..<3 {
context.setStrokeColor(GraphSegment.lineColors[lineIndex].cgColor)
// Move to the start point for the current line.
let value = startPoint[lineIndex]
let point = CGPoint(x: bounds.size.width, y: scaledValue(for: lineIndex, value: value))
context.move(to: point)
// Draw lines between the data points.
for (pointIndex, dataPoint) in dataPoints.enumerated() {
let value = dataPoint[lineIndex]
let point = CGPoint(x: bounds.size.width - CGFloat(pointIndex + 1), y: scaledValue(for: lineIndex, value: value))
context.addLine(to: point)
}
context.strokePath()
}
}
private func scaledValue(for lineIndex: Int, value: Double) -> CGFloat {
// For simplicity, this assumes the range is centered on zero.
let valueRange = valueRanges[lineIndex]
let scale = Double(bounds.size.height) / (valueRange.upperBound - valueRange.lowerBound)
return CGFloat(floor(value * -scale))
}
}
|
mit
|
087f00db76f4fae6add6c6b49e8a794c
| 29.875 | 129 | 0.59919 | 4.811688 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.