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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
meninsilicium/apple-swifty | Pair.swift | 1 | 2204 | //
// author: fabrice truillot de chambrier
// created: 19.01.2015
//
// license: see license.txt
//
// © 2014-2015, men in silicium sàrl
//
// MARK: - Pair
public struct Pair<T> {
private let left: T
private let right: T
// MARK: initialization
public init( _ value: T ) {
self.left = value
self.right = value
}
public init( left: T, right: T ) {
self.left = left
self.right = right
}
public init( tuple: (T, T) ) {
( self.left, self.right ) = tuple
}
public func tuple() -> (T, T) {
return (self.left, self.right)
}
}
// Iterable
extension Pair : Iterable {
public func foreach( @noescape function: (T) -> Void ) {
function( self.left )
function( self.right )
}
public func foreach( @noescape function: (Int, T) -> Void ) {
function( 0, self.left )
function( 1, self.right )
}
}
// Functor
extension Pair : Functor {
typealias MappedType = Any
typealias MappedFunctorType = Pair<MappedType>
public func map<R>( @noescape transform: (T) -> R ) -> Pair<R> {
return Pair<R>( left: transform( self.left ), right: transform( self.right ) )
}
}
public func <^><T, R>( pair: Pair<T>, @noescape transform: (T) -> R ) -> Pair<R> {
return pair.map( transform )
}
// Pointed
extension Pair : Pointed {
public static func pure( value: T ) -> Pair<T> {
return Pair<T>( value )
}
}
// Applicative
extension Pair : Applicative {
typealias ApplicativeType = Pair<(T) -> MappedType>
public static func apply<R>( transform: Pair<(T) -> R>, value: Pair<T> ) -> Pair<R> {
return Pair<R>( left: transform.left( value.left ), right: transform.right( value.right ) )
}
}
/*
func <*><T, R>( transform: Pair<(T) -> R>, value: Pair<T> ) -> Pair<R> {
return Pair.apply( transform, value: value )
}
*/
// Monad
extension Pair : Monad {
public func fmap<R>( @noescape transform: (T) -> Pair<R> ) -> Pair<R> {
return Pair<R>.flatten( self.map( transform ) )
}
public static func flatten( pair: Pair<Pair<T>> ) -> Pair<T> {
return Pair<T>( left: pair.left.left, right: pair.right.right )
}
}
/*
public func >>-<T, R>( value: Pair<T>, transform: (T) -> Pair<R> ) -> Pair<R> {
return value.fmap( transform )
}
*/
| mpl-2.0 | 18cc3c1b003327258ab1d9009f1d04e9 | 17.198347 | 93 | 0.612625 | 2.848642 | false | false | false | false |
PureSwift/Bluetooth | Sources/Bluetooth/UInt512.swift | 1 | 12524 | //
// UInt512.swift
// Bluetooth
//
// Created by Marco Estrella on 4/21/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// A 512 bit number stored according to host endianness.
@frozen
public struct UInt512: ByteValue {
public typealias ByteValue = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
public static var bitWidth: Int { return 512 }
public var bytes: ByteValue
public init(bytes: ByteValue = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) {
self.bytes = bytes
}
}
public extension UInt512 {
/// The minimum representable value in this type.
static var min: UInt512 { return UInt512(bytes: (.min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min, .min)) }
/// The maximum representable value in this type.
static var max: UInt512 { return UInt512(bytes: (.max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max, .max)) }
/// The value with all bits set to zero.
static var zero: UInt512 { return .min }
}
// MARK: - Equatable
extension UInt512: Equatable {
public static func == (lhs: UInt512, rhs: UInt512) -> Bool {
return lhs.bytes.0 == rhs.bytes.0 && lhs.bytes.1 == rhs.bytes.1 &&
lhs.bytes.2 == rhs.bytes.2 && lhs.bytes.3 == rhs.bytes.3 &&
lhs.bytes.4 == rhs.bytes.4 && lhs.bytes.5 == rhs.bytes.5 &&
lhs.bytes.6 == rhs.bytes.6 && lhs.bytes.7 == rhs.bytes.7 &&
lhs.bytes.8 == rhs.bytes.8 && lhs.bytes.9 == rhs.bytes.9 &&
lhs.bytes.10 == rhs.bytes.10 && lhs.bytes.11 == rhs.bytes.11 &&
lhs.bytes.12 == rhs.bytes.12 && lhs.bytes.13 == rhs.bytes.13 &&
lhs.bytes.14 == rhs.bytes.14 && lhs.bytes.15 == rhs.bytes.15 &&
lhs.bytes.16 == rhs.bytes.16 && lhs.bytes.17 == rhs.bytes.17 &&
lhs.bytes.18 == rhs.bytes.18 && lhs.bytes.19 == rhs.bytes.19 &&
lhs.bytes.20 == rhs.bytes.20 && lhs.bytes.21 == rhs.bytes.21 &&
lhs.bytes.22 == rhs.bytes.22 && lhs.bytes.23 == rhs.bytes.23 &&
lhs.bytes.24 == rhs.bytes.24 && lhs.bytes.25 == rhs.bytes.25 &&
lhs.bytes.26 == rhs.bytes.26 && lhs.bytes.27 == rhs.bytes.27 &&
lhs.bytes.28 == rhs.bytes.28 && lhs.bytes.29 == rhs.bytes.29 &&
lhs.bytes.30 == rhs.bytes.30 && lhs.bytes.31 == rhs.bytes.31 &&
lhs.bytes.32 == rhs.bytes.32 && lhs.bytes.33 == rhs.bytes.33 &&
lhs.bytes.34 == rhs.bytes.34 && lhs.bytes.35 == rhs.bytes.35 &&
lhs.bytes.36 == rhs.bytes.36 && lhs.bytes.37 == rhs.bytes.37 &&
lhs.bytes.38 == rhs.bytes.38 && lhs.bytes.39 == rhs.bytes.39 &&
lhs.bytes.40 == rhs.bytes.40 && lhs.bytes.41 == rhs.bytes.41 &&
lhs.bytes.42 == rhs.bytes.42 && lhs.bytes.43 == rhs.bytes.43 &&
lhs.bytes.44 == rhs.bytes.44 && lhs.bytes.45 == rhs.bytes.45 &&
lhs.bytes.46 == rhs.bytes.46 && lhs.bytes.47 == rhs.bytes.47 &&
lhs.bytes.48 == rhs.bytes.48 && lhs.bytes.49 == rhs.bytes.49 &&
lhs.bytes.50 == rhs.bytes.50 && lhs.bytes.51 == rhs.bytes.51 &&
lhs.bytes.52 == rhs.bytes.52 && lhs.bytes.53 == rhs.bytes.53 &&
lhs.bytes.54 == rhs.bytes.54 && lhs.bytes.55 == rhs.bytes.55 &&
lhs.bytes.56 == rhs.bytes.56 && lhs.bytes.57 == rhs.bytes.57 &&
lhs.bytes.58 == rhs.bytes.58 && lhs.bytes.59 == rhs.bytes.59 &&
lhs.bytes.60 == rhs.bytes.60 && lhs.bytes.61 == rhs.bytes.61 &&
lhs.bytes.62 == rhs.bytes.62 && lhs.bytes.63 == rhs.bytes.63
}
}
// MARK: - Hashable
extension UInt512: Hashable {
public func hash(into hasher: inout Hasher) {
withUnsafeBytes(of: bytes) { hasher.combine(bytes: $0) }
}
}
// MARK: - CustomStringConvertible
extension UInt512: CustomStringConvertible {
public var description: String {
let bytes = self.bigEndian.bytes
return bytes.0.toHexadecimal()
+ bytes.1.toHexadecimal()
+ bytes.2.toHexadecimal()
+ bytes.3.toHexadecimal()
+ bytes.4.toHexadecimal()
+ bytes.5.toHexadecimal()
+ bytes.6.toHexadecimal()
+ bytes.7.toHexadecimal()
+ bytes.8.toHexadecimal()
+ bytes.9.toHexadecimal()
+ bytes.10.toHexadecimal()
+ bytes.11.toHexadecimal()
+ bytes.12.toHexadecimal()
+ bytes.13.toHexadecimal()
+ bytes.14.toHexadecimal()
+ bytes.15.toHexadecimal()
+ bytes.16.toHexadecimal()
+ bytes.17.toHexadecimal()
+ bytes.18.toHexadecimal()
+ bytes.19.toHexadecimal()
+ bytes.20.toHexadecimal()
+ bytes.21.toHexadecimal()
+ bytes.22.toHexadecimal()
+ bytes.23.toHexadecimal()
+ bytes.24.toHexadecimal()
+ bytes.25.toHexadecimal()
+ bytes.26.toHexadecimal()
+ bytes.27.toHexadecimal()
+ bytes.28.toHexadecimal()
+ bytes.29.toHexadecimal()
+ bytes.30.toHexadecimal()
+ bytes.31.toHexadecimal()
+ bytes.32.toHexadecimal()
+ bytes.33.toHexadecimal()
+ bytes.34.toHexadecimal()
+ bytes.35.toHexadecimal()
+ bytes.36.toHexadecimal()
+ bytes.37.toHexadecimal()
+ bytes.38.toHexadecimal()
+ bytes.39.toHexadecimal()
+ bytes.40.toHexadecimal()
+ bytes.41.toHexadecimal()
+ bytes.42.toHexadecimal()
+ bytes.43.toHexadecimal()
+ bytes.44.toHexadecimal()
+ bytes.45.toHexadecimal()
+ bytes.46.toHexadecimal()
+ bytes.47.toHexadecimal()
+ bytes.48.toHexadecimal()
+ bytes.49.toHexadecimal()
+ bytes.50.toHexadecimal()
+ bytes.51.toHexadecimal()
+ bytes.52.toHexadecimal()
+ bytes.53.toHexadecimal()
+ bytes.54.toHexadecimal()
+ bytes.55.toHexadecimal()
+ bytes.56.toHexadecimal()
+ bytes.57.toHexadecimal()
+ bytes.58.toHexadecimal()
+ bytes.59.toHexadecimal()
+ bytes.60.toHexadecimal()
+ bytes.61.toHexadecimal()
+ bytes.62.toHexadecimal()
+ bytes.63.toHexadecimal()
}
}
// MARK: - Data Convertible
public extension UInt512 {
static var length: Int { return 64 }
init?(data: Data) {
guard data.count == UInt128.length else { return nil }
self.init(bytes: (data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16], data[17], data[18], data[19], data[20], data[21], data[22], data[23], data[24], data[25], data[26], data[27], data[28], data[29], data[30], data[31], data[32], data[33], data[34], data[35], data[36], data[37], data[38], data[39], data[40], data[41], data[42], data[43], data[44], data[45], data[46], data[47], data[48], data[49], data[50], data[51], data[52], data[53], data[54], data[55], data[56], data[57], data[58], data[59], data[60], data[61], data[62], data[63]))
}
var data: Data {
return Data([bytes.0, bytes.1, bytes.2, bytes.3, bytes.4, bytes.5, bytes.6, bytes.7, bytes.8, bytes.9, bytes.10, bytes.11, bytes.12, bytes.13, bytes.14, bytes.15, bytes.16, bytes.17, bytes.18, bytes.19, bytes.20, bytes.21, bytes.22, bytes.23, bytes.24, bytes.25, bytes.26, bytes.27, bytes.28, bytes.29, bytes.30, bytes.31, bytes.32, bytes.33, bytes.34, bytes.35, bytes.36, bytes.37, bytes.38, bytes.39, bytes.40, bytes.41, bytes.42, bytes.43, bytes.44, bytes.45, bytes.46, bytes.47, bytes.48, bytes.49, bytes.50, bytes.51, bytes.52, bytes.53, bytes.54, bytes.55, bytes.56, bytes.57, bytes.58, bytes.59, bytes.60, bytes.61, bytes.62, bytes.63])
}
}
// MARK: - Byte Swap
extension UInt512: ByteSwap {
/// A representation of this integer with the byte order swapped.
public var byteSwapped: UInt512 {
return UInt512(bytes: (bytes.63,
bytes.62,
bytes.61,
bytes.60,
bytes.59,
bytes.58,
bytes.57,
bytes.56,
bytes.55,
bytes.54,
bytes.53,
bytes.52,
bytes.51,
bytes.50,
bytes.49,
bytes.48,
bytes.47,
bytes.46,
bytes.45,
bytes.44,
bytes.43,
bytes.42,
bytes.41,
bytes.40,
bytes.39,
bytes.38,
bytes.37,
bytes.36,
bytes.35,
bytes.34,
bytes.33,
bytes.32,
bytes.31,
bytes.30,
bytes.29,
bytes.28,
bytes.27,
bytes.26,
bytes.25,
bytes.24,
bytes.23,
bytes.22,
bytes.21,
bytes.20,
bytes.19,
bytes.18,
bytes.17,
bytes.16,
bytes.15,
bytes.14,
bytes.13,
bytes.12,
bytes.11,
bytes.10,
bytes.9,
bytes.8,
bytes.7,
bytes.6,
bytes.5,
bytes.4,
bytes.3,
bytes.2,
bytes.1,
bytes.0))
}
}
// MARK: - ExpressibleByIntegerLiteral
extension UInt512: ExpressibleByIntegerLiteral {
public init(integerLiteral value: UInt64) {
let bytes = value.bigEndian.bytes
self = UInt512(bigEndian: UInt512(bytes: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, bytes.0, bytes.1, bytes.2, bytes.3, bytes.4, bytes.5, bytes.6, bytes.7)))
}
}
| mit | 606f1f48b37ccc66a39981cd540840b3 | 45.902622 | 656 | 0.475685 | 3.523635 | false | false | false | false |
mirego/taylor-ios | Taylor/Date/NSDate.swift | 1 | 4303 | // Copyright (c) 2016, Mirego
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// - Neither the name of the Mirego nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import UIKit
public extension Date
{
/**
Returns true if the date mathches the specified date's day.
- parameter anotherDate: The second date.
- returns: Returns true if the date mathches the specified date's day
*/
func isSameDay(_ anotherDate: Date) -> Bool
{
return isEqual(to: anotherDate, unitGranularity: .day)
}
/**
Returns true if the date is equal to the specified date using the specified NSCalendarUnit.
- parameter to: The comparison other date.
- parameter unitGranularity: Optional NSCalendarUnit. Default is Second.
- returns: Returns true if the date is equal to the specified date using the specified NSCalendarUnit
*/
func isEqual(to toDate: Date, unitGranularity: NSCalendar.Unit = .second) -> Bool
{
return (Calendar.current as NSCalendar).compare(self, to: toDate, toUnitGranularity: unitGranularity) == ComparisonResult.orderedSame
}
/**
Returns true if the date is earlier than the specified date using the specified NSCalendarUnit.
- parameter than: The comparison other date.
- parameter unitGranularity: Optional NSCalendarUnit. Default is Second.
- returns: Returns true if the date is earlier than the specified date using the specified NSCalendarUnit
*/
func isEarlier(than thanDate: Date, unitGranularity: NSCalendar.Unit = .second) -> Bool
{
return (Calendar.current as NSCalendar).compare(self, to: thanDate, toUnitGranularity: unitGranularity) == ComparisonResult.orderedAscending
}
/**
Returns true if the date is later than the specified date using the specified NSCalendarUnit.
- parameter than: The comparison other date.
- parameter unitGranularity: Optional NSCalendarUnit. Default is Second.
- returns: Returns true if the date is later than the specified date using the specified NSCalendarUnit
*/
func isLater(than thanDate: Date, unitGranularity: NSCalendar.Unit = .second) -> Bool
{
return (Calendar.current as NSCalendar).compare(self, to: thanDate, toUnitGranularity: unitGranularity) == ComparisonResult.orderedDescending
}
func daysBetween(toDate: Date) -> Int
{
let components = (Calendar.current as NSCalendar).components(.day, from: self, to: toDate, options: [])
return components.day!
}
func addDaysToDate(_ daysToAdd: Int) -> Date
{
return (Calendar.current as NSCalendar).date(byAdding: .day, value: daysToAdd, to: self, options: [])!
}
func getWeekDay() -> Int
{
let components = (Calendar.current as NSCalendar).components(.weekday, from: self)
return components.weekday!
}
}
| bsd-3-clause | 9d118b02c694714ebde634f44fc1380b | 42.464646 | 149 | 0.718568 | 4.867647 | false | false | false | false |
Appsaurus/Infinity | Infinity/controls/spark/SparkInfinityAnimator.swift | 1 | 3908 | //
// SparkInfiniteAnimator.swift
// InfiniteSample
//
// Created by Danis on 16/1/2.
// Copyright © 2016年 danis. All rights reserved.
//
import UIKit
open class SparkInfiniteAnimator: UIView, CustomInfiniteScrollAnimator {
fileprivate var circles = [CAShapeLayer]()
var animating = false
fileprivate var positions = [CGPoint]()
public override init(frame: CGRect) {
super.init(frame: frame)
let ovalDiameter = min(frame.width,frame.height) / 8
let ovalPath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: ovalDiameter, height: ovalDiameter))
let count = 8
for index in 0..<count {
let circleLayer = CAShapeLayer()
circleLayer.path = ovalPath.cgPath
circleLayer.fillColor = UIColor.sparkColorWithIndex(index).cgColor
circleLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.circles.append(circleLayer)
self.layer.addSublayer(circleLayer)
let angle = CGFloat(M_PI * 2) / CGFloat(count) * CGFloat(index)
let radius = min(frame.width, frame.height) * 0.4
let position = CGPoint(x: bounds.midX + sin(angle) * radius, y: bounds.midY - cos(angle) * radius)
circleLayer.position = position
positions.append(position)
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil && animating {
startAnimating()
}
}
open func animateState(_ state: InfiniteScrollState) {
switch state {
case .none:
stopAnimating()
case .loading:
startAnimating()
}
}
func startAnimating() {
animating = true
for index in 0..<8 {
applyAnimationForIndex(index)
}
}
fileprivate let CircleAnimationKey = "CircleAnimationKey"
fileprivate func applyAnimationForIndex(_ index: Int) {
let moveAnimation = CAKeyframeAnimation(keyPath: "position")
let moveV1 = NSValue(cgPoint: positions[index])
let moveV2 = NSValue(cgPoint: CGPoint(x: bounds.midX, y: bounds.midY))
let moveV3 = NSValue(cgPoint: positions[index])
moveAnimation.values = [moveV1,moveV2,moveV3]
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform")
let scaleV1 = NSValue(caTransform3D: CATransform3DIdentity)
let scaleV2 = NSValue(caTransform3D: CATransform3DMakeScale(0.1, 0.1, 1.0))
let scaleV3 = NSValue(caTransform3D: CATransform3DIdentity)
scaleAnimation.values = [scaleV1,scaleV2,scaleV3]
let animationGroup = CAAnimationGroup()
animationGroup.animations = [moveAnimation,scaleAnimation]
animationGroup.duration = 1.0
animationGroup.repeatCount = 1000
animationGroup.beginTime = CACurrentMediaTime() + Double(index) * animationGroup.duration / 8 / 2
animationGroup.timingFunction = CAMediaTimingFunction(controlPoints: 1, 0.5, 0, 0.5)
let circleLayer = circles[index]
circleLayer.isHidden = false
circleLayer.add(animationGroup, forKey: CircleAnimationKey)
}
func stopAnimating() {
for circleLayer in circles {
circleLayer.removeAnimation(forKey: CircleAnimationKey)
circleLayer.transform = CATransform3DIdentity
circleLayer.isHidden = true
}
animating = false
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| mit | 9e0fb26b3f421a59e660e7a083598b6e | 34.5 | 110 | 0.623816 | 4.797297 | false | false | false | false |
audiokit/AudioKit | Tests/AudioKitTests/Node Tests/NodeTests.swift | 1 | 11098 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
@testable import AudioKit
import AVFoundation
import CAudioKit
import XCTest
class NodeTests: XCTestCase {
func testNodeBasic() {
let engine = AudioEngine()
let osc = Oscillator()
XCTAssertNotNil(osc.avAudioUnit)
XCTAssertNil(osc.avAudioNode.engine)
osc.start()
engine.output = osc
XCTAssertNotNil(osc.avAudioNode.engine)
let audio = engine.startTest(totalDuration: 0.1)
audio.append(engine.render(duration: 0.1))
testMD5(audio)
}
func testNodeConnection() {
let engine = AudioEngine()
let osc = Oscillator()
osc.start()
let verb = CostelloReverb(osc)
engine.output = verb
let audio = engine.startTest(totalDuration: 0.1)
audio.append(engine.render(duration: 0.1))
testMD5(audio)
}
func testRedundantConnection() {
let osc = Oscillator()
let mixer = Mixer()
mixer.addInput(osc)
mixer.addInput(osc)
XCTAssertEqual(mixer.connections.count, 1)
}
func testDynamicOutput() {
let engine = AudioEngine()
let osc1 = Oscillator()
osc1.start()
engine.output = osc1
let audio = engine.startTest(totalDuration: 2.0)
let newAudio = engine.render(duration: 1.0)
audio.append(newAudio)
let osc2 = Oscillator(frequency: 880)
osc2.start()
engine.output = osc2
let newAudio2 = engine.render(duration: 1.0)
audio.append(newAudio2)
testMD5(audio)
}
func testDynamicConnection() {
let engine = AudioEngine()
let osc = Oscillator()
let mixer = Mixer(osc)
XCTAssertNil(osc.avAudioNode.engine)
engine.output = mixer
// Osc should be attached.
XCTAssertNotNil(osc.avAudioNode.engine)
let audio = engine.startTest(totalDuration: 2.0)
osc.start()
audio.append(engine.render(duration: 1.0))
let osc2 = Oscillator(frequency: 880)
osc2.start()
mixer.addInput(osc2)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testDynamicConnection2() {
let engine = AudioEngine()
let osc = Oscillator()
let mixer = Mixer(osc)
engine.output = mixer
osc.start()
let audio = engine.startTest(totalDuration: 2.0)
audio.append(engine.render(duration: 1.0))
let osc2 = Oscillator(frequency: 880)
let verb = CostelloReverb(osc2)
osc2.start()
mixer.addInput(verb)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testDynamicConnection3() {
let engine = AudioEngine()
let osc = Oscillator()
let mixer = Mixer(osc)
engine.output = mixer
osc.start()
let audio = engine.startTest(totalDuration: 3.0)
audio.append(engine.render(duration: 1.0))
let osc2 = Oscillator(frequency: 880)
osc2.start()
mixer.addInput(osc2)
audio.append(engine.render(duration: 1.0))
mixer.removeInput(osc2)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testDynamicConnection4() {
let engine = AudioEngine()
let outputMixer = Mixer()
let osc = Oscillator()
outputMixer.addInput(osc)
engine.output = outputMixer
let audio = engine.startTest(totalDuration: 2.0)
osc.start()
audio.append(engine.render(duration: 1.0))
let osc2 = Oscillator()
osc2.frequency = 880
let localMixer = Mixer()
localMixer.addInput(osc2)
outputMixer.addInput(localMixer)
osc2.start()
audio.append(engine.render(duration: 1.0))
// testMD5(audio)
}
func testDynamicConnection5() {
let engine = AudioEngine()
let outputMixer = Mixer()
engine.output = outputMixer
let audio = engine.startTest(totalDuration: 1.0)
let osc = Oscillator()
let mixer = Mixer()
mixer.addInput(osc)
outputMixer.addInput(mixer) // change mixer to osc and this will play
osc.start()
audio.append(engine.render(duration: 1.0))
// testMD5(audio)
}
func testDisconnect() {
let engine = AudioEngine()
let osc = Oscillator()
let mixer = Mixer(osc)
engine.output = mixer
let audio = engine.startTest(totalDuration: 2.0)
osc.start()
audio.append(engine.render(duration: 1.0))
mixer.removeInput(osc)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testNodeDetach() {
let engine = AudioEngine()
let osc = Oscillator()
let mixer = Mixer(osc)
engine.output = mixer
osc.start()
let audio = engine.startTest(totalDuration: 2.0)
audio.append(engine.render(duration: 1.0))
osc.detach()
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testTwoEngines() {
let engine = AudioEngine()
let engine2 = AudioEngine()
let osc = Oscillator()
engine2.output = osc
osc.start()
let verb = CostelloReverb(osc)
engine.output = verb
let audio = engine.startTest(totalDuration: 0.1)
audio.append(engine.render(duration: 0.1))
testMD5(audio)
}
func testManyMixerConnections() {
let engine = AudioEngine()
var oscs: [Oscillator] = []
for _ in 0 ..< 16 {
oscs.append(Oscillator())
}
let mixer = Mixer(oscs)
engine.output = mixer
XCTAssertEqual(mixer.avAudioNode.numberOfInputs, 16)
}
func connectionCount(node: AVAudioNode) -> Int {
var count = 0
for bus in 0 ..< node.numberOfInputs {
if let inputConnection = node.engine!.inputConnectionPoint(for: node, inputBus: bus) {
if inputConnection.node != nil {
count += 1
}
}
}
return count
}
func testFanout() {
let engine = AudioEngine()
let osc = Oscillator()
let verb = CostelloReverb(osc)
let mixer = Mixer(osc, verb)
engine.output = mixer
XCTAssertEqual(connectionCount(node: verb.avAudioNode), 1)
XCTAssertEqual(connectionCount(node: mixer.avAudioNode), 2)
}
func testMixerRedundantUpstreamConnection() {
let engine = AudioEngine()
let osc = Oscillator()
let mixer1 = Mixer(osc)
let mixer2 = Mixer(mixer1)
engine.output = mixer2
XCTAssertEqual(connectionCount(node: mixer1.avAudioNode), 1)
mixer2.addInput(osc)
XCTAssertEqual(connectionCount(node: mixer1.avAudioNode), 1)
}
func testTransientNodes() {
let engine = AudioEngine()
let osc = Oscillator()
func exampleStart() {
let env = AmplitudeEnvelope(osc)
osc.amplitude = 1
engine.output = env
osc.start()
try! engine.start()
sleep(1)
}
func exampleStop() {
osc.stop()
engine.stop()
sleep(1)
}
exampleStart()
exampleStop()
exampleStart()
exampleStop()
exampleStart()
exampleStop()
}
func testAutomationAfterDelayedConnection() {
let engine = AudioEngine()
let osc = Oscillator()
let osc2 = Oscillator()
let mixer = Mixer()
let events = [AutomationEvent(targetValue: 1320, startTime: 0.0, rampDuration: 0.5)]
engine.output = mixer
mixer.addInput(osc)
let audio = engine.startTest(totalDuration: 2.0)
osc.play()
osc.$frequency.automate(events: events)
audio.append(engine.render(duration: 1.0))
mixer.removeInput(osc)
mixer.addInput(osc2)
osc2.play()
osc2.$frequency.automate(events: events)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
// This provides a baseline for measuring the overhead
// of mixers in testMixerPerformance.
func testChainPerformance() {
let engine = AudioEngine()
let osc = Oscillator()
let rev = CostelloReverb(osc)
XCTAssertNotNil(osc.avAudioUnit)
XCTAssertNil(osc.avAudioNode.engine)
osc.start()
engine.output = rev
XCTAssertNotNil(osc.avAudioNode.engine)
measureMetrics([.wallClockTime], automaticallyStartMeasuring: false) {
let audio = engine.startTest(totalDuration: 10.0)
startMeasuring()
let buf = engine.render(duration: 10.0)
stopMeasuring()
audio.append(buf)
}
}
// Measure the overhead of mixers.
func testMixerPerformance() {
let engine = AudioEngine()
let osc = Oscillator()
let mix1 = Mixer(osc)
let rev = CostelloReverb(mix1)
let mix2 = Mixer(rev)
XCTAssertNotNil(osc.avAudioUnit)
XCTAssertNil(osc.avAudioNode.engine)
osc.start()
engine.output = mix2
XCTAssertNotNil(osc.avAudioNode.engine)
measureMetrics([.wallClockTime], automaticallyStartMeasuring: false) {
let audio = engine.startTest(totalDuration: 10.0)
startMeasuring()
let buf = engine.render(duration: 10.0)
stopMeasuring()
audio.append(buf)
}
}
func testConnectionTreeDescriptionForStandaloneNode() {
let osc = Oscillator()
XCTAssertEqual(osc.connectionTreeDescription, "\(Node.connectionTreeLinePrefix)↳Oscillator")
}
func testConnectionTreeDescriptionForConnectedNode() {
let osc = Oscillator()
let verb = CostelloReverb(osc)
let mixer = Mixer(osc, verb)
let mixerAddress = MemoryAddress(of: mixer).description
XCTAssertEqual(mixer.connectionTreeDescription,
"""
\(Node.connectionTreeLinePrefix)↳Mixer("\(mixerAddress)")
\(Node.connectionTreeLinePrefix) ↳Oscillator
\(Node.connectionTreeLinePrefix) ↳CostelloReverb
\(Node.connectionTreeLinePrefix) ↳Oscillator
""")
}
func testConnectionTreeDescriptionForNamedNode() {
let nameString = "Customized Name"
let sampler = MIDISampler(name: nameString)
let compressor = Compressor(sampler)
let mixer = Mixer(compressor)
let mixerAddress = MemoryAddress(of: mixer).description
XCTAssertEqual(mixer.connectionTreeDescription,
"""
\(Node.connectionTreeLinePrefix)↳Mixer("\(mixerAddress)")
\(Node.connectionTreeLinePrefix) ↳Compressor
\(Node.connectionTreeLinePrefix) ↳MIDISampler("\(nameString)")
""")
}
}
| mit | 21c384ccc7ed583c9b4dae885951e983 | 25.511962 | 100 | 0.595921 | 4.41866 | false | true | false | false |
plivesey/SwiftGen | swiftgen-cli/strings.swift | 1 | 1124 | //
// SwiftGen
// Copyright (c) 2015 Olivier Halligon
// MIT Licence
//
import Commander
import PathKit
import GenumKit
let stringsCommand = command(
outputOption,
templateOption(prefix: "strings"), templatePathOption,
Option<String>("enumName", "L10n", flag: "e", description: "The name of the enum to generate"),
Argument<Path>("FILE", description: "Localizable.strings file to parse.", validator: fileExists)
) { output, templateName, templatePath, enumName, path in
let parser = StringsFileParser()
do {
try parser.parseFile(at: path)
let templateRealPath = try findTemplate(
prefix: "strings", templateShortName: templateName, templateFullPath: templatePath
)
let template = try GenumTemplate(templateString: templateRealPath.read(), environment: genumEnvironment())
let context = parser.stencilContext(enumName: enumName, tableName: path.lastComponentWithoutExtension)
let rendered = try template.render(context)
output.write(content: rendered, onlyIfChanged: true)
} catch let error as NSError {
printError(string: "error: \(error.localizedDescription)")
}
}
| mit | 4b8602f53b1e2a01c25137ec3a430e31 | 34.125 | 110 | 0.741103 | 4.442688 | false | false | false | false |
lbnp/italk2 | italk2/FirstViewController.swift | 1 | 2883 | //
// FirstViewController.swift
// italk2
//
// Created by Jun Kamoshima on 2015/07/12.
// Copyright (c) 2015 lbnp. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate, UIScrollViewDelegate {
var italk : Italk?
@IBAction func connectClicked(sender: UIButton) {
italk?.connect("main.italk.ne.jp", port: 12345)
}
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var logTextView: UITextView!
@IBOutlet weak var chatTextField: UITextField!
@IBAction func sendClicked(sender: AnyObject) {
sendText()
chatTextField.endEditing(true)
}
func sendText() {
let textToSend = chatTextField.text! + "\n"
logTextView.text = logTextView.text + textToSend
chatTextField.text = nil
chatTextField.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
scrollView.delegate = self
chatTextField.delegate = self
logTextView.delegate = self
logTextView.text = nil
italk = Italk()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeShown:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillBeShown(notification: NSNotification) {
let userInfo = notification.userInfo!
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let myBoundSize: CGSize = UIScreen.mainScreen().bounds.size
let textLimit = chatTextField.frame.origin.y + chatTextField.frame.height + 8.0
let keyboardLimit = myBoundSize.height - keyboardScreenEndFrame.size.height
if textLimit >= keyboardLimit {
scrollView.contentOffset.y = textLimit - keyboardLimit
}
}
func keyboardWillBeHidden(notification: NSNotification) {
scrollView.contentOffset.y = 0
}
}
| mit | 6d6cbe8b9b12b4848ed23f5f65683d6d | 35.961538 | 148 | 0.696844 | 5.084656 | false | false | false | false |
jduquennoy/Log4swift | Log4swiftTests/Formatters/PatternFormatterTests.swift | 1 | 29996 | //
// PatternFormatterTests.swift
// Log4swift
//
// Created by Jérôme Duquennoy on 19/06/2015.
// Copyright © 2015 Jérôme Duquennoy. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
@testable import Log4swift
class PatternFormatterTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testDefaultPatternForFormatterReturnsTheUnmodifiedMessage() {
// Execute
let formatter = PatternFormatter("identifier")
let message = "test message"
XCTAssertEqual(formatter.format(message: message, info: LogInfoDictionary()), message)
}
func testCreateFormatterWithNonClosedParametersThrowsError() {
XCTAssertThrows { let _ = try PatternFormatter(identifier:"testFormatter", pattern: "%d{ blablabla") }
}
func testFormatterAppliesLogLevelMarker() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%l")
// Execute
let formattedMessage = formatter.format(message: "", info: [LogInfoKeys.LogLevel: LogLevel.Error])
// validate
XCTAssertEqual(formattedMessage, LogLevel.Error.description)
}
func testFormatterAppliesLogLevelMarkerWithPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "[%l{\"padding\":\"10\"}][%n] %m")
let info: LogInfoDictionary = [
LogInfoKeys.LoggerName: "nameOfTheLogger",
LogInfoKeys.LogLevel: LogLevel.Warning
]
// Execute
let formattedMessage = formatter.format(message: "Log message", info: info)
// Validate
XCTAssertEqual(formattedMessage, "[\(LogLevel.Warning) ][nameOfTheLogger] Log message")
}
func testFormatterAppliesLogLevelMarkerWithNegativePadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "[%l{\"padding\":\"-10\"}][%n] %m")
let info: LogInfoDictionary = [
LogInfoKeys.LoggerName: "nameOfTheLogger",
LogInfoKeys.LogLevel: LogLevel.Warning
]
// Execute
let formattedMessage = formatter.format(message: "Log message", info: info)
// Validate
XCTAssertEqual(formattedMessage, "[ \(LogLevel.Warning)][nameOfTheLogger] Log message")
}
func testFormatterAppliesLogLevelMarkerWithZeroPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "[%l{\"padding\":\"0\"}][%n] %m")
let info: LogInfoDictionary = [
LogInfoKeys.LoggerName: "nameOfTheLogger",
LogInfoKeys.LogLevel: LogLevel.Warning
]
// Execute
let formattedMessage = formatter.format(message: "Log message", info: info)
// Validate
XCTAssertEqual(formattedMessage, "[\(LogLevel.Warning)][nameOfTheLogger] Log message")
}
func testFormatterAppliesLoggerNameMarker() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%n")
let info: LogInfoDictionary = [LogInfoKeys.LoggerName: "loggername"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "loggername")
}
func testFormatterAppliesLoggerNameWithPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "[%l][%n{\"padding\":\"10\"}] %m")
let info: LogInfoDictionary = [
LogInfoKeys.LoggerName: "name",
LogInfoKeys.LogLevel: LogLevel.Warning
]
// Execute
let formattedMessage = formatter.format(message: "Log message", info: info)
// Validate
XCTAssertEqual(formattedMessage, "[\(LogLevel.Warning)][name ] Log message")
}
func testFormatterAppliesLoggerNameWithNegativePadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "[%l][%n{\"padding\":\"-10\"}] %m")
let info: LogInfoDictionary = [
LogInfoKeys.LoggerName: "name",
LogInfoKeys.LogLevel: LogLevel.Warning
]
// Execute
let formattedMessage = formatter.format(message: "Log message", info: info)
// Validate
XCTAssertEqual(formattedMessage, "[\(LogLevel.Warning)][ name] Log message")
}
func testFormatterAppliesLoggerNameWithZeroPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "[%l][%n{\"padding\":\"0\"}] %m")
let info: LogInfoDictionary = [
LogInfoKeys.LoggerName: "name",
LogInfoKeys.LogLevel: LogLevel.Warning
]
// Execute
let formattedMessage = formatter.format(message: "Log message", info: info)
// Validate
XCTAssertEqual(formattedMessage, "[\(LogLevel.Warning)][name] Log message")
}
func testFormatterAppliesDateMarkerWithDefaultFormatIfNoneIsSpecified() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%d")
let info: LogInfoDictionary = [.Timestamp: 123456789.0]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate (regex used to avoid problems with time shift)
let validationRegexp = try! NSRegularExpression(pattern: "^1973-11-(29|30) [0-2][0-9]:(03|33|18):09$", options: NSRegularExpression.Options())
let matches = validationRegexp.matches(in: formattedMessage, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, formattedMessage.lengthOfBytes(using: String.Encoding.utf8)))
XCTAssert(matches.count > 0, "Formatted date '\(formattedMessage)' is not valid")
}
func testFormatterAppliesDateMarkerWithFormat() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%d{\"format\":\"%D %T\"}")
let info: LogInfoDictionary = [.Timestamp: 123456789.0]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate (regex used to avoid problems with time shift)
let validationRegexp = try! NSRegularExpression(pattern: "^11/(29|30)/73 [0-2][0-9]:(03|33|18):09$", options: NSRegularExpression.Options())
let matches = validationRegexp.matches(in: formattedMessage, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, formattedMessage.lengthOfBytes(using: String.Encoding.utf8)))
XCTAssert(matches.count > 0, "Formatted date '\(formattedMessage)' is not valid")
}
func testFormatterAppliesDateMarkerWithFormatAndCommonParametersPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%d{'padding':'19', 'format':'%D %T'}")
let info: LogInfoDictionary = [.Timestamp: 123456789.0]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate (regex used to avoid problems with time shift)
let validationRegexp = try! NSRegularExpression(pattern: "^11/(29|30)/73 [0-2][0-9]:(03|33|18):09 $", options: NSRegularExpression.Options())
let matches = validationRegexp.matches(in: formattedMessage, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, formattedMessage.lengthOfBytes(using: String.Encoding.utf8)))
XCTAssert(matches.count > 0, "Formatted date '\(formattedMessage)' is not valid")
}
func testFormatterAppliesDateMarkerWithFormatAndCommonParametersNegativePadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%d{'padding':'-19', 'format':'%D %R'}")
let info: LogInfoDictionary = [.Timestamp: 123456789.0]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate (regex used to avoid problems with time shift)
let validationRegexp = try! NSRegularExpression(pattern: "^ 11/(29|30)/73 [0-2][0-9]:(03|33|18)$", options: NSRegularExpression.Options())
let matches = validationRegexp.matches(in: formattedMessage, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, formattedMessage.lengthOfBytes(using: String.Encoding.utf8)))
XCTAssert(matches.count > 0, "Formatted date '\(formattedMessage)' is not valid")
}
func testFormatterAppliesDateMarkerWithFormatAndCommonParametersZeroPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%d{'padding':'0', 'format':'%D %R'}")
let info: LogInfoDictionary = [.Timestamp: 123456789.0]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate (regex used to avoid problems with time shift)
let validationRegexp = try! NSRegularExpression(pattern: "^11/(29|30)/73 [0-2][0-9]:(03|33|18)$", options: NSRegularExpression.Options())
let matches = validationRegexp.matches(in: formattedMessage, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, formattedMessage.lengthOfBytes(using: String.Encoding.utf8)))
XCTAssert(matches.count > 0, "Formatted date '\(formattedMessage)' is not valid")
}
func testCurrentTimeIsUsedByFormatterIfTimeIsNotAvailableInInfo() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%d{'padding':'0', 'format':'%s'}")
let info = LogInfoDictionary()
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
let expectedTimestamp = Date().timeIntervalSince1970
if let loggedMessageTime = TimeInterval(formattedMessage) {
XCTAssertEqual(loggedMessageTime, expectedTimestamp, accuracy: 1.0)
} else {
XCTAssertTrue(false, "Could not read logged time")
}
}
func testMarkerParametersAreInterpreted() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %l{'padding':'0'}")
let info: LogInfoDictionary = [LogInfoKeys.LogLevel: LogLevel.Debug]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test \(LogLevel.Debug)")
}
func testFormatterAppliesFileNameMarker() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %F")
let info: LogInfoDictionary = [LogInfoKeys.FileName: "testFileName"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test testFileName")
}
func testFormatterAppliesFileNameMarkerWithCommonParametersPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %F{'padding':'10'}")
let info: LogInfoDictionary = [LogInfoKeys.FileName: "12345"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 12345 ")
}
func testFormatterAppliesFileNameMarkerWithCommonParametersNegativePadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %F{'padding':'-10'}")
let info: LogInfoDictionary = [LogInfoKeys.FileName: "12345"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 12345")
}
func testFormatterAppliesFileNameMarkerWithCommonParametersZeroPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %F{'padding':'0'}")
let info: LogInfoDictionary = [LogInfoKeys.FileName: "12345"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 12345")
}
func testFormatterAppliesShortFileNameMarker() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %f")
let info: LogInfoDictionary = [LogInfoKeys.FileName: "/test/testFileName.txt"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test testFileName.txt")
}
func testFormatterAppliesShortFileNameMarkerWithCommonParametersPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %f{'padding':'10'}")
let info: LogInfoDictionary = [LogInfoKeys.FileName: "/test/12345"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 12345 ")
}
func testFormatterAppliesShortFileNameMarkerWithCommonParametersNegativePadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %f{'padding':'-10'}")
let info: LogInfoDictionary = [LogInfoKeys.FileName: "/test/12345"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 12345")
}
func testFormatterAppliesShortFileNameMarkerWithCommonParametersZeroPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %f{'padding':'0'}")
let info: LogInfoDictionary = [LogInfoKeys.FileName: "/test/12345"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 12345")
}
func testFormatterAppliesFileLineMarker() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %L")
let info: LogInfoDictionary = [LogInfoKeys.FileLine: 42]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 42")
}
func testFormatterAppliesFileLineMarkerWithCommonParametersPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %L{'padding':'5'}")
let info: LogInfoDictionary = [LogInfoKeys.FileLine: 42]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 42 ")
}
func testFormatterAppliesFileLineMarkerWithCommonParametersNegativePadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %L{'padding':'-5'}")
let info: LogInfoDictionary = [LogInfoKeys.FileLine: 42]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 42")
}
func testFormatterAppliesFileLineMarkerWithCommonParametersZeroPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %L{'padding':'0'}")
let info: LogInfoDictionary = [LogInfoKeys.FileLine: 42]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 42")
}
func testFormatterAppliesFunctionMarker() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %M")
let info: LogInfoDictionary = [LogInfoKeys.Function: "testFunction"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test testFunction")
}
func testFormatterAppliesFunctionMarkerWithCommonParametersPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %M{'padding':'10'}")
let info: LogInfoDictionary = [LogInfoKeys.Function: "12345"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 12345 ")
}
func testFormatterAppliesFunctionMarkerWithCommonParametersNegativePadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %M{'padding':'-10'}")
let info: LogInfoDictionary = [LogInfoKeys.Function: "12345"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 12345")
}
func testFormatterAppliesFunctionMarkerWithCommonParametersZeroPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %M{'padding':'0'}")
let info: LogInfoDictionary = [LogInfoKeys.Function: "12345"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 12345")
}
func testFormatterAppliesPercentageMarker() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %%")
let info = LogInfoDictionary()
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test %")
}
func testFormatterDoesNotReplaceUnknownMarkers() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%x %y %z are unknown markers")
let info = LogInfoDictionary()
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "%x %y %z are unknown markers")
}
func testFormatterWithComplexFormatting() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "[%l][%n] %m")
let info: LogInfoDictionary = [
LogInfoKeys.LoggerName: "nameOfTheLogger",
LogInfoKeys.LogLevel: LogLevel.Warning
]
// Execute
let formattedMessage = formatter.format(message: "Log message", info: info)
// Validate
XCTAssertEqual(formattedMessage, "[\(LogLevel.Warning)][nameOfTheLogger] Log message")
}
func testFormatterReturnsDashIfDataUnavailableForMarkers() {
let formatter = try! PatternFormatter(identifier: "testFormatter", pattern: "[%l][%n][%F][%f][%L][%M][%t][%T] %m")
let info = LogInfoDictionary()
// Execute
let formattedMessage = formatter.format(message: "Log message", info: info)
// Validate
XCTAssertEqual(formattedMessage, "[-][-][-][-][-][-][-][-] Log message")
}
func testUpdatingFormatterFromDictionaryWithNoPatternThrowsError() {
let dictionary = Dictionary<String, Any>()
let formatter = PatternFormatter("testFormatter")
XCTAssertThrows { try formatter.update(withDictionary: dictionary) }
}
func testUpdatingFormatterFromDictionaryWithInvalidPatternThrowsError() {
let dictionary = [PatternFormatter.DictionaryKey.Pattern.rawValue: "%x{"]
let formatter = PatternFormatter("testFormatter")
XCTAssertThrows { try formatter.update(withDictionary: dictionary) }
}
func testUpdatingFormatterFromDictionaryWithValidParametersCreatesFormatter() {
let dictionary = [PatternFormatter.DictionaryKey.Pattern.rawValue: "static test pattern"]
let formatter = PatternFormatter("testFormatter")
_ = XCTAssertNoThrow { try formatter.update(withDictionary: dictionary); }
let formattedMessage = formatter.format(message: "", info: LogInfoDictionary())
XCTAssertEqual(formattedMessage, dictionary[PatternFormatter.DictionaryKey.Pattern.rawValue]!)
}
func testFormatterAppliesHighResDateMarkerWithDefaultFormatIfNoneIsSpecified() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%D")
let info: LogInfoDictionary = [.Timestamp: 123456789.876]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate (regex used to avoid problems with time shift)
let validationRegexp = try! NSRegularExpression(pattern: "^1973-11-(29|30) [0-2][0-9]:(03|33|18):09.876$", options: NSRegularExpression.Options())
let matches = validationRegexp.matches(in: formattedMessage, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, formattedMessage.lengthOfBytes(using: String.Encoding.utf8)))
XCTAssert(matches.count > 0, "Formatted date '\(formattedMessage)' is not valid")
}
func testFormatterAppliesCocoaDateMarkerWithFormat() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%D{\"format\":\"dd.MM.yy HH:mm:ss.SSS\"}")
let info: LogInfoDictionary = [.Timestamp: 123456789.876]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate (regex used to avoid problems with time shift)
let validationRegexp = try! NSRegularExpression(pattern: "^(29|30).11.73 [0-2][0-9]:(03|33|18):09.876$", options: NSRegularExpression.Options())
let matches = validationRegexp.matches(in: formattedMessage, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, formattedMessage.lengthOfBytes(using: String.Encoding.utf8)))
XCTAssert(matches.count > 0, "Formatted date '\(formattedMessage)' is not valid")
}
func testFormatterAppliesCocoaDateMarkerWithFormatAndPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%D{'padding':'23', 'format':'dd.MM.yy HH:mm:ss.SSS'}")
let info: LogInfoDictionary = [.Timestamp: 123456789.876]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate (regex used to avoid problems with time shift)
let validationRegexp = try! NSRegularExpression(pattern: "^(29|30).11.73 [0-2][0-9]:(03|33|18):09.876 $", options: NSRegularExpression.Options())
let matches = validationRegexp.matches(in: formattedMessage, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, formattedMessage.lengthOfBytes(using: String.Encoding.utf8)))
XCTAssert(matches.count > 0, "Formatted date '\(formattedMessage)' is not valid")
}
func testFormatterAppliesCocoaDateMarkerWithFormatAndNegativePadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%D{'padding':'-23', 'format':'dd.MM.yy HH:mm:ss.SSS'}")
let info: LogInfoDictionary = [.Timestamp: 123456789.876]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate (regex used to avoid problems with time shift)
let validationRegexp = try! NSRegularExpression(pattern: "^ (29|30).11.73 [0-2][0-9]:(03|33|18):09.876$", options: NSRegularExpression.Options())
let matches = validationRegexp.matches(in: formattedMessage, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, formattedMessage.lengthOfBytes(using: String.Encoding.utf8)))
XCTAssert(matches.count > 0, "Formatted date '\(formattedMessage)' is not valid")
}
func testFormatterAppliesCocoaDateMarkerWithFormatAndZeroPadding() {
let format = "dd.MM.yy HH:mm:ss.SSS"
let timestamp = 123456789.876
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%D{'padding':'0', 'format':'\(format)'}")
let info: LogInfoDictionary = [.Timestamp: timestamp]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
let decodedDate = dateFormatter.date(from: formattedMessage)
XCTAssertEqual(decodedDate?.timeIntervalSince1970 ?? 0.0, timestamp, accuracy: 0.01, "Formatted date '\(formattedMessage)' is not valid")
}
func testFormatterAppliesCocoaDateMarkerWithCurrentTimestampIfNoneIsProvided() {
let format = "dd.MM.yy HH:mm:ss.SSS"
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "%D{'format':'\(format)'}")
let expectedDate = Date()
// Execute
let formattedMessage = formatter.format(message: "", info: [:])
// Validate
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
let decodedDate = dateFormatter.date(from: formattedMessage) ?? Date.distantPast
XCTAssert(abs(expectedDate.timeIntervalSince(decodedDate)) < 0.01, "Formatted date is not now when no timestamp is provided")
}
func testFormatterAppliesThreadIdMarker() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %t")
let info: LogInfoDictionary = [.ThreadId: UInt64(0x1234567890ABCDEF)]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 1234567890abcdef")
}
func testFormatterAppliesThreadIdMarkerWithCommonParametersPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %t{'padding':'20'}")
let info: LogInfoDictionary = [.ThreadId: UInt64(0x1234567890ABCDEF)]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 1234567890abcdef ")
}
func testFormatterAppliesThreadIdMarkerWithCommonParametersNegativePadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %t{'padding':'-20'}")
let info: LogInfoDictionary = [.ThreadId: UInt64(0x1234567890ABCDEF)]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 1234567890abcdef")
}
func testFormatterAppliesThreadIdMarkerWithCommonParametersZeroPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %t{'padding':'0'}")
let info: LogInfoDictionary = [.ThreadId: UInt64(0x1234567890ABCDEF)]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test 1234567890abcdef")
}
func testFormatterAppliesThreadNameMarker() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %T")
let info: LogInfoDictionary = [.ThreadName: "nameOfThread"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test nameOfThread")
}
func testFormatterAppliesThreadNameMarkerWithCommonParametersPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %T{'padding':'15'}")
let info: LogInfoDictionary = [.ThreadName: "nameOfThread"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test nameOfThread ")
}
func testFormatterAppliesThreadNameMarkerWithCommonParametersNegativePadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %T{'padding':'-15'}")
let info: LogInfoDictionary = [.ThreadName: "nameOfThread"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test nameOfThread")
}
func testFormatterAppliesThreadNameMarkerWithCommonParametersZeroPadding() {
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %T{'padding':'0'}")
let info: LogInfoDictionary = [.ThreadName: "nameOfThread"]
// Execute
let formattedMessage = formatter.format(message: "", info: info)
// Validate
XCTAssertEqual(formattedMessage, "test nameOfThread")
}
func testFormatterAppliesProcessIdMarker() {
let expectedProcessId = String(ProcessInfo.processInfo.processIdentifier, radix: 16, uppercase: false)
let formatter = try! PatternFormatter(identifier:"testFormatter", pattern: "test %p")
// Execute
let formattedMessage = formatter.format(message: "", info: [:])
// Validate
XCTAssertEqual(formattedMessage, "test \(expectedProcessId)")
}
func testFormatterAppliesProcessIdMarkerWithCommonParametersPadding() {
let padding = 10
let formatter = try! PatternFormatter(identifier: "testFormatter", pattern: "test %p{'padding':'\(padding)'}")
let expectedProcessId = String(ProcessInfo.processInfo.processIdentifier, radix: 16, uppercase: false)
let expectedSpaces = String(repeating: " ", count: padding - expectedProcessId.count)
let expectedString = "test \(expectedProcessId)\(expectedSpaces)"
// Execute
let formattedMessage = formatter.format(message: "", info: [:])
// Validate
XCTAssertEqual(formattedMessage, expectedString)
}
func testFormatterAppliesProcessIdMarkerWithCommonParametersNegativePadding() {
let padding = -10
let formatter = try! PatternFormatter(identifier: "testFormatter", pattern: "test %p{'padding':'-10'}")
let expectedProcessId = String(ProcessInfo.processInfo.processIdentifier, radix: 16, uppercase: false)
let expectedSpaces = String(repeating: " ", count: abs(padding) - expectedProcessId.count)
let expectedString = "test \(expectedSpaces)\(expectedProcessId)"
// Execute
let formattedMessage = formatter.format(message: "", info: [:])
// Validate
XCTAssertEqual(formattedMessage, expectedString)
}
func testFormatterAppliesProcessIdMarkerWithCommonParametersZeroPadding() {
let formatter = try! PatternFormatter(identifier: "testFormatter", pattern: "test %p{'padding':'0'}")
let expectedProcessId = String(ProcessInfo.processInfo.processIdentifier, radix: 16, uppercase: false)
let expectedString = "test \(expectedProcessId)"
// Execute
let formattedMessage = formatter.format(message: "", info: [:])
// Validate
XCTAssertEqual(formattedMessage, expectedString)
}
}
| apache-2.0 | 3dddc2b0436709baa652a6e415c853de | 40.654167 | 196 | 0.716048 | 4.4843 | false | true | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/Swiftz/Sources/Swiftz/Ratio.swift | 3 | 2947 | //
// Ratio.swift
// Swiftz
//
// Created by Robert Widmann on 8/11/15.
// Copyright © 2015-2016 TypeLift. All rights reserved.
//
#if SWIFT_PACKAGE
import Swiftx
#endif
/// "Arbitrary-Precision" ratios of integers.
///
/// While Int has arbitrary precision in Swift, operations beyond 64-bits are O(inf).
public typealias Rational = Ratio<Int>
/// Represents a `Ratio`nal number with an `IntegralType` numerator and denominator.
public struct Ratio<T : IntegralType> {
public let numerator, denominator : () -> T
public init(numerator : @autoclosure @escaping () -> T, denominator : @autoclosure @escaping () -> T) {
self.numerator = numerator
self.denominator = denominator
}
public static var infinity : Rational {
return Rational(numerator: 1, denominator: 0)
}
public static var NAN : Rational {
return Rational(numerator: 0, denominator: 0)
}
}
extension Ratio : Equatable { }
public func == <T>(l : Ratio<T>, r : Ratio<T>) -> Bool {
let lred = reduce(l.numerator(), d: l.denominator())
let rred = reduce(r.numerator(), d: r.denominator())
return (lred.numerator() == rred.numerator()) && (rred.denominator() == rred.denominator())
}
extension Ratio : Comparable { }
public func < <T>(l : Ratio<T>, r : Ratio<T>) -> Bool {
return (l.numerator().times(r.denominator())) < (r.numerator().times(l.denominator()))
}
public func <= <T>(l : Ratio<T>, r : Ratio<T>) -> Bool {
return (l.numerator().times(r.denominator())) <= (r.numerator().times(l.denominator()))
}
public func >= <T>(l : Ratio<T>, r : Ratio<T>) -> Bool {
return !(l < r)
}
public func > <T>(l : Ratio<T>, r : Ratio<T>) -> Bool {
return !(l <= r)
}
extension Ratio : NumericType {
public static var zero : Ratio<T> { return Ratio(numerator: T.zero, denominator: T.one) }
public static var one : Ratio<T> { return Ratio(numerator: T.one, denominator: T.one) }
public var signum : Ratio<T> { return Ratio(numerator: self.numerator().signum, denominator: T.one) }
public var negate : Ratio<T> { return Ratio(numerator: self.numerator().negate, denominator: self.denominator()) }
public func plus(_ other : Ratio<T>) -> Ratio<T> {
return reduce(self.numerator().times(other .denominator()).plus(other .numerator().times(self.denominator())), d: self.denominator().times(other .denominator()))
}
public func minus(_ other : Ratio<T>) -> Ratio<T> {
return reduce(self.numerator().times(other .denominator()).minus(other .numerator().times(self.denominator())), d: self.denominator().times(other .denominator()))
}
public func times(_ other : Ratio<T>) -> Ratio<T> {
return reduce(self.numerator().times(other .numerator()), d: self.denominator().times(other .denominator()))
}
}
/// Implementation Details Follow
private func reduce<T>(_ n : T, d : T) -> Ratio<T> {
if d == T.zero {
return undefined()
}
let gcd = n.greatestCommonDivisor(d)
return Ratio(numerator: n.quotient(gcd), denominator: d.quotient(gcd))
}
| apache-2.0 | 683e5cb3ad8aff3b7db2478809fb15ae | 31.733333 | 164 | 0.671419 | 3.325056 | false | false | false | false |
qvacua/vimr | Tabs/Sources/Tabs/Theme.swift | 1 | 1878 | /**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Cocoa
import MaterialIcons
public struct Theme {
public static let `default` = Self()
public var foregroundColor = NSColor.textColor {
didSet {
self.closeButtonImage = Icon.close.asImage(
dimension: self.iconDimension.width,
color: self.foregroundColor
)
}
}
public var backgroundColor = NSColor.textBackgroundColor
public var separatorColor = NSColor.gridColor
public var selectedForegroundColor = NSColor.selectedTextColor {
didSet {
self.selectedCloseButtonImage = Icon.close.asImage(
dimension: self.iconDimension.width,
color: self.selectedForegroundColor
)
}
}
public var selectedBackgroundColor = NSColor.selectedTextBackgroundColor
public var tabSelectedIndicatorColor = NSColor.selectedTextColor
public var titleFont = NSFont.systemFont(ofSize: 11)
public var selectedTitleFont = NSFont.boldSystemFont(ofSize: 11)
public var tabHeight = CGFloat(28)
public var tabMaxWidth = CGFloat(250)
public var separatorThickness = CGFloat(1)
public var tabHorizontalPadding = CGFloat(4)
public var tabSelectionIndicatorThickness = CGFloat(3)
public var iconDimension = CGSize(width: 16, height: 16)
public var tabMinWidth: CGFloat {
3 * self.tabHorizontalPadding + self.iconDimension.width + 32
}
public var tabBarHeight: CGFloat { self.tabHeight }
public var tabSpacing = CGFloat(-1)
public var closeButtonImage: NSImage
public var selectedCloseButtonImage: NSImage
public init() {
self.closeButtonImage = Icon.close.asImage(
dimension: self.iconDimension.width,
color: self.foregroundColor
)
self.selectedCloseButtonImage = Icon.close.asImage(
dimension: self.iconDimension.width,
color: self.selectedForegroundColor
)
}
}
| mit | 56c2f8d1983ed56e7185a31baa03d93d | 26.217391 | 74 | 0.728967 | 4.625616 | false | false | false | false |
tensorflow/swift | Sources/SIL/Bitstream.swift | 1 | 4572 | // 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 Foundation
// You can think of this struct as either [Bool] representing a bit sequence
// or as an arbitrary precision integer (with checked casts to fixed-width values).
struct Bits: Equatable, Hashable, ExpressibleByIntegerLiteral, CustomStringConvertible {
// Sorted in the order of significance, i.e. bits[0] is the LSB.
private var bits: [Bool]
var description: String { String(bits.reversed().map { $0 ? "1" : "0" }) }
var count: Int { bits.lastIndex(of: true).map { $0 + 1 } ?? 0 }
var isZero: Bool { bits.allSatisfy(!) }
// TODO(#30): Going through strings might be a bit slow, and in those cases
// we can utilize bitwise shifts, or use a more efficient representation
var uint8: UInt8 { return cast() }
var uint32: UInt32 { return cast() }
var int: Int {
assert(
count <= Int.bitWidth - 1,
"Casting a bit sequence of length " + String(bits.count) + " to an integer of width "
+ String(Int.bitWidth - 1))
return Int(uint32)
}
init(integerLiteral lit: Int) {
self.init(lit)
}
init(_ value: Int) {
self.bits = []
var rem = value
while rem != 0 {
bits.append(rem % 2 == 1)
rem /= 2
}
}
init(leastFirst bits: [Bool]) { self.bits = bits }
init(mostFirst bits: [Bool]) { self.bits = bits.reversed() }
// NB: Assumes that the integer is unsigned!
private func cast<T: FixedWidthInteger>() -> T {
assert(
count <= T.bitWidth,
"Casting a bit sequence of length " + String(bits.count) + " to an integer of width "
+ String(T.bitWidth))
return T.init(count == 0 ? "0" : description, radix: 2)!
}
static func join(_ arr: [Bits]) -> Bits {
return Bits(leastFirst: Array(arr.map { $0.bits }.joined()))
}
static func == (lhs: Bits, rhs: Bits) -> Bool {
let minLen = min(lhs.bits.count, rhs.bits.count)
// NB: .count does not consider trailing zeros
return zip(lhs.bits, rhs.bits).allSatisfy(==) && lhs.count <= minLen && rhs.count <= minLen
}
func hash(into hasher: inout Hasher) {
for b in 0..<count {
hasher.combine(b)
}
}
}
// Reinterprets Data as a stream of bits instead of bytes
struct Bitstream {
let data: Data
var offset: Int = 0 // NB: in bits, not bytes!
var byteOffset: Int { offset / 8; }
var bitOffset: Int { offset % 8; }
var isEmpty: Bool { offset == data.count * 8 }
enum Error: Swift.Error {
case endOfFile
}
init(_ fromData: Data) { data = fromData }
mutating func nextBit() throws -> Bool {
try checkOffset(needBits: 1)
let byte = data[byteOffset]
let result = (byte >> bitOffset) % 2 == 1
offset += 1
return result
}
mutating func nextByte() throws -> UInt8 {
if (offset % 8 == 0) {
try checkOffset(needBits: 8)
let result = data[byteOffset]
offset += 8
return result
} else {
return try next(bits: 8).uint8
}
}
mutating func next(bits num: Int) throws -> Bits {
var bits: [Bool] = []
for _ in 0..<num {
bits.append(try nextBit())
}
return Bits(leastFirst: bits)
}
mutating func next(bytes num: Int) throws -> [UInt8] {
var bytes: [UInt8] = []
for _ in 0..<num {
bytes.append(try nextByte())
}
return bytes
}
mutating func align(toMultipleOf mult: Int) {
let rem = offset % mult
if rem == 0 { return }
offset += mult - (offset % mult)
assert(offset % mult == 0)
}
private func checkOffset(needBits needed: Int) throws {
guard offset <= (data.count * 8 - needed) else {
throw Error.endOfFile
}
}
}
| apache-2.0 | 265d69d2d013be71754a891efd433fca | 31.425532 | 99 | 0.581802 | 3.979112 | false | false | false | false |
awind/Pixel | Pixel/SettingViewController.swift | 1 | 5998 | //
// SettingViewController.swift
// Pixel
//
// Created by Fei on 15/12/30.
// Copyright © 2015年 SongFei. All rights reserved.
//
import UIKit
import Armchair
import MessageUI
import MBProgressHUD
class SettingViewController: UIViewController, MFMailComposeViewControllerDelegate {
@IBOutlet weak var cacheSize: UILabel!
@IBOutlet weak var logoutButton: UIButton!
var size = Int()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Settings"
self.navigationController?.navigationBar.barTintColor = UIColor(red: 46.0/255.0, green: 123.0/255.0, blue: 213.0/255.0, alpha: 1.0)
self.navigationController?.navigationBar.barStyle = UIBarStyle.Black
self.navigationController?.navigationBar.translucent = true
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(done))
cacheFolderSize()
cacheSize.text = "\(size/(1024*1024))MB"
if !Account.checkIsLogin() {
logoutButton.hidden = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func about(sender: AnyObject) {
self.navigationController?.pushViewController(AboutViewController(), animated: true)
}
@IBAction func clear(sender: UIButton) {
let message = "\(self.size/(1024*1024))MB缓存"
let alert = UIAlertController(title: NSLocalizedString("CLEAR_CACHE", comment: "clearCache"), message: message, preferredStyle: UIAlertControllerStyle.Alert)
let alertConfirm = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default) { alertConfirm in
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.mode = .Determinate
hud.labelText = NSLocalizedString("LOADING", comment: "loading")
dispatch_async(dispatch_get_main_queue(), {
self.clearCacheFolder()
hud.hide(true)
self.cacheSize.text = "0MB"
self.size = 0
})
}
let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: "cancel"), style: UIAlertActionStyle.Cancel) { (cancle) -> Void in
}
alert.addAction(alertConfirm)
alert.addAction(cancel)
self.presentViewController(alert, animated: true, completion: nil)
}
@IBAction func review(sender: AnyObject) {
Armchair.rateApp()
}
@IBAction func logout(sender: AnyObject) {
let userDefault = NSUserDefaults.standardUserDefaults()
userDefault.removeObjectForKey("accessToken")
self.presentViewController(GuideViewController(), animated: true, completion: nil)
}
@IBAction func feedback(sender: UIButton) {
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
} else {
//self.showSendMailErrorAlert()
}
}
func done() {
self.dismissViewControllerAnimated(true, completion: nil)
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["[email protected]"])
mailComposerVC.setSubject("Feedback for Pixel")
mailComposerVC.setMessageBody("Some Advice for Pixel", isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
let alertVC = UIAlertController(title: "无法发送邮件", message: "您的设备无法发送邮件,请检查您的邮件配置。", preferredStyle: .Alert)
let confirmAction = UIAlertAction(title: "确定", style: .Default, handler: nil)
alertVC.addAction(confirmAction)
self.presentViewController(alertVC, animated: true, completion: nil)
}
// MARK: MFMailComposeViewControllerDelegate
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
func cacheFolderSize() {
let cachePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
// print(cachePath)
let files = NSFileManager.defaultManager().subpathsAtPath(cachePath!)
for p in files!{
let path = cachePath!.stringByAppendingFormat("/\(p)")
let floder = try! NSFileManager.defaultManager().attributesOfItemAtPath(path)
for (abc,bcd) in floder {
if abc == NSFileSize {
size += bcd.integerValue
}
}
}
}
func clearCacheFolder() {
let cachePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
// print(cachePath)
let files = NSFileManager.defaultManager().subpathsAtPath(cachePath!)
for p in files!{
let path = cachePath!.stringByAppendingFormat("/\(p)")
if(NSFileManager.defaultManager().fileExistsAtPath(path)){
do {
try NSFileManager.defaultManager().removeItemAtPath(path)
} catch {
print("Error !!!!!")
}
}
}
}
} | apache-2.0 | 62dc7f46ccc6e3ee2b9b7c7c39ac30c6 | 36.295597 | 165 | 0.651881 | 5.515349 | false | false | false | false |
cnoon/swift-compiler-crashes | crashes-duplicates/19387-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 11 | 2331 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func
let : A {
enum A {
struct d<T where g: P {
let t: a<T where T where g: P {
let a {
b
struct d
let a {
let AnyObject, A {
func < {
var f
class A.h
}
class d
let i { f
struct A {
class B
}
var d = Int
var b = {
protocol b = Int
}
}
class b<T> : e: T> {
class A : T where g: P {
enum S<ff where g {
let AnyObject.d<h {
protocol A {
let : Int = {
func f: B<T where h: T: P {
var d {
struct A : T where h: P {
struct A {
var f: a {
class b
func b( ) {
class B
var e: P {
b( )
enum S<d where g: e
init( )
}(v: a {
class B<T where h: A")
let t: A"
}
class d<T where T> : B
var f: B
class B<T where h: e == " " " [ ]
protocol b = " " [ ]
struct d<T where T: P {
var f: Int = Int
class A {
func b( )?
{
var b = c() {
var b = i{
class B<g {
class B<T where T where g: T> : AnyObject.c {
class b<T where g: A"
enum e : A")?
init( ) -> : B<T where g: AnyObject.c {
class B<l {
func
}
var b = D>(x()
struct d<T where g: a {
class B<T where h
func a<T where g: P {
class A {
func a<T where g: B<T where g: T where g: A")
let t: d = " " " " " [ ]
let t: B<T {
class B
}()
class b<T: B
class A : AnyObject, A {
let AnyObject.c {
func
}
}
class A {
let a {
func
enum e : a {
var e
let t: Int = D>(x() {
func < {
class B<T {
let a {
class A<T where h: P {
enum e == " " [ 1
class B<T : P {
class A {
return ")
class d: Int = i{
class B<l {
let : AnyObject, U) {
class C<T where h
}
enum e == " [ 1
let t: P {
b
class A {
}
class B
func b
class A {
func a<ff where h: A<T : a {
class B<g = " " [ ]
class A {
var b {
class A {
let a {
}
let : B
class d<T where g: A {
func a() -> : P {
class B<T where g: a {
var b = Int
class A"
}
let a {
class B<T where h
let a {
var e: A {
var f: a {
class B<T where h
struct d
func
class B<T> : e : T: P {
func b
class d<h {
func a()
protocol b = D>(x(t: a {
var f: a {
func f: A<l {
func
class a<T where g: a {
let i { f
protocol A {
[ ]
class d
class b
class b( )
let : Int = i{
func < {
let t: a {
protocol A {
var b = " " [ ]
let a {
class a<T {
class B
func a<T where h: e
let a : a {
let AnyObject, U) -> : a {
func b( ) -> : c()?
class B<T where h: A {
func a
var b {
class B
return ")
var b {
protocol A {
var d = i{
enum A {
func
| mit | 79f1804be60990c4f4f484ade3f55096 | 12.631579 | 87 | 0.56671 | 2.307921 | false | false | false | false |
einsteinx2/iSub | Classes/Singletons/PlayQueue.swift | 1 | 19087 | //
// PlayQueue.swift
// Pods
//
// Created by Benjamin Baron on 2/11/16.
//
//
import Foundation
import MediaPlayer
import Nuke
enum RepeatMode: Int {
case normal = 0
case repeatOne = 1
case repeatAll = 2
}
enum ShuffleMode: Int {
case normal = 0
case shuffle = 1
}
final class PlayQueue {
// MARK: - Notifications -
struct Notifications {
static let indexChanged = Notification.Name("PlayQueue_indexChanged")
static let displayVideo = Notification.Name("PlayQueue_displayVideo")
static let videoEnded = Notification.Name("PlayQueue_videoEnded")
struct Keys {
static let avPlayer = "avPlayer"
}
}
func notifyPlayQueueIndexChanged() {
NotificationCenter.postOnMainThread(name: PlayQueue.Notifications.indexChanged)
}
fileprivate func registerForNotifications() {
// Watch for changes to the play queue playlist
NotificationCenter.addObserverOnMainThread(self, selector: #selector(playlistChanged(_:)), name: Playlist.Notifications.playlistChanged)
NotificationCenter.addObserverOnMainThread(self, selector: #selector(songStarted), name: GaplessPlayer.Notifications.songStarted)
NotificationCenter.addObserverOnMainThread(self, selector: #selector(songPaused), name: GaplessPlayer.Notifications.songPaused)
NotificationCenter.addObserverOnMainThread(self, selector: #selector(songEnded), name: GaplessPlayer.Notifications.songEnded)
NotificationCenter.addObserverOnMainThread(self, selector: #selector(videoEnded(_:)), name: Notifications.videoEnded)
}
fileprivate func unregisterForNotifications() {
NotificationCenter.removeObserverOnMainThread(self, name: Playlist.Notifications.playlistChanged)
NotificationCenter.removeObserverOnMainThread(self, name: GaplessPlayer.Notifications.songStarted)
NotificationCenter.removeObserverOnMainThread(self, name: GaplessPlayer.Notifications.songPaused)
NotificationCenter.removeObserverOnMainThread(self, name: GaplessPlayer.Notifications.songEnded)
NotificationCenter.removeObserverOnMainThread(self, name: Notifications.videoEnded)
}
@objc fileprivate func playlistChanged(_ notification: Notification) {
}
@objc fileprivate func songStarted() {
updateLockScreenInfo()
}
@objc fileprivate func songPaused() {
updateLockScreenInfo()
}
@objc fileprivate func songEnded() {
incrementIndex()
updateLockScreenInfo()
StreamQueue.si.start()
}
@objc fileprivate func videoEnded(_ notification: Notification) {
songEnded()
playSong(atIndex: currentIndex)
}
// MARK: - Properties -
static let si = PlayQueue()
var repeatMode = RepeatMode.normal
var shuffleMode = ShuffleMode.normal { didSet { /* TODO: Do something */ } }
fileprivate(set) var currentIndex = -1 {
didSet {
preheadArt()
updateLockScreenInfo()
// Prefetch the art
if let coverArtId = currentSong?.coverArtId, let serverId = currentSong?.serverId {
CachedImage.preheat(coverArtId: coverArtId, serverId: serverId, size: .player)
CachedImage.preheat(coverArtId: coverArtId, serverId: serverId, size: .cell)
}
if currentIndex != oldValue {
notifyPlayQueueIndexChanged()
}
}
}
var previousIndex: Int { return indexAtOffset(-1, fromIndex: currentIndex) }
var nextIndex: Int { return indexAtOffset(1, fromIndex: currentIndex) }
var currentDisplaySong: Song? { return currentSong ?? previousSong }
var currentSong: Song? { return playlist.song(atIndex: currentIndex) }
var previousSong: Song? { return playlist.song(atIndex: previousIndex) }
var nextSong: Song? { return playlist.song(atIndex: nextIndex) }
var songCount: Int { return playlist.songCount }
var isPlaying: Bool { return player.isPlaying }
var isStarted: Bool { return player.isStarted }
var currentSongProgress: Double { return player.progress }
var playlist: Playlist { return Playlist.playQueue }
var songs: [Song] {
// TODO: Figure out what to do about the way playlist models hold songs and how we regenerate the model in this class
let playlist = self.playlist
playlist.loadSubItems()
return playlist.songs
}
fileprivate let player: GaplessPlayer = { return GaplessPlayer.si }()
fileprivate var videoPlaybackManager: VideoPlaybackManager?
init() {
registerForNotifications()
}
deinit {
unregisterForNotifications()
}
// MARK: - Play Queue -
func incrementIndex() {
currentIndex = nextIndex
}
func reset() {
playlist.removeAllSongs()
player.stop()
currentIndex = -1
}
func removeSongs(atIndexes indexes: IndexSet) {
// Stop the music if we're removing the current song
let containsCurrentIndex = indexes.contains(currentIndex)
if containsCurrentIndex {
player.stop()
}
// Remove the songs
playlist.remove(songsAtIndexes: indexes)
// Adjust the current index if songs are removed below it
if currentIndex >= 0 {
let range = NSMakeRange(0, currentIndex)
let countOfIndexesBelowCurrent = indexes.count(in: Range(range) ?? 0..<0)
currentIndex = currentIndex - countOfIndexesBelowCurrent
}
// If we removed the current song, start the next one
if containsCurrentIndex {
playSong(atIndex: currentIndex)
}
}
func removeSong(atIndex index: Int) {
var indexSet = IndexSet()
indexSet.insert(index)
removeSongs(atIndexes: indexSet)
}
func insertSong(song: Song, index: Int, notify: Bool = false) {
playlist.insert(song: song, index: index, notify: notify)
}
func insertSongNext(song: Song, notify: Bool = false) {
let index = currentIndex < 0 ? songCount : currentIndex + 1
playlist.insert(song: song, index: index, notify: notify)
}
func moveSong(fromIndex: Int, toIndex: Int, notify: Bool = false) {
if playlist.moveSong(fromIndex: fromIndex, toIndex: toIndex, notify: notify) {
if fromIndex == currentIndex && toIndex < currentIndex {
// Moved the current song to a lower index
currentIndex = toIndex
} else if fromIndex == currentIndex && toIndex > currentIndex {
// Moved the current song to a higher index
currentIndex = toIndex - 1
} else if fromIndex > currentIndex && toIndex <= currentIndex {
// Moved a song from after the current song to before
currentIndex += 1
} else if fromIndex < currentIndex && toIndex >= currentIndex {
// Moved a song from before the current song to after
currentIndex -= 1
}
}
}
func songAtIndex(_ index: Int) -> Song? {
return playlist.song(atIndex: index)
}
func indexAtOffset(_ offset: Int, fromIndex: Int) -> Int {
switch repeatMode {
case .normal:
if offset >= 0 {
if fromIndex + offset > songCount {
// If we're past the end of the play queue, always return the last index + 1
return songCount
} else {
return fromIndex + offset
}
} else {
return fromIndex + offset >= 0 ? fromIndex + offset : 0;
}
case .repeatAll:
if offset >= 0 {
if fromIndex + offset >= songCount {
let remainder = offset - (songCount - fromIndex)
return indexAtOffset(remainder, fromIndex: 0)
} else {
return fromIndex + offset
}
} else {
return fromIndex + offset >= 0 ? fromIndex + offset : songCount + fromIndex + offset;
}
case .repeatOne:
return fromIndex
}
}
func indexAtOffsetFromCurrentIndex(_ offset: Int) -> Int {
return indexAtOffset(offset, fromIndex: self.currentIndex)
}
// MARK: - Player Control -
func playSongs(_ songs: [Song], playIndex: Int) {
reset()
playlist.add(songs: songs)
playSong(atIndex: playIndex)
}
func playSong(atIndex index: Int) {
currentIndex = index
if let currentSong = currentSong {
if currentSong.contentType?.basicType == .audio || currentSong.contentType?.basicType == .video {
startSong()
}
}
}
func playPreviousSong() {
if player.progress > 10.0 {
// Past 10 seconds in the song, so restart playback instead of changing songs
playSong(atIndex: self.currentIndex)
} else {
// Within first 10 seconds, go to previous song
playSong(atIndex: self.previousIndex)
}
}
func playNextSong() {
playSong(atIndex: self.nextIndex)
}
func play() {
player.play()
}
func pause() {
player.pause()
}
func playPause() {
player.playPause()
}
func stop() {
player.stop()
}
fileprivate var startSongDelayTimer: DispatchSourceTimer?
func startSong(byteOffset: Int64 = 0) {
if let startSongDelayTimer = startSongDelayTimer {
startSongDelayTimer.cancel()
self.startSongDelayTimer = nil
}
if currentSong != nil {
// Only start the caching process if it's been a half second after the last request
// Prevents crash when skipping through playlist fast
startSongDelayTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.main)
startSongDelayTimer!.schedule(deadline: .now() + .milliseconds(600))
startSongDelayTimer!.setEventHandler {
self.startSongDelayed(byteOffset: byteOffset)
}
startSongDelayTimer!.resume()
} else {
player.stop()
}
}
fileprivate func startSongDelayed(byteOffset: Int64) {
// Destroy the streamer to start a new song
player.stop()
videoPlaybackManager?.stop()
videoPlaybackManager = nil
// Start the stream manager
StreamQueue.si.start()
if let currentSong = currentSong {
if currentSong.contentType?.basicType == .audio {
// Check to see if the song is already cached
if currentSong.isFullyCached {
// The song is fully cached, start streaming from the local copy
player.start(song: currentSong, byteOffset: byteOffset)
} else {
if let currentCachingSong = DownloadQueue.si.currentSong, currentCachingSong == currentSong {
// If the Cache Queue is downloading it and it's ready for playback, start the player
if DownloadQueue.si.streamHandler?.isReadyForPlayback == true {
player.start(song: currentSong, byteOffset: byteOffset)
}
} else {
if StreamQueue.si.streamHandler?.isReadyForPlayback == true {
player.start(song: currentSong, byteOffset: byteOffset)
}
}
}
} else if currentSong.contentType?.basicType == .video, let urlRequest = URLRequest(subsonicAction: .hls, serverId: currentSong.serverId, parameters: ["id": currentSong.songId, "bitRate": ["2048", "1024", "512", "256"]]), let url = urlRequest.url {
// Video, so use the video manager to handle playback and proxying
videoPlaybackManager = VideoPlaybackManager(url: url)
videoPlaybackManager?.start()
} else {
// Neither a song or video, so skip it
playNextSong()
}
}
}
// MARK: - Lock Screen -
fileprivate func preheadArt() {
if let coverArtId = currentSong?.coverArtId, let serverId = currentSong?.serverId {
CachedImage.preheat(coverArtId: coverArtId, serverId: serverId, size: .player)
CachedImage.preheat(coverArtId: coverArtId, serverId: serverId, size: .cell)
}
if let coverArtId = nextSong?.coverArtId, let serverId = currentSong?.serverId {
CachedImage.preheat(coverArtId: coverArtId, serverId: serverId, size: .player)
CachedImage.preheat(coverArtId: coverArtId, serverId: serverId, size: .cell)
}
}
fileprivate var defaultItemArtwork: MPMediaItemArtwork = {
MPMediaItemArtwork(image: CachedImage.default(forSize: .player))
}()
fileprivate var lockScreenUpdateTimer: Timer?
@objc func updateLockScreenInfo() {
var trackInfo = [String: AnyObject]()
if let song = self.currentSong {
trackInfo[MPMediaItemPropertyTitle] = song.title as AnyObject?
if let albumName = song.album?.name {
trackInfo[MPMediaItemPropertyAlbumTitle] = albumName as AnyObject?
}
if let artistName = song.artistDisplayName {
trackInfo[MPMediaItemPropertyArtist] = artistName as AnyObject?
}
if let genre = song.genre?.name {
trackInfo[MPMediaItemPropertyGenre] = genre as AnyObject?
}
if let duration = song.duration {
trackInfo[MPMediaItemPropertyPlaybackDuration] = duration as AnyObject?
}
trackInfo[MPNowPlayingInfoPropertyPlaybackQueueIndex] = currentIndex as AnyObject?
trackInfo[MPNowPlayingInfoPropertyPlaybackQueueCount] = songCount as AnyObject?
trackInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = player.progress as AnyObject?
trackInfo[MPNowPlayingInfoPropertyPlaybackRate] = 1.0 as AnyObject?
trackInfo[MPMediaItemPropertyArtwork] = defaultItemArtwork
if let coverArtId = song.coverArtId, let image = CachedImage.cached(coverArtId: coverArtId, serverId: song.serverId, size: .player) {
trackInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: image)
}
MPNowPlayingInfoCenter.default().nowPlayingInfo = trackInfo
}
// Run this every 15 seconds to update the progress and keep it in sync
if let lockScreenUpdateTimer = self.lockScreenUpdateTimer {
lockScreenUpdateTimer.invalidate()
}
lockScreenUpdateTimer = Timer(timeInterval: 15.0, target: self, selector: #selector(updateLockScreenInfo), userInfo: nil, repeats: false)
}
}
fileprivate class VideoPlaybackManager: NSObject, HLSProxyServerDelegate {
let url: URL
let proxyServer: HLSProxyServer
var player: AVPlayer?
var playerItem: AVPlayerItem?
var registeredForKVO = false
init(url: URL) {
self.url = url
self.proxyServer = HLSProxyServer(playlistUrl: url, allowSelfSignedCerts: true)
super.init()
}
deinit {
stop()
}
func start() {
proxyServer.delegate = self
proxyServer.start()
}
func stop() {
proxyServer.stop()
if registeredForKVO {
playerItem?.removeObserver(self, forKeyPath: "status")
player?.removeObserver(self, forKeyPath: "status")
registeredForKVO = false
}
NotificationCenter.default.removeObserver(self)
}
func hlsProxyServer(_ server: HLSProxyServer, streamIsReady url: URL) {
print("stream ready")
let urlString = "http://localhost:9999/stream.m3u8"
let asset = AVURLAsset(url: URL(string: urlString)!)
let playerItem = AVPlayerItem(asset: asset)
playerItem.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(), context: nil)
self.playerItem = playerItem
let player = AVPlayer(playerItem: playerItem)
player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(), context: nil)
self.player = player
registeredForKVO = true
NotificationCenter.addObserverOnMainThread(self, selector: #selector(videoEnded(_:)), name: .AVPlayerItemDidPlayToEndTime, object: playerItem)
// NotificationCenter.addObserverOnMainThread(self, selector: #selector(videoFailed(_:)), name: .AVPlayerItemNewErrorLogEntry, object: playerItem)
// NotificationCenter.addObserverOnMainThread(self, selector: #selector(videoFailed(_:)), name: .AVPlayerItemFailedToPlayToEndTime, object: playerItem)
// NotificationCenter.addObserverOnMainThread(self, selector: #selector(videoFailed(_:)), name: .AVPlayerItemPlaybackStalled, object: playerItem)
let userInfo = [PlayQueue.Notifications.Keys.avPlayer: player]
NotificationCenter.postOnMainThread(name: PlayQueue.Notifications.displayVideo, object: nil, userInfo: userInfo)
}
func hlsProxyServer(_ server: HLSProxyServer, streamDidFail error: HLSProxyError) {
print("stream did fail")
}
func hlsProxyServer(_ server: HLSProxyServer, playlistDidEnd playlist: HLSPlaylist) {
print("stream playlist did end")
}
@objc func videoEnded(_ notification: Notification) {
let userInfo: [String: Any] = player == nil ? [String: Any]() : [PlayQueue.Notifications.Keys.avPlayer: player as Any]
NotificationCenter.postOnMainThread(name: PlayQueue.Notifications.videoEnded, object: nil, userInfo: userInfo)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let player = object as? AVPlayer {
if player.status == .readyToPlay {
player.play()
}
} else if let playerItem = object as? AVPlayerItem {
// NOTE: Add a breakpoint here to debug playback issues. Check playerItem.error and playerItem.errorLog()
print("playerItem: \(playerItem) keyPath: \(String(describing: keyPath)) change: \(String(describing: change))")
if let error = playerItem.error, let errorLog = playerItem.errorLog() {
log.error("video playback error: \(error) errorLog(): \(errorLog)")
}
}
}
}
| gpl-3.0 | 81889a1c074769fdbf3b60cb73519c0f | 38.517598 | 260 | 0.620056 | 5.155862 | false | false | false | false |
brentdax/swift | test/attr/attr_objc.swift | 1 | 94192 | // RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference | %FileCheck %s
// RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference 2> %t.dump
// RUN: %FileCheck -check-prefix CHECK-DUMP %s < %t.dump
// REQUIRES: objc_interop
import Foundation
class PlainClass {}
struct PlainStruct {}
enum PlainEnum {}
protocol PlainProtocol {} // expected-note {{protocol 'PlainProtocol' declared here}}
enum ErrorEnum : Error {
case failed
}
@objc class Class_ObjC1 {}
protocol Protocol_Class1 : class {} // expected-note {{protocol 'Protocol_Class1' declared here}}
protocol Protocol_Class2 : class {}
@objc protocol Protocol_ObjC1 {}
@objc protocol Protocol_ObjC2 {}
//===--- Subjects of @objc attribute.
@objc extension PlainStruct { } // expected-error{{'@objc' can only be applied to an extension of a class}}{{1-7=}}
class FáncyName {}
@objc (FancyName) extension FáncyName {}
@objc
var subject_globalVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
var subject_getterSetter: Int {
@objc
get { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
return 0
}
@objc
set { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
}
var subject_global_observingAccessorsVar1: Int = 0 {
@objc
willSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
}
@objc
didSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
}
}
class subject_getterSetter1 {
var instanceVar1: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
}
var instanceVar2: Int {
get {
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var instanceVar3: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var observingAccessorsVar1: Int = 0 {
@objc
willSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
@objc
didSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
}
}
class subject_staticVar1 {
@objc
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
@objc
class var staticVar2: Int { return 42 }
}
@objc
func subject_freeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}}
@objc
var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_nestedFreeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
}
@objc
func subject_genericFunc<T>(t: T) { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}}
@objc
var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
func subject_funcParam(a: @objc Int) { // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@objc }} {{27-33=}}
}
@objc // expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}}
struct subject_struct {
@objc
var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
@objc // expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}}
struct subject_genericStruct<T> {
@objc
var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
@objc
class subject_class1 { // no-error
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no-error
}
@objc
class subject_class2 : Protocol_Class1, PlainProtocol { // no-error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}}
class subject_genericClass<T> {
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{1-7=}}
class subject_genericClass2<T> : Class_ObjC1 {
@objc
var subject_instanceVar: Int // no-error
@objc
init(foo: Int) {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
extension subject_genericClass where T : Hashable {
@objc var prop: Int { return 0 } // expected-error{{members of constrained extensions cannot be declared @objc}}
}
extension subject_genericClass {
@objc var extProp: Int { return 0 } // expected-error{{members of extensions of generic classes cannot be declared @objc}}
@objc func extFoo() {} // expected-error{{members of extensions of generic classes cannot be declared @objc}}
}
@objc
enum subject_enum: Int {
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement1
@objc(subject_enumElement2)
case subject_enumElement2
@objc(subject_enumElement3)
case subject_enumElement3, subject_enumElement4 // expected-error {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}}{{3-30=}}
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement5, subject_enumElement6
@nonobjc // expected-error {{'@nonobjc' attribute cannot be applied to this declaration}}
case subject_enumElement7
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
enum subject_enum2 {
@objc(subject_enum2Element1)
case subject_enumElement1 // expected-error{{'@objc' enum case is not allowed outside of an '@objc' enum}}{{3-31=}}
}
@objc
protocol subject_protocol1 {
@objc
var subject_instanceVar: Int { get }
@objc
func subject_instanceFunc()
}
@objc protocol subject_protocol2 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol2 {
@objc protocol subject_protocol3 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol3 {
@objc
protocol subject_protocol4 : PlainProtocol {} // expected-error {{@objc protocol 'subject_protocol4' cannot refine non-@objc protocol 'PlainProtocol'}}
@objc
protocol subject_protocol5 : Protocol_Class1 {} // expected-error {{@objc protocol 'subject_protocol5' cannot refine non-@objc protocol 'Protocol_Class1'}}
@objc
protocol subject_protocol6 : Protocol_ObjC1 {}
protocol subject_containerProtocol1 {
@objc
var subject_instanceVar: Int { get } // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc
func subject_instanceFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc
static func subject_staticFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
@objc
protocol subject_containerObjCProtocol1 {
func func_FunctionReturn1() -> PlainStruct
// expected-error@-1 {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_FunctionParam1(a: PlainStruct)
// expected-error@-1 {{method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_Variadic(_: AnyObject...)
// expected-error @-1{{method cannot be a member of an @objc protocol because it has a variadic parameter}}
// expected-note @-2{{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
subscript(a: PlainStruct) -> Int { get }
// expected-error@-1 {{subscript cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
var varNonObjC1: PlainStruct { get }
// expected-error@-1 {{property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
}
@objc
protocol subject_containerObjCProtocol2 {
init(a: Int)
@objc init(a: Double)
func func1() -> Int
@objc func func1_() -> Int
var instanceVar1: Int { get set }
@objc var instanceVar1_: Int { get set }
subscript(i: Int) -> Int { get set }
@objc subscript(i: String) -> Int { get set}
}
protocol nonObjCProtocol {
@objc func objcRequirement() // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
func concreteContext1() {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext2 {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext3 {
func dynamicSelf1() -> Self { return self }
@objc func dynamicSelf1_() -> Self { return self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func genericParams<T: NSObject>() -> [T] { return [] }
// expected-error@-1{{method cannot be marked @objc because it has generic parameters}}
@objc func returnObjCProtocolMetatype() -> NSCoding.Protocol { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias AnotherNSCoding = NSCoding
typealias MetaNSCoding1 = NSCoding.Protocol
typealias MetaNSCoding2 = AnotherNSCoding.Protocol
@objc func returnObjCAliasProtocolMetatype1() -> AnotherNSCoding.Protocol { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnObjCAliasProtocolMetatype2() -> MetaNSCoding1 { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnObjCAliasProtocolMetatype3() -> MetaNSCoding2 { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias Composition = NSCopying & NSCoding
@objc func returnCompositionMetatype1() -> Composition.Protocol { return Composition.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnCompositionMetatype2() -> (NSCopying & NSCoding).Protocol { return (NSCopying & NSCoding).self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias NSCodingExistential = NSCoding.Type
@objc func inoutFunc(a: inout Int) {}
// expected-error@-1{{method cannot be marked @objc because inout parameters cannot be represented in Objective-C}}
@objc func metatypeOfExistentialMetatypePram1(a: NSCodingExistential.Protocol) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
@objc func metatypeOfExistentialMetatypePram2(a: NSCoding.Type.Protocol) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
}
func genericContext1<T>(_: T) {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {} // expected-error{{type 'subject_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{type 'subject_inGenericContext2' cannot be nested in generic function 'genericContext1'}}
class subject_constructor_inGenericContext { // expected-error{{type 'subject_constructor_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
init() {} // no-error
}
class subject_var_inGenericContext { // expected-error{{type 'subject_var_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
var subject_instanceVar: Int = 0 // no-error
}
class subject_func_inGenericContext { // expected-error{{type 'subject_func_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
func f() {} // no-error
}
}
class GenericContext2<T> {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {}
@objc
func f() {} // no-error
}
class GenericContext3<T> {
class MoreNested {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{5-11=}}
class subject_inGenericContext {}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{5-11=}}
class subject_inGenericContext2 : Class_ObjC1 {}
@objc
func f() {} // no-error
}
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}}
class ConcreteSubclassOfGeneric : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric {
@objc func foo() {} // okay
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{1-7=}}
class ConcreteSubclassOfGeneric2 : subject_genericClass2<Int> {}
extension ConcreteSubclassOfGeneric2 {
@objc func foo() {} // okay
}
@objc(CustomNameForSubclassOfGeneric) // okay
class ConcreteSubclassOfGeneric3 : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric3 {
@objc func foo() {} // okay
}
class subject_subscriptIndexed1 {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed2 {
@objc
subscript(a: Int8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed3 {
@objc
subscript(a: UInt8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed1 {
@objc
subscript(a: String) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed2 {
@objc
subscript(a: Class_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed3 {
@objc
subscript(a: Class_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed4 {
@objc
subscript(a: Protocol_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed5 {
@objc
subscript(a: Protocol_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed6 {
@objc
subscript(a: Protocol_ObjC1 & Protocol_ObjC2) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed7 {
@objc
subscript(a: (Protocol_ObjC1 & Protocol_ObjC2).Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptBridgedFloat {
@objc
subscript(a: Float32) -> Int {
get { return 0 }
}
}
class subject_subscriptGeneric<T> {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptInvalid2 {
@objc
subscript(a: PlainClass) -> Int {
// expected-error@-1 {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid3 {
@objc
subscript(a: PlainClass.Type) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid4 {
@objc
subscript(a: PlainStruct) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid5 {
@objc
subscript(a: PlainEnum) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{enums cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid6 {
@objc
subscript(a: PlainProtocol) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid7 {
@objc
subscript(a: Protocol_Class1) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid8 {
@objc
subscript(a: Protocol_Class1 & Protocol_Class2) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_propertyInvalid1 {
@objc
let plainStruct = PlainStruct() // expected-error {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
}
//===--- Tests for @objc inference.
@objc
class infer_instanceFunc1 {
// CHECK-LABEL: @objc class infer_instanceFunc1 {
func func1() {}
// CHECK-LABEL: @objc func func1() {
@objc func func1_() {} // no-error
func func2(a: Int) {}
// CHECK-LABEL: @objc func func2(a: Int) {
@objc func func2_(a: Int) {} // no-error
func func3(a: Int) -> Int {}
// CHECK-LABEL: @objc func func3(a: Int) -> Int {
@objc func func3_(a: Int) -> Int {} // no-error
func func4(a: Int, b: Double) {}
// CHECK-LABEL: @objc func func4(a: Int, b: Double) {
@objc func func4_(a: Int, b: Double) {} // no-error
func func5(a: String) {}
// CHECK-LABEL: @objc func func5(a: String) {
@objc func func5_(a: String) {} // no-error
func func6() -> String {}
// CHECK-LABEL: @objc func func6() -> String {
@objc func func6_() -> String {} // no-error
func func7(a: PlainClass) {}
// CHECK-LABEL: {{^}} func func7(a: PlainClass) {
@objc func func7_(a: PlainClass) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func7m(a: PlainClass.Type) {}
// CHECK-LABEL: {{^}} func func7m(a: PlainClass.Type) {
@objc func func7m_(a: PlainClass.Type) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
func func8() -> PlainClass {}
// CHECK-LABEL: {{^}} func func8() -> PlainClass {
@objc func func8_() -> PlainClass {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func8m() -> PlainClass.Type {}
// CHECK-LABEL: {{^}} func func8m() -> PlainClass.Type {
@objc func func8m_() -> PlainClass.Type {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
func func9(a: PlainStruct) {}
// CHECK-LABEL: {{^}} func func9(a: PlainStruct) {
@objc func func9_(a: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func10() -> PlainStruct {}
// CHECK-LABEL: {{^}} func func10() -> PlainStruct {
@objc func func10_() -> PlainStruct {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func11(a: PlainEnum) {}
// CHECK-LABEL: {{^}} func func11(a: PlainEnum) {
@objc func func11_(a: PlainEnum) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
func func12(a: PlainProtocol) {}
// CHECK-LABEL: {{^}} func func12(a: PlainProtocol) {
@objc func func12_(a: PlainProtocol) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
func func13(a: Class_ObjC1) {}
// CHECK-LABEL: @objc func func13(a: Class_ObjC1) {
@objc func func13_(a: Class_ObjC1) {} // no-error
func func14(a: Protocol_Class1) {}
// CHECK-LABEL: {{^}} func func14(a: Protocol_Class1) {
@objc func func14_(a: Protocol_Class1) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
func func15(a: Protocol_ObjC1) {}
// CHECK-LABEL: @objc func func15(a: Protocol_ObjC1) {
@objc func func15_(a: Protocol_ObjC1) {} // no-error
func func16(a: AnyObject) {}
// CHECK-LABEL: @objc func func16(a: AnyObject) {
@objc func func16_(a: AnyObject) {} // no-error
func func17(a: @escaping () -> ()) {}
// CHECK-LABEL: {{^}} @objc func func17(a: @escaping () -> ()) {
@objc func func17_(a: @escaping () -> ()) {}
func func18(a: @escaping (Int) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func18(a: @escaping (Int) -> (), b: Int)
@objc func func18_(a: @escaping (Int) -> (), b: Int) {}
func func19(a: @escaping (String) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func19(a: @escaping (String) -> (), b: Int) {
@objc func func19_(a: @escaping (String) -> (), b: Int) {}
func func_FunctionReturn1() -> () -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn1() -> () -> () {
@objc func func_FunctionReturn1_() -> () -> () {}
func func_FunctionReturn2() -> (Int) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn2() -> (Int) -> () {
@objc func func_FunctionReturn2_() -> (Int) -> () {}
func func_FunctionReturn3() -> () -> Int {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn3() -> () -> Int {
@objc func func_FunctionReturn3_() -> () -> Int {}
func func_FunctionReturn4() -> (String) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn4() -> (String) -> () {
@objc func func_FunctionReturn4_() -> (String) -> () {}
func func_FunctionReturn5() -> () -> String {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn5() -> () -> String {
@objc func func_FunctionReturn5_() -> () -> String {}
func func_ZeroParams1() {}
// CHECK-LABEL: @objc func func_ZeroParams1() {
@objc func func_ZeroParams1a() {} // no-error
func func_OneParam1(a: Int) {}
// CHECK-LABEL: @objc func func_OneParam1(a: Int) {
@objc func func_OneParam1a(a: Int) {} // no-error
func func_TupleStyle1(a: Int, b: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle1(a: Int, b: Int) {
@objc func func_TupleStyle1a(a: Int, b: Int) {}
func func_TupleStyle2(a: Int, b: Int, c: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle2(a: Int, b: Int, c: Int) {
@objc func func_TupleStyle2a(a: Int, b: Int, c: Int) {}
// Check that we produce diagnostics for every parameter and return type.
@objc func func_MultipleDiags(a: PlainStruct, b: PlainEnum) -> Any {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter 1 cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-error@-3 {{method cannot be marked @objc because the type of the parameter 2 cannot be represented in Objective-C}}
// expected-note@-4 {{non-'@objc' enums cannot be represented in Objective-C}}
@objc func func_UnnamedParam1(_: Int) {} // no-error
@objc func func_UnnamedParam2(_: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
@objc func func_varParam1(a: AnyObject) {
var a = a
let b = a; a = b
}
func func_varParam2(a: AnyObject) {
var a = a
let b = a; a = b
}
// CHECK-LABEL: @objc func func_varParam2(a: AnyObject) {
}
@objc
class infer_constructor1 {
// CHECK-LABEL: @objc class infer_constructor1
init() {}
// CHECK: @objc init()
init(a: Int) {}
// CHECK: @objc init(a: Int)
init(a: PlainStruct) {}
// CHECK: {{^}} init(a: PlainStruct)
init(malice: ()) {}
// CHECK: @objc init(malice: ())
init(forMurder _: ()) {}
// CHECK: @objc init(forMurder _: ())
}
@objc
class infer_destructor1 {
// CHECK-LABEL: @objc class infer_destructor1
deinit {}
// CHECK: @objc deinit
}
// @!objc
class infer_destructor2 {
// CHECK-LABEL: {{^}}class infer_destructor2
deinit {}
// CHECK: @objc deinit
}
@objc
class infer_instanceVar1 {
// CHECK-LABEL: @objc class infer_instanceVar1 {
init() {}
var instanceVar1: Int
// CHECK: @objc var instanceVar1: Int
var (instanceVar2, instanceVar3): (Int, PlainProtocol)
// CHECK: @objc var instanceVar2: Int
// CHECK: {{^}} var instanceVar3: PlainProtocol
@objc var (instanceVar1_, instanceVar2_): (Int, PlainProtocol)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var intstanceVar4: Int {
// CHECK: @objc var intstanceVar4: Int {
get {}
// CHECK-NEXT: @objc get {}
}
var intstanceVar5: Int {
// CHECK: @objc var intstanceVar5: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
@objc var instanceVar5_: Int {
// CHECK: @objc var instanceVar5_: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
var observingAccessorsVar1: Int {
// CHECK: @objc var observingAccessorsVar1: Int {
willSet {}
// CHECK-NEXT: {{^}} willSet {}
didSet {}
// CHECK-NEXT: {{^}} didSet {}
}
@objc var observingAccessorsVar1_: Int {
// CHECK: {{^}} @objc var observingAccessorsVar1_: Int {
willSet {}
// CHECK-NEXT: {{^}} willSet {}
didSet {}
// CHECK-NEXT: {{^}} didSet {}
}
var var_Int: Int
// CHECK-LABEL: @objc var var_Int: Int
var var_Bool: Bool
// CHECK-LABEL: @objc var var_Bool: Bool
var var_CBool: CBool
// CHECK-LABEL: @objc var var_CBool: CBool
var var_String: String
// CHECK-LABEL: @objc var var_String: String
var var_Float: Float
var var_Double: Double
// CHECK-LABEL: @objc var var_Float: Float
// CHECK-LABEL: @objc var var_Double: Double
var var_Char: Unicode.Scalar
// CHECK-LABEL: @objc var var_Char: Unicode.Scalar
//===--- Tuples.
var var_tuple1: ()
// CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple1: ()
@objc var var_tuple1_: ()
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple2: Void
// CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple2: Void
@objc var var_tuple2_: Void
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple3: (Int)
// CHECK-LABEL: @objc var var_tuple3: (Int)
@objc var var_tuple3_: (Int) // no-error
var var_tuple4: (Int, Int)
// CHECK-LABEL: {{^}} var var_tuple4: (Int, Int)
@objc var var_tuple4_: (Int, Int)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{tuples cannot be represented in Objective-C}}
//===--- Stdlib integer types.
var var_Int8: Int8
var var_Int16: Int16
var var_Int32: Int32
var var_Int64: Int64
// CHECK-LABEL: @objc var var_Int8: Int8
// CHECK-LABEL: @objc var var_Int16: Int16
// CHECK-LABEL: @objc var var_Int32: Int32
// CHECK-LABEL: @objc var var_Int64: Int64
var var_UInt8: UInt8
var var_UInt16: UInt16
var var_UInt32: UInt32
var var_UInt64: UInt64
// CHECK-LABEL: @objc var var_UInt8: UInt8
// CHECK-LABEL: @objc var var_UInt16: UInt16
// CHECK-LABEL: @objc var var_UInt32: UInt32
// CHECK-LABEL: @objc var var_UInt64: UInt64
var var_OpaquePointer: OpaquePointer
// CHECK-LABEL: @objc var var_OpaquePointer: OpaquePointer
var var_PlainClass: PlainClass
// CHECK-LABEL: {{^}} var var_PlainClass: PlainClass
@objc var var_PlainClass_: PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
var var_PlainStruct: PlainStruct
// CHECK-LABEL: {{^}} var var_PlainStruct: PlainStruct
@objc var var_PlainStruct_: PlainStruct
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
var var_PlainEnum: PlainEnum
// CHECK-LABEL: {{^}} var var_PlainEnum: PlainEnum
@objc var var_PlainEnum_: PlainEnum
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
var var_PlainProtocol: PlainProtocol
// CHECK-LABEL: {{^}} var var_PlainProtocol: PlainProtocol
@objc var var_PlainProtocol_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_ClassObjC: Class_ObjC1
// CHECK-LABEL: @objc var var_ClassObjC: Class_ObjC1
@objc var var_ClassObjC_: Class_ObjC1 // no-error
var var_ProtocolClass: Protocol_Class1
// CHECK-LABEL: {{^}} var var_ProtocolClass: Protocol_Class1
@objc var var_ProtocolClass_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_ProtocolObjC: Protocol_ObjC1
// CHECK-LABEL: @objc var var_ProtocolObjC: Protocol_ObjC1
@objc var var_ProtocolObjC_: Protocol_ObjC1 // no-error
var var_PlainClassMetatype: PlainClass.Type
// CHECK-LABEL: {{^}} var var_PlainClassMetatype: PlainClass.Type
@objc var var_PlainClassMetatype_: PlainClass.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainStructMetatype: PlainStruct.Type
// CHECK-LABEL: {{^}} var var_PlainStructMetatype: PlainStruct.Type
@objc var var_PlainStructMetatype_: PlainStruct.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainEnumMetatype: PlainEnum.Type
// CHECK-LABEL: {{^}} var var_PlainEnumMetatype: PlainEnum.Type
@objc var var_PlainEnumMetatype_: PlainEnum.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainExistentialMetatype: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_PlainExistentialMetatype: PlainProtocol.Type
@objc var var_PlainExistentialMetatype_: PlainProtocol.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ClassObjCMetatype: Class_ObjC1.Type
// CHECK-LABEL: @objc var var_ClassObjCMetatype: Class_ObjC1.Type
@objc var var_ClassObjCMetatype_: Class_ObjC1.Type // no-error
var var_ProtocolClassMetatype: Protocol_Class1.Type
// CHECK-LABEL: {{^}} var var_ProtocolClassMetatype: Protocol_Class1.Type
@objc var var_ProtocolClassMetatype_: Protocol_Class1.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
@objc var var_ProtocolObjCMetatype1_: Protocol_ObjC1.Type // no-error
var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
@objc var var_ProtocolObjCMetatype2_: Protocol_ObjC2.Type // no-error
var var_AnyObject1: AnyObject
var var_AnyObject2: AnyObject.Type
// CHECK-LABEL: @objc var var_AnyObject1: AnyObject
// CHECK-LABEL: @objc var var_AnyObject2: AnyObject.Type
var var_Existential0: Any
// CHECK-LABEL: @objc var var_Existential0: Any
@objc var var_Existential0_: Any
var var_Existential1: PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential1: PlainProtocol
@objc var var_Existential1_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential2: PlainProtocol & PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential2: PlainProtocol
@objc var var_Existential2_: PlainProtocol & PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential3: PlainProtocol & Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential3: PlainProtocol & Protocol_Class1
@objc var var_Existential3_: PlainProtocol & Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential4: PlainProtocol & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential4: PlainProtocol & Protocol_ObjC1
@objc var var_Existential4_: PlainProtocol & Protocol_ObjC1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential5: Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential5: Protocol_Class1
@objc var var_Existential5_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential6: Protocol_Class1 & Protocol_Class2
// CHECK-LABEL: {{^}} var var_Existential6: Protocol_Class1 & Protocol_Class2
@objc var var_Existential6_: Protocol_Class1 & Protocol_Class2
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential7: Protocol_Class1 & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential7: Protocol_Class1 & Protocol_ObjC1
@objc var var_Existential7_: Protocol_Class1 & Protocol_ObjC1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential8: Protocol_ObjC1
// CHECK-LABEL: @objc var var_Existential8: Protocol_ObjC1
@objc var var_Existential8_: Protocol_ObjC1 // no-error
var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
@objc var var_Existential9_: Protocol_ObjC1 & Protocol_ObjC2 // no-error
var var_ExistentialMetatype0: Any.Type
var var_ExistentialMetatype1: PlainProtocol.Type
var var_ExistentialMetatype2: (PlainProtocol & PlainProtocol).Type
var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
var var_ExistentialMetatype5: (Protocol_Class1).Type
var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
var var_ExistentialMetatype8: Protocol_ObjC1.Type
var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype0: Any.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype1: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype2: (PlainProtocol).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype5: (Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
// CHECK-LABEL: @objc var var_ExistentialMetatype8: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
// CHECK-LABEL: var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
var var_Optional1: Class_ObjC1?
var var_Optional2: Protocol_ObjC1?
var var_Optional3: Class_ObjC1.Type?
var var_Optional4: Protocol_ObjC1.Type?
var var_Optional5: AnyObject?
var var_Optional6: AnyObject.Type?
var var_Optional7: String?
var var_Optional8: Protocol_ObjC1?
var var_Optional9: Protocol_ObjC1.Type?
var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
var var_Optional12: OpaquePointer?
var var_Optional13: UnsafeMutablePointer<Int>?
var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional1: Class_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional2: Protocol_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional3: Class_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional4: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional5: AnyObject?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional6: AnyObject.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional7: String?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional8: Protocol_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional9: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional12: OpaquePointer?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional13: UnsafeMutablePointer<Int>?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional5: AnyObject!
var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
var var_ImplicitlyUnwrappedOptional7: String!
var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional5: AnyObject!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional7: String!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
var var_Optional_fail1: PlainClass?
var var_Optional_fail2: PlainClass.Type?
var var_Optional_fail3: PlainClass!
var var_Optional_fail4: PlainStruct?
var var_Optional_fail5: PlainStruct.Type?
var var_Optional_fail6: PlainEnum?
var var_Optional_fail7: PlainEnum.Type?
var var_Optional_fail8: PlainProtocol?
var var_Optional_fail10: PlainProtocol?
var var_Optional_fail11: (PlainProtocol & Protocol_ObjC1)?
var var_Optional_fail12: Int?
var var_Optional_fail13: Bool?
var var_Optional_fail14: CBool?
var var_Optional_fail20: AnyObject??
var var_Optional_fail21: AnyObject.Type??
var var_Optional_fail22: ComparisonResult? // a non-bridged imported value type
var var_Optional_fail23: NSRange? // a bridged struct imported from C
// CHECK-NOT: @objc{{.*}}Optional_fail
// CHECK-LABEL: @objc var var_CFunctionPointer_1: @convention(c) () -> ()
var var_CFunctionPointer_1: @convention(c) () -> ()
// CHECK-LABEL: @objc var var_CFunctionPointer_invalid_1: Int
var var_CFunctionPointer_invalid_1: @convention(c) Int // expected-error {{@convention attribute only applies to function types}}
// CHECK-LABEL: {{^}} var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int
var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int // expected-error {{'(PlainStruct) -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
// <rdar://problem/20918869> Confusing diagnostic for @convention(c) throws
var var_CFunctionPointer_invalid_3 : @convention(c) (Int) throws -> Int // expected-error {{'(Int) throws -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
weak var var_Weak1: Class_ObjC1?
weak var var_Weak2: Protocol_ObjC1?
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//weak var var_Weak3: Class_ObjC1.Type?
//weak var var_Weak4: Protocol_ObjC1.Type?
weak var var_Weak5: AnyObject?
//weak var var_Weak6: AnyObject.Type?
weak var var_Weak7: Protocol_ObjC1?
weak var var_Weak8: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak1: @sil_weak Class_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak2: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak5: @sil_weak AnyObject
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak7: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak8: @sil_weak (Protocol_ObjC1 & Protocol_ObjC2)?
weak var var_Weak_fail1: PlainClass?
weak var var_Weak_bad2: PlainStruct?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
weak var var_Weak_bad3: PlainEnum?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
weak var var_Weak_bad4: String?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Weak_fail
unowned var var_Unowned1: Class_ObjC1
unowned var var_Unowned2: Protocol_ObjC1
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//unowned var var_Unowned3: Class_ObjC1.Type
//unowned var var_Unowned4: Protocol_ObjC1.Type
unowned var var_Unowned5: AnyObject
//unowned var var_Unowned6: AnyObject.Type
unowned var var_Unowned7: Protocol_ObjC1
unowned var var_Unowned8: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc unowned var var_Unowned1: @sil_unowned Class_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned2: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned5: @sil_unowned AnyObject
// CHECK-LABEL: @objc unowned var var_Unowned7: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned8: @sil_unowned Protocol_ObjC1 & Protocol_ObjC2
unowned var var_Unowned_fail1: PlainClass
unowned var var_Unowned_bad2: PlainStruct
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
unowned var var_Unowned_bad3: PlainEnum
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
unowned var var_Unowned_bad4: String
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Unowned_fail
var var_FunctionType1: () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType1: () -> ()
var var_FunctionType2: (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType2: (Int) -> ()
var var_FunctionType3: (Int) -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionType3: (Int) -> Int
var var_FunctionType4: (Int, Double) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType4: (Int, Double) -> ()
var var_FunctionType5: (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType5: (String) -> ()
var var_FunctionType6: () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionType6: () -> String
var var_FunctionType7: (PlainClass) -> ()
// CHECK-NOT: @objc var var_FunctionType7: (PlainClass) -> ()
var var_FunctionType8: () -> PlainClass
// CHECK-NOT: @objc var var_FunctionType8: () -> PlainClass
var var_FunctionType9: (PlainStruct) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType9: (PlainStruct) -> ()
var var_FunctionType10: () -> PlainStruct
// CHECK-LABEL: {{^}} var var_FunctionType10: () -> PlainStruct
var var_FunctionType11: (PlainEnum) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType11: (PlainEnum) -> ()
var var_FunctionType12: (PlainProtocol) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType12: (PlainProtocol) -> ()
var var_FunctionType13: (Class_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType13: (Class_ObjC1) -> ()
var var_FunctionType14: (Protocol_Class1) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType14: (Protocol_Class1) -> ()
var var_FunctionType15: (Protocol_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType15: (Protocol_ObjC1) -> ()
var var_FunctionType16: (AnyObject) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType16: (AnyObject) -> ()
var var_FunctionType17: (() -> ()) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType17: (() -> ()) -> ()
var var_FunctionType18: ((Int) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType18: ((Int) -> (), Int) -> ()
var var_FunctionType19: ((String) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType19: ((String) -> (), Int) -> ()
var var_FunctionTypeReturn1: () -> () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn1: () -> () -> ()
@objc var var_FunctionTypeReturn1_: () -> () -> () // no-error
var var_FunctionTypeReturn2: () -> (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn2: () -> (Int) -> ()
@objc var var_FunctionTypeReturn2_: () -> (Int) -> () // no-error
var var_FunctionTypeReturn3: () -> () -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn3: () -> () -> Int
@objc var var_FunctionTypeReturn3_: () -> () -> Int // no-error
var var_FunctionTypeReturn4: () -> (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn4: () -> (String) -> ()
@objc var var_FunctionTypeReturn4_: () -> (String) -> () // no-error
var var_FunctionTypeReturn5: () -> () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn5: () -> () -> String
@objc var var_FunctionTypeReturn5_: () -> () -> String // no-error
var var_BlockFunctionType1: @convention(block) () -> ()
// CHECK-LABEL: @objc var var_BlockFunctionType1: @convention(block) () -> ()
@objc var var_BlockFunctionType1_: @convention(block) () -> () // no-error
var var_ArrayType1: [AnyObject]
// CHECK-LABEL: {{^}} @objc var var_ArrayType1: [AnyObject]
@objc var var_ArrayType1_: [AnyObject] // no-error
var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject]
@objc var var_ArrayType2_: [@convention(block) (AnyObject) -> AnyObject] // no-error
var var_ArrayType3: [PlainStruct]
// CHECK-LABEL: {{^}} var var_ArrayType3: [PlainStruct]
@objc var var_ArrayType3_: [PlainStruct]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType4: [(AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType4: [(AnyObject) -> AnyObject]
@objc var var_ArrayType4_: [(AnyObject) -> AnyObject]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType5: [Protocol_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType5: [Protocol_ObjC1]
@objc var var_ArrayType5_: [Protocol_ObjC1] // no-error
var var_ArrayType6: [Class_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType6: [Class_ObjC1]
@objc var var_ArrayType6_: [Class_ObjC1] // no-error
var var_ArrayType7: [PlainClass]
// CHECK-LABEL: {{^}} var var_ArrayType7: [PlainClass]
@objc var var_ArrayType7_: [PlainClass]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType8: [PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType8: [PlainProtocol]
@objc var var_ArrayType8_: [PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType9: [Protocol_ObjC1 & PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType9: [PlainProtocol & Protocol_ObjC1]
@objc var var_ArrayType9_: [Protocol_ObjC1 & PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
// CHECK-LABEL: {{^}} @objc var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
@objc var var_ArrayType10_: [Protocol_ObjC1 & Protocol_ObjC2]
// no-error
var var_ArrayType11: [Any]
// CHECK-LABEL: @objc var var_ArrayType11: [Any]
@objc var var_ArrayType11_: [Any]
var var_ArrayType13: [Any?]
// CHECK-LABEL: {{^}} var var_ArrayType13: [Any?]
@objc var var_ArrayType13_: [Any?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType15: [AnyObject?]
// CHECK-LABEL: {{^}} var var_ArrayType15: [AnyObject?]
@objc var var_ArrayType15_: [AnyObject?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType16: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType16: {{\[}}[@convention(block) (AnyObject) -> AnyObject]]
@objc var var_ArrayType16_: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
var var_ArrayType17: [[(AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType17: {{\[}}[(AnyObject) -> AnyObject]]
@objc var var_ArrayType17_: [[(AnyObject) -> AnyObject]]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
}
@objc
class ObjCBase {}
class infer_instanceVar2<
GP_Unconstrained,
GP_PlainClass : PlainClass,
GP_PlainProtocol : PlainProtocol,
GP_Class_ObjC : Class_ObjC1,
GP_Protocol_Class : Protocol_Class1,
GP_Protocol_ObjC : Protocol_ObjC1> : ObjCBase {
// CHECK-LABEL: class infer_instanceVar2<{{.*}}> : ObjCBase where {{.*}} {
override init() {}
var var_GP_Unconstrained: GP_Unconstrained
// CHECK-LABEL: {{^}} var var_GP_Unconstrained: GP_Unconstrained
@objc var var_GP_Unconstrained_: GP_Unconstrained
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainClass: GP_PlainClass
// CHECK-LABEL: {{^}} var var_GP_PlainClass: GP_PlainClass
@objc var var_GP_PlainClass_: GP_PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainProtocol: GP_PlainProtocol
// CHECK-LABEL: {{^}} var var_GP_PlainProtocol: GP_PlainProtocol
@objc var var_GP_PlainProtocol_: GP_PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Class_ObjC: GP_Class_ObjC
// CHECK-LABEL: {{^}} var var_GP_Class_ObjC: GP_Class_ObjC
@objc var var_GP_Class_ObjC_: GP_Class_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_Class: GP_Protocol_Class
// CHECK-LABEL: {{^}} var var_GP_Protocol_Class: GP_Protocol_Class
@objc var var_GP_Protocol_Class_: GP_Protocol_Class
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_ObjC: GP_Protocol_ObjC
// CHECK-LABEL: {{^}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC
@objc var var_GP_Protocol_ObjCa: GP_Protocol_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
func func_GP_Unconstrained(a: GP_Unconstrained) {}
// CHECK-LABEL: {{^}} func func_GP_Unconstrained(a: GP_Unconstrained) {
@objc func func_GP_Unconstrained_(a: GP_Unconstrained) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
@objc func func_GP_Unconstrained_() -> GP_Unconstrained {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
@objc func func_GP_Class_ObjC__() -> GP_Class_ObjC {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
}
class infer_instanceVar3 : Class_ObjC1 {
// CHECK-LABEL: @objc class infer_instanceVar3 : Class_ObjC1 {
var v1: Int = 0
// CHECK-LABEL: @objc @_hasInitialValue var v1: Int
}
@objc
protocol infer_instanceVar4 {
// CHECK-LABEL: @objc protocol infer_instanceVar4 {
var v1: Int { get }
// CHECK-LABEL: @objc var v1: Int { get }
}
// @!objc
class infer_instanceVar5 {
// CHECK-LABEL: {{^}}class infer_instanceVar5 {
@objc
var intstanceVar1: Int {
// CHECK: @objc var intstanceVar1: Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
class infer_staticVar1 {
// CHECK-LABEL: @objc class infer_staticVar1 {
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
// CHECK: @objc @_hasInitialValue class var staticVar1: Int
}
// @!objc
class infer_subscript1 {
// CHECK-LABEL: class infer_subscript1
@objc
subscript(i: Int) -> Int {
// CHECK: @objc subscript(i: Int) -> Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
protocol infer_throughConformanceProto1 {
// CHECK-LABEL: @objc protocol infer_throughConformanceProto1 {
func funcObjC1()
var varObjC1: Int { get }
var varObjC2: Int { get set }
// CHECK: @objc func funcObjC1()
// CHECK: @objc var varObjC1: Int { get }
// CHECK: @objc var varObjC2: Int { get set }
}
class infer_class1 : PlainClass {}
// CHECK-LABEL: {{^}}class infer_class1 : PlainClass {
class infer_class2 : Class_ObjC1 {}
// CHECK-LABEL: @objc class infer_class2 : Class_ObjC1 {
class infer_class3 : infer_class2 {}
// CHECK-LABEL: @objc class infer_class3 : infer_class2 {
class infer_class4 : Protocol_Class1 {}
// CHECK-LABEL: {{^}}class infer_class4 : Protocol_Class1 {
class infer_class5 : Protocol_ObjC1 {}
// CHECK-LABEL: {{^}}class infer_class5 : Protocol_ObjC1 {
//
// If a protocol conforms to an @objc protocol, this does not infer @objc on
// the protocol itself, or on the newly introduced requirements. Only the
// inherited @objc requirements get @objc.
//
// Same rule applies to classes.
//
protocol infer_protocol1 {
// CHECK-LABEL: {{^}}protocol infer_protocol1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol2 : Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol2 : Protocol_Class1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol3 : Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol3 : Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol5 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
class C {
// Don't crash.
@objc func foo(x: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}}
@IBAction func myAction(sender: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}}
}
//===---
//===--- @IBOutlet implies @objc
//===---
class HasIBOutlet {
// CHECK-LABEL: {{^}}class HasIBOutlet {
init() {}
@IBOutlet weak var goodOutlet: Class_ObjC1!
// CHECK-LABEL: {{^}} @objc @IBOutlet @_implicitly_unwrapped_optional @_hasInitialValue weak var goodOutlet: @sil_weak Class_ObjC1!
@IBOutlet var badOutlet: PlainStruct
// expected-error@-1 {{@IBOutlet property cannot have non-object type 'PlainStruct'}} {{3-13=}}
// expected-error@-2 {{@IBOutlet property has non-optional type 'PlainStruct'}}
// expected-note@-3 {{add '?' to form the optional type 'PlainStruct?'}}
// expected-note@-4 {{add '!' to form an implicitly unwrapped optional}}
// CHECK-LABEL: {{^}} @IBOutlet var badOutlet: PlainStruct
}
//===---
//===--- @IBAction implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBAction {
class HasIBAction {
@IBAction func goodAction(_ sender: AnyObject?) { }
// CHECK: {{^}} @objc @IBAction func goodAction(_ sender: AnyObject?) {
@IBAction func badAction(_ sender: PlainStruct?) { }
// expected-error@-1{{argument to @IBAction method cannot have non-object type 'PlainStruct?'}}
}
//===---
//===--- @IBInspectable implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBInspectable {
class HasIBInspectable {
@IBInspectable var goodProperty: AnyObject?
// CHECK: {{^}} @objc @IBInspectable @_hasInitialValue var goodProperty: AnyObject?
}
//===---
//===--- @GKInspectable implies @objc
//===---
// CHECK-LABEL: {{^}}class HasGKInspectable {
class HasGKInspectable {
@GKInspectable var goodProperty: AnyObject?
// CHECK: {{^}} @objc @GKInspectable @_hasInitialValue var goodProperty: AnyObject?
}
//===---
//===--- @NSManaged implies @objc
//===---
class HasNSManaged {
// CHECK-LABEL: {{^}}class HasNSManaged {
init() {}
@NSManaged
var goodManaged: Class_ObjC1
// CHECK-LABEL: {{^}} @objc @NSManaged dynamic var goodManaged: Class_ObjC1
@NSManaged
var badManaged: PlainStruct
// expected-error@-1 {{property cannot be marked @NSManaged because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-error@-3{{'dynamic' property 'badManaged' must also be '@objc'}}
// CHECK-LABEL: {{^}} @NSManaged var badManaged: PlainStruct
}
//===---
//===--- Pointer argument types
//===---
@objc class TakesCPointers {
// CHECK-LABEL: {{^}}@objc class TakesCPointers {
func constUnsafeMutablePointer(p: UnsafePointer<Int>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointer(p: UnsafePointer<Int>) {
func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {
func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {
func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {}
// CHECK-LABEL: @objc func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {
func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {
func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {
}
// @objc with nullary names
@objc(NSObjC2)
class Class_ObjC2 {
// CHECK-LABEL: @objc(NSObjC2) class Class_ObjC2
@objc(initWithMalice)
init(foo: ()) { }
@objc(initWithIntent)
init(bar _: ()) { }
@objc(initForMurder)
init() { }
@objc(isFoo)
func foo() -> Bool {}
// CHECK-LABEL: @objc(isFoo) func foo() -> Bool {
}
@objc() // expected-error{{expected name within parentheses of @objc attribute}}
class Class_ObjC3 {
}
// @objc with selector names
extension PlainClass {
// CHECK-LABEL: @objc(setFoo:) dynamic func
@objc(setFoo:)
func foo(b: Bool) { }
// CHECK-LABEL: @objc(setWithRed:green:blue:alpha:) dynamic func set
@objc(setWithRed:green:blue:alpha:)
func set(_: Float, green: Float, blue: Float, alpha: Float) { }
// CHECK-LABEL: @objc(createWithRed:green:blue:alpha:) dynamic class func createWith
@objc(createWithRed:green blue:alpha)
class func createWithRed(_: Float, green: Float, blue: Float, alpha: Float) { }
// expected-error@-2{{missing ':' after selector piece in @objc attribute}}{{28-28=:}}
// expected-error@-3{{missing ':' after selector piece in @objc attribute}}{{39-39=:}}
// CHECK-LABEL: @objc(::) dynamic func badlyNamed
@objc(::)
func badlyNamed(_: Int, y: Int) {}
}
@objc(Class:) // expected-error{{'@objc' class must have a simple name}}{{12-13=}}
class BadClass1 { }
@objc(Protocol:) // expected-error{{'@objc' protocol must have a simple name}}{{15-16=}}
protocol BadProto1 { }
@objc(Enum:) // expected-error{{'@objc' enum must have a simple name}}{{11-12=}}
enum BadEnum1: Int { case X }
@objc
enum BadEnum2: Int {
@objc(X:) // expected-error{{'@objc' enum case must have a simple name}}{{10-11=}}
case X
}
class BadClass2 {
@objc(realDealloc) // expected-error{{'@objc' deinitializer cannot have a name}}
deinit { }
@objc(badprop:foo:wibble:) // expected-error{{'@objc' property must have a simple name}}{{16-28=}}
var badprop: Int = 5
@objc(foo) // expected-error{{'@objc' subscript cannot have a name; did you mean to put the name on the getter or setter?}}
subscript (i: Int) -> Int {
get {
return i
}
}
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam(x: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam2(_: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters}}
func noArgNamesTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 2 parameters}}
func oneArgNameTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 0 parameters}}
func oneArgNameNoParams() { }
@objc(foo:) // expected-error{{'@objc' initializer name provides one argument name, but initializer has 0 parameters}}
init() { }
var _prop = 5
@objc var prop: Int {
@objc(property) get { return _prop }
@objc(setProperty:) set { _prop = newValue }
}
var prop2: Int {
@objc(property) get { return _prop } // expected-error{{'@objc' getter for non-'@objc' property}}
@objc(setProperty:) set { _prop = newValue } // expected-error{{'@objc' setter for non-'@objc' property}}
}
var prop3: Int {
@objc(setProperty:) didSet { } // expected-error{{observing accessors are not allowed to be marked @objc}} {{5-25=}}
}
@objc
subscript (c: Class_ObjC1) -> Class_ObjC1 {
@objc(getAtClass:) get {
return c
}
@objc(setAtClass:class:) set {
}
}
}
// Swift overrides that aren't also @objc overrides.
class Super {
@objc(renamedFoo)
var foo: Int { get { return 3 } } // expected-note 2{{overridden declaration is here}}
@objc func process(i: Int) -> Int { } // expected-note {{overriding '@objc' method 'process(i:)' here}}
}
class Sub1 : Super {
@objc(foo) // expected-error{{Objective-C property has a different name from the property it overrides ('foo' vs. 'renamedFoo')}}{{9-12=renamedFoo}}
override var foo: Int { get { return 5 } }
override func process(i: Int?) -> Int { } // expected-error{{method cannot be an @objc override because the type of the parameter cannot be represented in Objective-C}}
}
class Sub2 : Super {
@objc
override var foo: Int { get { return 5 } }
}
class Sub3 : Super {
override var foo: Int { get { return 5 } }
}
class Sub4 : Super {
@objc(renamedFoo)
override var foo: Int { get { return 5 } }
}
class Sub5 : Super {
@objc(wrongFoo) // expected-error{{Objective-C property has a different name from the property it overrides ('wrongFoo' vs. 'renamedFoo')}} {{9-17=renamedFoo}}
override var foo: Int { get { return 5 } }
}
enum NotObjCEnum { case X }
struct NotObjCStruct {}
// Closure arguments can only be @objc if their parameters and returns are.
// CHECK-LABEL: @objc class ClosureArguments
@objc class ClosureArguments {
// CHECK: @objc func foo
@objc func foo(f: (Int) -> ()) {}
// CHECK: @objc func bar
@objc func bar(f: (NotObjCEnum) -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func bas
@objc func bas(f: (NotObjCEnum) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zim
@objc func zim(f: () -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zang
@objc func zang(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
@objc func zangZang(f: (Int...) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func fooImplicit
func fooImplicit(f: (Int) -> ()) {}
// CHECK: {{^}} func barImplicit
func barImplicit(f: (NotObjCEnum) -> NotObjCStruct) {}
// CHECK: {{^}} func basImplicit
func basImplicit(f: (NotObjCEnum) -> ()) {}
// CHECK: {{^}} func zimImplicit
func zimImplicit(f: () -> NotObjCStruct) {}
// CHECK: {{^}} func zangImplicit
func zangImplicit(f: (NotObjCEnum, NotObjCStruct) -> ()) {}
// CHECK: {{^}} func zangZangImplicit
func zangZangImplicit(f: (Int...) -> ()) {}
}
typealias GoodBlock = @convention(block) (Int) -> ()
typealias BadBlock = @convention(block) (NotObjCEnum) -> () // expected-error{{'(NotObjCEnum) -> ()' is not representable in Objective-C, so it cannot be used with '@convention(block)'}}
@objc class AccessControl {
// CHECK: @objc func foo
func foo() {}
// CHECK: {{^}} private func bar
private func bar() {}
// CHECK: @objc private func baz
@objc private func baz() {}
}
//===--- Ban @objc +load methods
class Load1 {
// Okay: not @objc
class func load() { }
class func alloc() {}
class func allocWithZone(_: Int) {}
class func initialize() {}
}
@objc class Load2 {
class func load() { } // expected-error{{method 'load()' defines Objective-C class method 'load', which is not permitted by Swift}}
class func alloc() {} // expected-error{{method 'alloc()' defines Objective-C class method 'alloc', which is not permitted by Swift}}
class func allocWithZone(_: Int) {} // expected-error{{method 'allocWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
class func initialize() {} // expected-error{{method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}}
}
@objc class Load3 {
class var load: Load3 {
get { return Load3() } // expected-error{{getter for 'load' defines Objective-C class method 'load', which is not permitted by Swift}}
set { }
}
@objc(alloc) class var prop: Int { return 0 } // expected-error{{getter for 'prop' defines Objective-C class method 'alloc', which is not permitted by Swift}}
@objc(allocWithZone:) class func fooWithZone(_: Int) {} // expected-error{{method 'fooWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
@objc(initialize) class func barnitialize() {} // expected-error{{method 'barnitialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}}
}
// Members of protocol extensions cannot be @objc
extension PlainProtocol {
@objc var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
@objc var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
// Don't infer @objc for extensions of @objc protocols.
// CHECK: {{^}} var propertyOK: Int
var propertyOK: Int { return 5 }
}
//===---
//===--- Error handling
//===---
class ClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
@objc func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
@objc func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
@objc func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
@objc func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: @objc init(degrees: Double) throws
@objc init(degrees: Double) throws { }
// Errors
@objc func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type 'Class_ObjC1?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsOptionalArray() throws -> [String]? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type '[String]?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsInt() throws -> Int { return 0 } // expected-error{{throwing method cannot be marked @objc because it returns a value of type 'Int'; return 'Void' or a type that bridges to an Objective-C class}}
@objc func methodAcceptsThrowingFunc(fn: (String) throws -> Int) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{throwing function types cannot be represented in Objective-C}}
@objc init?(radians: Double) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc init!(string: String) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc func fooWithErrorEnum1(x: ErrorEnum) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{non-'@objc' enums cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorEnum2(x: ErrorEnum)
func fooWithErrorEnum2(x: ErrorEnum) {}
@objc func fooWithErrorProtocolComposition1(x: Error & Protocol_ObjC1) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{protocol-constrained type containing 'Error' cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1)
func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1) { }
}
// CHECK-DUMP-LABEL: class_decl{{.*}}"ImplicitClassThrows1"
@objc class ImplicitClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
// CHECK-DUMP: func_decl{{.*}}"methodReturnsVoid()"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
// CHECK-DUMP: func_decl{{.*}}"methodReturnsObjCClass()" {{.*}}foreign_error=NilResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: {{^}} func methodReturnsOptionalObjCClass() throws -> Class_ObjC1?
func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil }
// CHECK: @objc func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int)
// CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int) throws { }
// CHECK: @objc init(degrees: Double) throws
// CHECK-DUMP: constructor_decl{{.*}}"init(degrees:)"{{.*}}foreign_error=NilResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
init(degrees: Double) throws { }
// CHECK: {{^}} func methodReturnsBridgedValueType() throws -> NSRange
func methodReturnsBridgedValueType() throws -> NSRange { return NSRange() }
@objc func methodReturnsBridgedValueType2() throws -> NSRange {
return NSRange()
}
// expected-error@-3{{throwing method cannot be marked @objc because it returns a value of type 'NSRange' (aka '_NSRange'); return 'Void' or a type that bridges to an Objective-C class}}
// CHECK: {{^}} @objc func methodReturnsError() throws -> Error
func methodReturnsError() throws -> Error { return ErrorEnum.failed }
// CHECK: @objc func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int)
func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int) {
func add(x: Int) -> (Int) -> Int {
return { x + $0 }
}
}
}
// CHECK-DUMP-LABEL: class_decl{{.*}}"SubclassImplicitClassThrows1"
@objc class SubclassImplicitClassThrows1 : ImplicitClassThrows1 {
// CHECK: @objc override func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping ((Int) -> Int), fn3: @escaping ((Int) -> Int))
// CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: (@escaping (Int) -> Int), fn3: (@escaping (Int) -> Int)) throws { }
}
class ThrowsRedecl1 {
@objc func method1(_ x: Int, error: Class_ObjC1) { } // expected-note{{declared here}}
@objc func method1(_ x: Int) throws { } // expected-error{{with Objective-C selector 'method1:error:'}}
@objc func method2AndReturnError(_ x: Int) { } // expected-note{{declared here}}
@objc func method2() throws { } // expected-error{{with Objective-C selector 'method2AndReturnError:'}}
@objc func method3(_ x: Int, error: Int, closure: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc func method3(_ x: Int, closure: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'method3:error:closure:'}}
@objc(initAndReturnError:) func initMethod1(error: Int) { } // expected-note{{declared here}}
@objc init() throws { } // expected-error{{with Objective-C selector 'initAndReturnError:'}}
@objc(initWithString:error:) func initMethod2(string: String, error: Int) { } // expected-note{{declared here}}
@objc init(string: String) throws { } // expected-error{{with Objective-C selector 'initWithString:error:'}}
@objc(initAndReturnError:fn:) func initMethod3(error: Int, fn: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc init(fn: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'initAndReturnError:fn:'}}
}
class ThrowsObjCName {
@objc(method4:closure:error:) func method4(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method5AndReturnError:x:closure:) func method5(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method6) func method6() throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has one parameter (the error parameter)}}
@objc(method7) func method7(x: Int) throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has 2 parameters (including the error parameter)}}
// CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method8:fn1:error:fn2:)
func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method9AndReturnError:s:fn1:fn2:)
func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
class SubclassThrowsObjCName : ThrowsObjCName {
// CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
@objc protocol ProtocolThrowsObjCName {
@objc optional func doThing(_ x: String) throws -> String // expected-note{{requirement 'doThing' declared here}}
}
class ConformsToProtocolThrowsObjCName1 : ProtocolThrowsObjCName {
@objc func doThing(_ x: String) throws -> String { return x } // okay
}
class ConformsToProtocolThrowsObjCName2 : ProtocolThrowsObjCName {
@objc func doThing(_ x: Int) throws -> String { return "" }
// expected-warning@-1{{instance method 'doThing' nearly matches optional requirement 'doThing' of protocol 'ProtocolThrowsObjCName'}}
// expected-note@-2{{move 'doThing' to an extension to silence this warning}}
// expected-note@-3{{make 'doThing' private to silence this warning}}{{9-9=private }}
// expected-note@-4{{candidate has non-matching type '(Int) throws -> String'}}
}
@objc class DictionaryTest {
// CHECK-LABEL: @objc func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>)
func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
// CHECK-LABEL: @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>)
@objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
func func_dictionary2a(x: Dictionary<String, Int>) { }
@objc func func_dictionary2b(x: Dictionary<String, Int>) { }
}
@objc extension PlainClass {
// CHECK-LABEL: @objc final func objc_ext_objc_okay(_: Int) {
final func objc_ext_objc_okay(_: Int) { }
final func objc_ext_objc_not_okay(_: PlainStruct) { }
// expected-error@-1{{method cannot be in an @objc extension of a class (without @nonobjc) because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// CHECK-LABEL: {{^}} @nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) {
@nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) { }
}
@objc class ObjC_Class1 : Hashable {
var hashValue: Int { return 0 }
}
func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool {
return true
}
// CHECK-LABEL: @objc class OperatorInClass
@objc class OperatorInClass {
// CHECK: {{^}} static func == (lhs: OperatorInClass, rhs: OperatorInClass) -> Bool
static func ==(lhs: OperatorInClass, rhs: OperatorInClass) -> Bool {
return true
}
// CHECK: {{^}} @objc static func + (lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass
@objc static func +(lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass { // expected-error {{operator methods cannot be declared @objc}}
return lhs
}
} // CHECK: {{^}$}}
@objc protocol OperatorInProtocol {
static func +(lhs: Self, rhs: Self) -> Self // expected-error {{@objc protocols must not have operator requirements}}
}
class AdoptsOperatorInProtocol : OperatorInProtocol {
static func +(lhs: AdoptsOperatorInProtocol, rhs: AdoptsOperatorInProtocol) -> Self {}
// expected-error@-1 {{operator methods cannot be declared @objc}}
}
//===--- @objc inference for witnesses
@objc protocol InferFromProtocol {
@objc(inferFromProtoMethod1:)
optional func method1(value: Int)
}
// Infer when in the same declaration context.
// CHECK-LABEL: ClassInfersFromProtocol1
class ClassInfersFromProtocol1 : InferFromProtocol{
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
// Infer when in a different declaration context of the same class.
// CHECK-LABEL: ClassInfersFromProtocol2a
class ClassInfersFromProtocol2a {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
extension ClassInfersFromProtocol2a : InferFromProtocol { }
// Infer when in a different declaration context of the same class.
class ClassInfersFromProtocol2b : InferFromProtocol { }
// CHECK-LABEL: ClassInfersFromProtocol2b
extension ClassInfersFromProtocol2b {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
// Don't infer when there is a signature mismatch.
// CHECK-LABEL: ClassInfersFromProtocol3
class ClassInfersFromProtocol3 : InferFromProtocol {
}
extension ClassInfersFromProtocol3 {
// CHECK: {{^}} func method1(value: String)
func method1(value: String) { }
}
// Inference for subclasses.
class SuperclassImplementsProtocol : InferFromProtocol { }
class SubclassInfersFromProtocol1 : SuperclassImplementsProtocol {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
class SubclassInfersFromProtocol2 : SuperclassImplementsProtocol {
}
extension SubclassInfersFromProtocol2 {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
@objc class NeverReturningMethod {
@objc func doesNotReturn() -> Never {}
}
// SR-5025
class User: NSObject {
}
@objc extension User {
var name: String {
get {
return "No name"
}
set {
// Nothing
}
}
var other: String {
unsafeAddress { // expected-error{{addressors are not allowed to be marked @objc}}
}
}
}
// 'dynamic' methods cannot be @inlinable.
class BadClass {
@inlinable @objc dynamic func badMethod1() {}
// expected-error@-1 {{'@inlinable' attribute cannot be applied to 'dynamic' declarations}}
}
@objc
protocol ObjCProtocolWithWeakProperty {
weak var weakProp: AnyObject? { get set } // okay
}
@objc
protocol ObjCProtocolWithUnownedProperty {
unowned var unownedProp: AnyObject { get set } // okay
}
| apache-2.0 | 2a1e76f9f32f399a90a45afa309c1170 | 39.810225 | 350 | 0.7043 | 3.900046 | false | false | false | false |
zisko/swift | test/Prototypes/BigInt.swift | 2 | 54662 | //===--- BigInt.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
//
//===----------------------------------------------------------------------===//
// XFAIL: linux
// RUN: rm -rf %t ; mkdir -p %t
// RUN: %target-build-swift -swift-version 4 -o %t/a.out %s
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
// REQUIRES: CPU=x86_64
import StdlibUnittest
import Darwin
extension FixedWidthInteger {
/// Returns the high and low parts of a potentially overflowing addition.
func addingFullWidth(_ other: Self) ->
(high: Self, low: Self) {
let sum = self.addingReportingOverflow(other)
return (sum.overflow ? 1 : 0, sum.partialValue)
}
/// Returns the high and low parts of two seqeuential potentially overflowing
/// additions.
static func addingFullWidth(_ x: Self, _ y: Self, _ z: Self) ->
(high: Self, low: Self) {
let xy = x.addingReportingOverflow(y)
let xyz = xy.partialValue.addingReportingOverflow(z)
let high: Self = (xy.overflow ? 1 : 0) +
(xyz.overflow ? 1 : 0)
return (high, xyz.partialValue)
}
/// Returns a tuple containing the value that would be borrowed from a higher
/// place and the partial difference of this value and `rhs`.
func subtractingWithBorrow(_ rhs: Self) ->
(borrow: Self, partialValue: Self) {
let difference = subtractingReportingOverflow(rhs)
return (difference.overflow ? 1 : 0, difference.partialValue)
}
/// Returns a tuple containing the value that would be borrowed from a higher
/// place and the partial value of `x` and `y` subtracted from this value.
func subtractingWithBorrow(_ x: Self, _ y: Self) ->
(borrow: Self, partialValue: Self) {
let firstDifference = subtractingReportingOverflow(x)
let secondDifference =
firstDifference.partialValue.subtractingReportingOverflow(y)
let borrow: Self = (firstDifference.overflow ? 1 : 0) +
(secondDifference.overflow ? 1 : 0)
return (borrow, secondDifference.partialValue)
}
}
//===--- BigInt -----------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A dynamically-sized signed integer.
///
/// The `_BigInt` type is fully generic on the size of its "word" -- the
/// `BigInt` alias uses the system's word-sized `UInt` as its word type, but
/// any word size should work properly.
public struct _BigInt<Word: FixedWidthInteger & UnsignedInteger> :
BinaryInteger, SignedInteger, CustomStringConvertible,
CustomDebugStringConvertible
where Word.Magnitude == Word
{
/// The binary representation of the value's magnitude, with the least
/// significant word at index `0`.
///
/// - `_data` has no trailing zero elements
/// - If `self == 0`, then `isNegative == false` and `_data == []`
internal var _data: [Word] = []
/// A Boolean value indicating whether this instance is negative.
public private(set) var isNegative = false
/// A Boolean value indicating whether this instance is equal to zero.
public var isZero: Bool {
return _data.count == 0
}
//===--- Numeric initializers -------------------------------------------===//
/// Creates a new instance equal to zero.
public init() { }
/// Creates a new instance using `_data` as the data collection.
init<C: Collection>(_ _data: C) where C.Iterator.Element == Word {
self._data = Array(_data)
_standardize()
}
public init(integerLiteral value: Int) {
self.init(value)
}
public init<T : BinaryInteger>(_ source: T) {
var source = source
if source < 0 as T {
if source.bitWidth <= UInt64.bitWidth {
let sourceMag = Int(truncatingIfNeeded: source).magnitude
self = _BigInt(sourceMag)
self.isNegative = true
return
} else {
// Have to kind of assume that we're working with another BigInt here
self.isNegative = true
source *= -1
}
}
// FIXME: This is broken on 32-bit arch w/ Word = UInt64
let wordRatio = UInt.bitWidth / Word.bitWidth
_sanityCheck(wordRatio != 0)
for var sourceWord in source.words {
for _ in 0..<wordRatio {
_data.append(Word(truncatingIfNeeded: sourceWord))
sourceWord >>= Word.bitWidth
}
}
_standardize()
}
public init?<T : BinaryInteger>(exactly source: T) {
self.init(source)
}
public init<T : BinaryInteger>(truncatingIfNeeded source: T) {
self.init(source)
}
public init<T : BinaryInteger>(clamping source: T) {
self.init(source)
}
public init<T : BinaryFloatingPoint>(_ source: T) {
fatalError("Not implemented")
}
public init?<T : BinaryFloatingPoint>(exactly source: T) {
fatalError("Not implemented")
}
/// Returns a randomly-generated word.
static func _randomWord() -> Word {
// This handles up to a 64-bit word
if Word.bitWidth > UInt32.bitWidth {
return Word(arc4random()) << 32 | Word(arc4random())
} else {
return Word(truncatingIfNeeded: arc4random())
}
}
/// Creates a new instance whose magnitude has `randomBits` bits of random
/// data. The sign of the new value is randomly selected.
public init(randomBits: Int) {
let (words, extraBits) =
randomBits.quotientAndRemainder(dividingBy: Word.bitWidth)
// Get the bits for any full words.
self._data = (0..<words).map({ _ in _BigInt._randomWord() })
// Get another random number - the highest bit will determine the sign,
// while the lower `Word.bitWidth - 1` bits are available for any leftover
// bits in `randomBits`.
let word = _BigInt._randomWord()
if extraBits != 0 {
let mask = ~((~0 as Word) << Word(extraBits))
_data.append(word & mask)
}
isNegative = word & ~(~0 >> 1) == 0
_standardize()
}
//===--- Private methods ------------------------------------------------===//
/// Standardizes this instance after mutation, removing trailing zeros
/// and making sure zero is nonnegative. Calling this method satisfies the
/// two invariants.
mutating func _standardize(source: String = #function) {
defer { _checkInvariants(source: source + " >> _standardize()") }
while _data.last == 0 {
_data.removeLast()
}
// Zero is never negative.
isNegative = isNegative && _data.count != 0
}
/// Checks and asserts on invariants -- all invariants must be satisfied
/// at the end of every mutating method.
///
/// - `_data` has no trailing zero elements
/// - If `self == 0`, then `isNegative == false`
func _checkInvariants(source: String = #function) {
if _data.count == 0 {
assert(isNegative == false,
"\(source): isNegative with zero length _data")
}
assert(_data.last != 0, "\(source): extra zeroes on _data")
}
//===--- Word-based arithmetic ------------------------------------------===//
mutating func _unsignedAdd(_ rhs: Word) {
defer { _standardize() }
// Quick return if `rhs == 0`
guard rhs != 0 else { return }
// Quick return if `self == 0`
if isZero {
_data.append(rhs)
return
}
// Add `rhs` to the first word, catching any carry.
var carry: Word
(carry, _data[0]) = _data[0].addingFullWidth(rhs)
// Handle any additional carries
for i in 1..<_data.count {
// No more action needed if there's nothing to carry
if carry == 0 { break }
(carry, _data[i]) = _data[i].addingFullWidth(carry)
}
// If there's any carry left, add it now
if carry != 0 {
_data.append(1)
}
}
/// Subtracts `rhs` from this instance, ignoring the sign.
///
/// - Precondition: `rhs <= self.magnitude`
mutating func _unsignedSubtract(_ rhs: Word) {
_precondition(_data.count > 1 || _data[0] > rhs)
// Quick return if `rhs == 0`
guard rhs != 0 else { return }
// If `isZero == true`, then `rhs` must also be zero.
_precondition(!isZero)
var carry: Word
(carry, _data[0]) = _data[0].subtractingWithBorrow(rhs)
for i in 1..<_data.count {
// No more action needed if there's nothing to carry
if carry == 0 { break }
(carry, _data[i]) = _data[i].subtractingWithBorrow(carry)
}
_sanityCheck(carry == 0)
_standardize()
}
/// Adds `rhs` to this instance.
mutating func add(_ rhs: Word) {
if isNegative {
// If _data only contains one word and `rhs` is greater, swap them,
// make self positive and continue with unsigned subtraction.
var rhs = rhs
if _data.count == 1 && _data[0] < rhs {
swap(&rhs, &_data[0])
isNegative = false
}
_unsignedSubtract(rhs)
} else { // positive or zero
_unsignedAdd(rhs)
}
}
/// Subtracts `rhs` from this instance.
mutating func subtract(_ rhs: Word) {
guard rhs != 0 else { return }
if isNegative {
_unsignedAdd(rhs)
} else if isZero {
isNegative = true
_data.append(rhs)
} else {
var rhs = rhs
if _data.count == 1 && _data[0] < rhs {
swap(&rhs, &_data[0])
isNegative = true
}
_unsignedSubtract(rhs)
}
}
/// Multiplies this instance by `rhs`.
mutating func multiply(by rhs: Word) {
// If either `self` or `rhs` is zero, the result is zero.
guard !isZero && rhs != 0 else {
self = 0
return
}
// If `rhs` is a power of two, can just left shift `self`.
let rhsLSB = rhs.trailingZeroBitCount
if rhs >> rhsLSB == 1 {
self <<= rhsLSB
return
}
var carry: Word = 0
for i in 0..<_data.count {
let product = _data[i].multipliedFullWidth(by: rhs)
(carry, _data[i]) = product.low.addingFullWidth(carry)
carry = carry &+ product.high
}
// Add the leftover carry
if carry != 0 {
_data.append(carry)
}
_standardize()
}
/// Divides this instance by `rhs`, returning the remainder.
@discardableResult
mutating func divide(by rhs: Word) -> Word {
_precondition(rhs != 0, "divide by zero")
// No-op if `rhs == 1` or `self == 0`.
if rhs == 1 || isZero {
return 0
}
// If `rhs` is a power of two, can just right shift `self`.
let rhsLSB = rhs.trailingZeroBitCount
if rhs >> rhsLSB == 1 {
defer { self >>= rhsLSB }
return _data[0] & ~(~0 << rhsLSB)
}
var carry: Word = 0
for i in (0..<_data.count).reversed() {
let lhs = (high: carry, low: _data[i])
(_data[i], carry) = rhs.dividingFullWidth(lhs)
}
_standardize()
return carry
}
//===--- Numeric --------------------------------------------------------===//
public typealias Magnitude = _BigInt
public var magnitude: _BigInt {
var result = self
result.isNegative = false
return result
}
/// Adds `rhs` to this instance, ignoring any signs.
mutating func _unsignedAdd(_ rhs: _BigInt) {
defer { _checkInvariants() }
let commonCount = Swift.min(_data.count, rhs._data.count)
let maxCount = Swift.max(_data.count, rhs._data.count)
_data.reserveCapacity(maxCount)
// Add the words up to the common count, carrying any overflows
var carry: Word = 0
for i in 0..<commonCount {
(carry, _data[i]) = Word.addingFullWidth(_data[i], rhs._data[i], carry)
}
// If there are leftover words in `self`, just need to handle any carries
if _data.count > rhs._data.count {
for i in commonCount..<maxCount {
// No more action needed if there's nothing to carry
if carry == 0 { break }
(carry, _data[i]) = _data[i].addingFullWidth(carry)
}
// If there are leftover words in `rhs`, need to copy to `self` with carries
} else if _data.count < rhs._data.count {
for i in commonCount..<maxCount {
// Append remaining words if nothing to carry
if carry == 0 {
_data.append(contentsOf: rhs._data.suffix(from: i))
break
}
let sum: Word
(carry, sum) = rhs._data[i].addingFullWidth(carry)
_data.append(sum)
}
}
// If there's any carry left, add it now
if carry != 0 {
_data.append(1)
}
}
/// Subtracts `rhs` from this instance, ignoring the sign.
///
/// - Precondition: `rhs.magnitude <= self.magnitude` (unchecked)
/// - Precondition: `rhs._data.count <= self._data.count`
mutating func _unsignedSubtract(_ rhs: _BigInt) {
_precondition(rhs._data.count <= _data.count)
var carry: Word = 0
for i in 0..<rhs._data.count {
(carry, _data[i]) = _data[i].subtractingWithBorrow(rhs._data[i], carry)
}
for i in rhs._data.count..<_data.count {
// No more action needed if there's nothing to carry
if carry == 0 { break }
(carry, _data[i]) = _data[i].subtractingWithBorrow(carry)
}
_sanityCheck(carry == 0)
_standardize()
}
public static func +=(lhs: inout _BigInt, rhs: _BigInt) {
defer { lhs._checkInvariants() }
if lhs.isNegative == rhs.isNegative {
lhs._unsignedAdd(rhs)
} else {
lhs -= -rhs
}
}
public static func -=(lhs: inout _BigInt, rhs: _BigInt) {
defer { lhs._checkInvariants() }
// Subtracting something of the opposite sign just adds magnitude.
guard lhs.isNegative == rhs.isNegative else {
lhs._unsignedAdd(rhs)
return
}
// Comare `lhs` and `rhs` so we can use `_unsignedSubtract` to subtract
// the smaller magnitude from the larger magnitude.
switch lhs._compareMagnitude(to: rhs) {
case .equal:
lhs = 0
case .greaterThan:
lhs._unsignedSubtract(rhs)
case .lessThan:
// x - y == -y + x == -(y - x)
var result = rhs
result._unsignedSubtract(lhs)
result.isNegative = !lhs.isNegative
lhs = result
}
}
public static func *=(lhs: inout _BigInt, rhs: _BigInt) {
// If either `lhs` or `rhs` is zero, the result is zero.
guard !lhs.isZero && !rhs.isZero else {
lhs = 0
return
}
var newData: [Word] = Array(repeating: 0,
count: lhs._data.count + rhs._data.count)
let (a, b) = lhs._data.count > rhs._data.count
? (lhs._data, rhs._data)
: (rhs._data, lhs._data)
_sanityCheck(a.count >= b.count)
var carry: Word = 0
for ai in 0..<a.count {
carry = 0
for bi in 0..<b.count {
// Each iteration needs to perform this operation:
//
// newData[ai + bi] += (a[ai] * b[bi]) + carry
//
// However, `a[ai] * b[bi]` produces a double-width result, and both
// additions can overflow to a higher word. The following two lines
// capture the low word of the multiplication and additions in
// `newData[ai + bi]` and any addition overflow in `carry`.
let product = a[ai].multipliedFullWidth(by: b[bi])
(carry, newData[ai + bi]) = Word.addingFullWidth(
newData[ai + bi], product.low, carry)
// Now we combine the high word of the multiplication with any addition
// overflow. It is safe to add `product.high` and `carry` here without
// checking for overflow, because if `product.high == .max - 1`, then
// `carry <= 1`. Otherwise, `carry <= 2`.
//
// Worst-case (aka 9 + 9*9 + 9):
//
// newData a[ai] b[bi] carry
// 0b11111111 + (0b11111111 * 0b11111111) + 0b11111111
// 0b11111111 + (0b11111110_____00000001) + 0b11111111
// (0b11111111_____00000000) + 0b11111111
// (0b11111111_____11111111)
//
// Second-worse case:
//
// 0b11111111 + (0b11111111 * 0b11111110) + 0b11111111
// 0b11111111 + (0b11111101_____00000010) + 0b11111111
// (0b11111110_____00000001) + 0b11111111
// (0b11111111_____00000000)
_sanityCheck(!product.high.addingReportingOverflow(carry).overflow)
carry = product.high &+ carry
}
// Leftover `carry` is inserted in new highest word.
_sanityCheck(newData[ai + b.count] == 0)
newData[ai + b.count] = carry
}
lhs._data = newData
lhs.isNegative = lhs.isNegative != rhs.isNegative
lhs._standardize()
}
/// Divides this instance by `rhs`, returning the remainder.
@discardableResult
mutating func _internalDivide(by rhs: _BigInt) -> _BigInt {
_precondition(!rhs.isZero, "Divided by zero")
defer { _checkInvariants() }
// Handle quick cases that don't require division:
// If `abs(self) < abs(rhs)`, the result is zero, remainder = self
// If `abs(self) == abs(rhs)`, the result is 1 or -1, remainder = 0
switch _compareMagnitude(to: rhs) {
case .lessThan:
defer { self = 0 }
return self
case .equal:
self = isNegative != rhs.isNegative ? -1 : 1
return 0
default:
break
}
var tempSelf = self.magnitude
let n = tempSelf.bitWidth - rhs.magnitude.bitWidth
var quotient: _BigInt = 0
var tempRHS = rhs.magnitude << n
var tempQuotient: _BigInt = 1 << n
for _ in (0...n).reversed() {
if tempRHS._compareMagnitude(to: tempSelf) != .greaterThan {
tempSelf -= tempRHS
quotient += tempQuotient
}
tempRHS >>= 1
tempQuotient >>= 1
}
// `tempSelf` is the remainder - match sign of original `self`
tempSelf.isNegative = self.isNegative
tempSelf._standardize()
quotient.isNegative = isNegative != rhs.isNegative
self = quotient
_standardize()
return tempSelf
}
public static func /=(lhs: inout _BigInt, rhs: _BigInt) {
lhs._internalDivide(by: rhs)
}
// FIXME: Remove once default implementations are provided:
public static func +(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs += rhs
return lhs
}
public static func -(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs -= rhs
return lhs
}
public static func *(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs *= rhs
return lhs
}
public static func /(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs /= rhs
return lhs
}
public static func %(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs %= rhs
return lhs
}
//===--- BinaryInteger --------------------------------------------------===//
/// Creates a new instance using the given data array in two's complement
/// representation.
init(_twosComplementData: [Word]) {
guard _twosComplementData.count > 0 else {
self = 0
return
}
// Is the highest bit set?
isNegative = _twosComplementData.last!.leadingZeroBitCount == 0
if isNegative {
_data = _twosComplementData.map(~)
self._unsignedAdd(1 as Word)
} else {
_data = _twosComplementData
}
_standardize()
}
/// Returns an array of the value's data using two's complement representation.
func _dataAsTwosComplement() -> [Word] {
// Special cases:
// * Nonnegative values are already in 2's complement
if !isNegative {
// Positive values need to have a leading zero bit
if _data.last?.leadingZeroBitCount == 0 {
return _data + [0]
} else {
return _data
}
}
// * -1 will get zeroed out below, easier to handle here
if _data.count == 1 && _data.first == 1 { return [~0] }
var x = self
x._unsignedSubtract(1 as Word)
if x._data.last!.leadingZeroBitCount == 0 {
// The highest bit is set to 1, which moves to 0 after negation.
// We need to add another word at the high end so the highest bit is 1.
return x._data.map(~) + [Word.max]
} else {
// The highest bit is set to 0, which moves to 1 after negation.
return x._data.map(~)
}
}
public var words: [UInt] {
_sanityCheck(UInt.bitWidth % Word.bitWidth == 0)
let twosComplementData = _dataAsTwosComplement()
var words: [UInt] = []
words.reserveCapacity((twosComplementData.count * Word.bitWidth
+ UInt.bitWidth - 1) / UInt.bitWidth)
var word: UInt = 0
var shift = 0
for w in twosComplementData {
word |= UInt(truncatingIfNeeded: w) << shift
shift += Word.bitWidth
if shift == UInt.bitWidth {
words.append(word)
word = 0
shift = 0
}
}
if shift != 0 {
if isNegative {
word |= ~((1 << shift) - 1)
}
words.append(word)
}
return words
}
/// The number of bits used for storage of this value. Always a multiple of
/// `Word.bitWidth`.
public var bitWidth: Int {
if isZero {
return 0
} else {
let twosComplementData = _dataAsTwosComplement()
// If negative, it's okay to have 1s padded on high end
if isNegative {
return twosComplementData.count * Word.bitWidth
}
// If positive, need to make space for at least one zero on high end
return twosComplementData.count * Word.bitWidth
- twosComplementData.last!.leadingZeroBitCount + 1
}
}
/// The number of sequential zeros in the least-significant position of this
/// value's binary representation.
///
/// The numbers 1 and zero have zero trailing zeros.
public var trailingZeroBitCount: Int {
guard !isZero else {
return 0
}
let i = _data.index(where: { $0 != 0 })!
_sanityCheck(_data[i] != 0)
return i * Word.bitWidth + _data[i].trailingZeroBitCount
}
public static func %=(lhs: inout _BigInt, rhs: _BigInt) {
defer { lhs._checkInvariants() }
lhs = lhs._internalDivide(by: rhs)
}
public func quotientAndRemainder(dividingBy rhs: _BigInt) ->
(_BigInt, _BigInt)
{
var x = self
let r = x._internalDivide(by: rhs)
return (x, r)
}
public static func &=(lhs: inout _BigInt, rhs: _BigInt) {
var lhsTemp = lhs._dataAsTwosComplement()
let rhsTemp = rhs._dataAsTwosComplement()
// If `lhs` is longer than `rhs`, behavior depends on sign of `rhs`
// * If `rhs < 0`, length is extended with 1s
// * If `rhs >= 0`, length is extended with 0s, which crops `lhsTemp`
if lhsTemp.count > rhsTemp.count && !rhs.isNegative {
lhsTemp.removeLast(lhsTemp.count - rhsTemp.count)
}
// If `rhs` is longer than `lhs`, behavior depends on sign of `lhs`
// * If `lhs < 0`, length is extended with 1s, so `lhs` should get extra
// bits from `rhs`
// * If `lhs >= 0`, length is extended with 0s
if lhsTemp.count < rhsTemp.count && lhs.isNegative {
lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..<rhsTemp.count])
}
// Perform bitwise & on words that both `lhs` and `rhs` have.
for i in 0..<Swift.min(lhsTemp.count, rhsTemp.count) {
lhsTemp[i] &= rhsTemp[i]
}
lhs = _BigInt(_twosComplementData: lhsTemp)
}
public static func |=(lhs: inout _BigInt, rhs: _BigInt) {
var lhsTemp = lhs._dataAsTwosComplement()
let rhsTemp = rhs._dataAsTwosComplement()
// If `lhs` is longer than `rhs`, behavior depends on sign of `rhs`
// * If `rhs < 0`, length is extended with 1s, so those bits of `lhs`
// should all be 1
// * If `rhs >= 0`, length is extended with 0s, which is a no-op
if lhsTemp.count > rhsTemp.count && rhs.isNegative {
lhsTemp.replaceSubrange(rhsTemp.count..<lhsTemp.count,
with: repeatElement(Word.max, count: lhsTemp.count - rhsTemp.count))
}
// If `rhs` is longer than `lhs`, behavior depends on sign of `lhs`
// * If `lhs < 0`, length is extended with 1s, so those bits of lhs
// should all be 1
// * If `lhs >= 0`, length is extended with 0s, so those bits should be
// copied from rhs
if lhsTemp.count < rhsTemp.count {
if lhs.isNegative {
lhsTemp.append(contentsOf:
repeatElement(Word.max, count: rhsTemp.count - lhsTemp.count))
} else {
lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..<rhsTemp.count])
}
}
// Perform bitwise | on words that both `lhs` and `rhs` have.
for i in 0..<Swift.min(lhsTemp.count, rhsTemp.count) {
lhsTemp[i] |= rhsTemp[i]
}
lhs = _BigInt(_twosComplementData: lhsTemp)
}
public static func ^=(lhs: inout _BigInt, rhs: _BigInt) {
var lhsTemp = lhs._dataAsTwosComplement()
let rhsTemp = rhs._dataAsTwosComplement()
// If `lhs` is longer than `rhs`, behavior depends on sign of `rhs`
// * If `rhs < 0`, length is extended with 1s, so those bits of `lhs`
// should all be flipped
// * If `rhs >= 0`, length is extended with 0s, which is a no-op
if lhsTemp.count > rhsTemp.count && rhs.isNegative {
for i in rhsTemp.count..<lhsTemp.count {
lhsTemp[i] = ~lhsTemp[i]
}
}
// If `rhs` is longer than `lhs`, behavior depends on sign of `lhs`
// * If `lhs < 0`, length is extended with 1s, so those bits of `lhs`
// should all be flipped copies of `rhs`
// * If `lhs >= 0`, length is extended with 0s, so those bits should
// be copied from rhs
if lhsTemp.count < rhsTemp.count {
if lhs.isNegative {
lhsTemp += rhsTemp.suffix(from: lhsTemp.count).map(~)
} else {
lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..<rhsTemp.count])
}
}
// Perform bitwise ^ on words that both `lhs` and `rhs` have.
for i in 0..<Swift.min(lhsTemp.count, rhsTemp.count) {
lhsTemp[i] ^= rhsTemp[i]
}
lhs = _BigInt(_twosComplementData: lhsTemp)
}
public static prefix func ~(x: _BigInt) -> _BigInt {
return -x - 1
}
//===--- SignedNumeric --------------------------------------------------===//
public static prefix func -(x: inout _BigInt) {
defer { x._checkInvariants() }
guard x._data.count > 0 else { return }
x.isNegative = !x.isNegative
}
//===--- Strideable -----------------------------------------------------===//
public func distance(to other: _BigInt) -> _BigInt {
return other - self
}
public func advanced(by n: _BigInt) -> _BigInt {
return self + n
}
//===--- Other arithmetic -----------------------------------------------===//
/// Returns the greatest common divisor for this value and `other`.
public func greatestCommonDivisor(with other: _BigInt) -> _BigInt {
// Quick return if either is zero
if other.isZero {
return magnitude
}
if isZero {
return other.magnitude
}
var (x, y) = (self.magnitude, other.magnitude)
let (xLSB, yLSB) = (x.trailingZeroBitCount, y.trailingZeroBitCount)
// Remove any common factor of two
let commonPower = Swift.min(xLSB, yLSB)
x >>= commonPower
y >>= commonPower
// Remove any remaining factor of two
if xLSB != commonPower {
x >>= xLSB - commonPower
}
if yLSB != commonPower {
y >>= yLSB - commonPower
}
while !x.isZero {
// Swap values to ensure that `x >= y`.
if x._compareMagnitude(to: y) == .lessThan {
swap(&x, &y)
}
// Subtract smaller and remove any factors of two
x._unsignedSubtract(y)
x >>= x.trailingZeroBitCount
}
// Add original common factor of two back into result
y <<= commonPower
return y
}
/// Returns the lowest common multiple for this value and `other`.
public func lowestCommonMultiple(with other: _BigInt) -> _BigInt {
let gcd = greatestCommonDivisor(with: other)
if _compareMagnitude(to: other) == .lessThan {
return ((self / gcd) * other).magnitude
} else {
return ((other / gcd) * self).magnitude
}
}
//===--- String methods ------------------------------------------------===//
/// Creates a new instance from the given string.
///
/// - Parameters:
/// - source: The string to parse for the new instance's value. If a
/// character in `source` is not in the range `0...9` or `a...z`, case
/// insensitive, or is not less than `radix`, the result is `nil`.
/// - radix: The radix to use when parsing `source`. `radix` must be in the
/// range `2...36`. The default is `10`.
public init?(_ source: String, radix: Int = 10) {
assert(2...36 ~= radix, "radix must be in range 2...36")
let radix = Word(radix)
func valueForCodeUnit(_ unit: Unicode.UTF16.CodeUnit) -> Word? {
switch unit {
// "0"..."9"
case 48...57: return Word(unit - 48)
// "a"..."z"
case 97...122: return Word(unit - 87)
// "A"..."Z"
case 65...90: return Word(unit - 55)
// invalid character
default: return nil
}
}
var source = source
// Check for a single prefixing hyphen
let negative = source.hasPrefix("-")
if negative {
source = String(source.dropFirst())
}
// Loop through characters, multiplying
for v in source.utf16.map(valueForCodeUnit) {
// Character must be valid and less than radix
guard let v = v else { return nil }
guard v < radix else { return nil }
self.multiply(by: radix)
self.add(v)
}
self.isNegative = negative
}
/// Returns a string representation of this instance.
///
/// - Parameters:
/// - radix: The radix to use when converting this instance to a string.
/// The value passed as `radix` must be in the range `2...36`. The
/// default is `10`.
/// - lowercase: Whether to use lowercase letters to represent digits
/// greater than 10. The default is `true`.
public func toString(radix: Int = 10, lowercase: Bool = true) -> String {
assert(2...36 ~= radix, "radix must be in range 2...36")
let digitsStart = ("0" as Unicode.Scalar).value
let lettersStart = ((lowercase ? "a" : "A") as Unicode.Scalar).value - 10
func toLetter(_ x: UInt32) -> Unicode.Scalar {
return x < 10
? Unicode.Scalar(digitsStart + x)!
: Unicode.Scalar(lettersStart + x)!
}
let radix = _BigInt(radix)
var result: [Unicode.Scalar] = []
var x = self.magnitude
while !x.isZero {
let remainder: _BigInt
(x, remainder) = x.quotientAndRemainder(dividingBy: radix)
result.append(toLetter(UInt32(remainder)))
}
let sign = isNegative ? "-" : ""
let rest = result.count == 0
? "0"
: String(String.UnicodeScalarView(result.reversed()))
return sign + rest
}
public var description: String {
return decimalString
}
public var debugDescription: String {
return "_BigInt(\(hexString), words: \(_data.count))"
}
/// A string representation of this instance's value in base 2.
public var binaryString: String {
return toString(radix: 2)
}
/// A string representation of this instance's value in base 10.
public var decimalString: String {
return toString(radix: 10)
}
/// A string representation of this instance's value in base 16.
public var hexString: String {
return toString(radix: 16, lowercase: false)
}
/// A string representation of this instance's value in base 36.
public var compactString: String {
return toString(radix: 36, lowercase: false)
}
//===--- Comparable -----------------------------------------------------===//
enum _ComparisonResult {
case lessThan, equal, greaterThan
}
/// Returns whether this instance is less than, greather than, or equal to
/// the given value.
func _compare(to rhs: _BigInt) -> _ComparisonResult {
// Negative values are less than positive values
guard isNegative == rhs.isNegative else {
return isNegative ? .lessThan : .greaterThan
}
switch _compareMagnitude(to: rhs) {
case .equal:
return .equal
case .lessThan:
return isNegative ? .greaterThan : .lessThan
case .greaterThan:
return isNegative ? .lessThan : .greaterThan
}
}
/// Returns whether the magnitude of this instance is less than, greather
/// than, or equal to the magnitude of the given value.
func _compareMagnitude(to rhs: _BigInt) -> _ComparisonResult {
guard _data.count == rhs._data.count else {
return _data.count < rhs._data.count ? .lessThan : .greaterThan
}
// Equal number of words: compare from most significant word
for i in (0..<_data.count).reversed() {
if _data[i] < rhs._data[i] { return .lessThan }
if _data[i] > rhs._data[i] { return .greaterThan }
}
return .equal
}
public static func ==(lhs: _BigInt, rhs: _BigInt) -> Bool {
return lhs._compare(to: rhs) == .equal
}
public static func < (lhs: _BigInt, rhs: _BigInt) -> Bool {
return lhs._compare(to: rhs) == .lessThan
}
//===--- Hashable -------------------------------------------------------===//
public var hashValue: Int {
#if arch(i386) || arch(arm)
let p: UInt = 16777619
let h: UInt = (2166136261 &* p) ^ (isNegative ? 1 : 0)
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
let p: UInt = 1099511628211
let h: UInt = (14695981039346656037 &* p) ^ (isNegative ? 1 : 0)
#else
fatalError("Unimplemented")
#endif
return Int(bitPattern: _data.reduce(h, { ($0 &* p) ^ UInt($1) }))
}
//===--- Bit shifting operators -----------------------------------------===//
static func _shiftLeft(_ data: inout [Word], byWords words: Int) {
guard words > 0 else { return }
data.insert(contentsOf: repeatElement(0, count: words), at: 0)
}
static func _shiftRight(_ data: inout [Word], byWords words: Int) {
guard words > 0 else { return }
data.removeFirst(Swift.min(data.count, words))
}
public static func <<= <RHS : BinaryInteger>(lhs: inout _BigInt, rhs: RHS) {
defer { lhs._checkInvariants() }
guard rhs != 0 else { return }
guard rhs > 0 else {
lhs >>= 0 - rhs
return
}
let wordWidth = RHS(Word.bitWidth)
// We can add `rhs / bits` extra words full of zero at the low end.
let extraWords = Int(rhs / wordWidth)
lhs._data.reserveCapacity(lhs._data.count + extraWords + 1)
_BigInt._shiftLeft(&lhs._data, byWords: extraWords)
// Each existing word will need to be shifted left by `rhs % bits`.
// For each pair of words, we'll use the high `offset` bits of the
// lower word and the low `Word.bitWidth - offset` bits of the higher
// word.
let highOffset = Int(rhs % wordWidth)
let lowOffset = Word.bitWidth - highOffset
// If there's no offset, we're finished, as `rhs` was a multiple of
// `Word.bitWidth`.
guard highOffset != 0 else { return }
// Add new word at the end, then shift everything left by `offset` bits.
lhs._data.append(0)
for i in ((extraWords + 1)..<lhs._data.count).reversed() {
lhs._data[i] = lhs._data[i] << highOffset
| lhs._data[i - 1] >> lowOffset
}
// Finally, shift the lowest word.
lhs._data[extraWords] = lhs._data[extraWords] << highOffset
lhs._standardize()
}
public static func >>= <RHS : BinaryInteger>(lhs: inout _BigInt, rhs: RHS) {
defer { lhs._checkInvariants() }
guard rhs != 0 else { return }
guard rhs > 0 else {
lhs <<= 0 - rhs
return
}
var tempData = lhs._dataAsTwosComplement()
let wordWidth = RHS(Word.bitWidth)
// We can remove `rhs / bits` full words at the low end.
// If that removes the entirety of `_data`, we're done.
let wordsToRemove = Int(rhs / wordWidth)
_BigInt._shiftRight(&tempData, byWords: wordsToRemove)
guard tempData.count != 0 else {
lhs = lhs.isNegative ? -1 : 0
return
}
// Each existing word will need to be shifted right by `rhs % bits`.
// For each pair of words, we'll use the low `offset` bits of the
// higher word and the high `_BigInt.Word.bitWidth - offset` bits of
// the lower word.
let lowOffset = Int(rhs % wordWidth)
let highOffset = Word.bitWidth - lowOffset
// If there's no offset, we're finished, as `rhs` was a multiple of
// `Word.bitWidth`.
guard lowOffset != 0 else {
lhs = _BigInt(_twosComplementData: tempData)
return
}
// Shift everything right by `offset` bits.
for i in 0..<(tempData.count - 1) {
tempData[i] = tempData[i] >> lowOffset |
tempData[i + 1] << highOffset
}
// Finally, shift the highest word and standardize the result.
tempData[tempData.count - 1] >>= lowOffset
lhs = _BigInt(_twosComplementData: tempData)
}
}
//===--- Bit --------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A one-bit fixed width integer.
struct Bit : FixedWidthInteger, UnsignedInteger {
typealias Magnitude = Bit
var value: UInt8 = 0
// Initializers
init(integerLiteral value: Int) {
self = Bit(value)
}
init(bigEndian value: Bit) {
self = value
}
init(littleEndian value: Bit) {
self = value
}
init?<T: BinaryFloatingPoint>(exactly source: T) {
switch source {
case T(0): value = 0
case T(1): value = 1
default:
return nil
}
}
init<T: BinaryFloatingPoint>(_ source: T) {
self = Bit(exactly: source.rounded(.down))!
}
init<T: BinaryInteger>(_ source: T) {
switch source {
case 0: value = 0
case 1: value = 1
default:
fatalError("Can't represent \(source) as a Bit")
}
}
init<T: BinaryInteger>(truncatingIfNeeded source: T) {
value = UInt8(source & 1)
}
init(_truncatingBits bits: UInt) {
value = UInt8(bits & 1)
}
init<T: BinaryInteger>(clamping source: T) {
value = source >= 1 ? 1 : 0
}
// FixedWidthInteger, BinaryInteger
static var bitWidth: Int {
return 1
}
var bitWidth: Int {
return 1
}
var trailingZeroBitCount: Int {
return Int(~value & 1)
}
static var max: Bit {
return 1
}
static var min: Bit {
return 0
}
static var isSigned: Bool {
return false
}
var nonzeroBitCount: Int {
return value.nonzeroBitCount
}
var leadingZeroBitCount: Int {
return Int(~value & 1)
}
var bigEndian: Bit {
return self
}
var littleEndian: Bit {
return self
}
var byteSwapped: Bit {
return self
}
var words: UInt.Words {
return UInt(value).words
}
// Hashable, CustomStringConvertible
var hashValue: Int {
return Int(value)
}
var description: String {
return "\(value)"
}
// Arithmetic Operations / Operators
func _checkOverflow(_ v: UInt8) -> Bool {
let mask: UInt8 = ~0 << 1
return v & mask != 0
}
func addingReportingOverflow(_ rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
let result = value &+ rhs.value
return (Bit(result & 1), _checkOverflow(result))
}
func subtractingReportingOverflow(_ rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
let result = value &- rhs.value
return (Bit(result & 1), _checkOverflow(result))
}
func multipliedReportingOverflow(by rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
let result = value &* rhs.value
return (Bit(result), false)
}
func dividedReportingOverflow(by rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
return (self, rhs != 0)
}
func remainderReportingOverflow(dividingBy rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
fatalError()
}
static func +=(lhs: inout Bit, rhs: Bit) {
let result = lhs.addingReportingOverflow(rhs)
assert(!result.overflow, "Addition overflow")
lhs = result.partialValue
}
static func -=(lhs: inout Bit, rhs: Bit) {
let result = lhs.subtractingReportingOverflow(rhs)
assert(!result.overflow, "Subtraction overflow")
lhs = result.partialValue
}
static func *=(lhs: inout Bit, rhs: Bit) {
let result = lhs.multipliedReportingOverflow(by: rhs)
assert(!result.overflow, "Multiplication overflow")
lhs = result.partialValue
}
static func /=(lhs: inout Bit, rhs: Bit) {
let result = lhs.dividedReportingOverflow(by: rhs)
assert(!result.overflow, "Division overflow")
lhs = result.partialValue
}
static func %=(lhs: inout Bit, rhs: Bit) {
assert(rhs != 0, "Modulo sum overflow")
lhs.value = 0 // No remainders with bit division!
}
func multipliedFullWidth(by other: Bit) -> (high: Bit, low: Bit) {
return (0, self * other)
}
func dividingFullWidth(_ dividend: (high: Bit, low: Bit)) ->
(quotient: Bit, remainder: Bit) {
assert(self != 0, "Division overflow")
assert(dividend.high == 0, "Quotient overflow")
return (dividend.low, 0)
}
// FIXME: Remove once default implementations are provided:
public static func +(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs += rhs
return lhs
}
public static func -(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs -= rhs
return lhs
}
public static func *(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs *= rhs
return lhs
}
public static func /(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs /= rhs
return lhs
}
public static func %(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs %= rhs
return lhs
}
// Bitwise operators
static prefix func ~(x: Bit) -> Bit {
return Bit(~x.value & 1)
}
// Why doesn't the type checker complain about these being missing?
static func &=(lhs: inout Bit, rhs: Bit) {
lhs.value &= rhs.value
}
static func |=(lhs: inout Bit, rhs: Bit) {
lhs.value |= rhs.value
}
static func ^=(lhs: inout Bit, rhs: Bit) {
lhs.value ^= rhs.value
}
static func ==(lhs: Bit, rhs: Bit) -> Bool {
return lhs.value == rhs.value
}
static func <(lhs: Bit, rhs: Bit) -> Bool {
return lhs.value < rhs.value
}
static func <<(lhs: Bit, rhs: Bit) -> Bit {
return rhs == 0 ? lhs : 0
}
static func >>(lhs: Bit, rhs: Bit) -> Bit {
return rhs == 0 ? lhs : 0
}
static func <<=(lhs: inout Bit, rhs: Bit) {
if rhs != 0 {
lhs = 0
}
}
static func >>=(lhs: inout Bit, rhs: Bit) {
if rhs != 0 {
lhs = 0
}
}
}
//===--- Tests ------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
typealias BigInt = _BigInt<UInt>
typealias BigInt8 = _BigInt<UInt8>
typealias BigIntBit = _BigInt<Bit>
func testBinaryInit<T: BinaryInteger>(_ x: T) -> BigInt {
return BigInt(x)
}
func randomBitLength() -> Int {
return Int(arc4random_uniform(1000) + 2)
}
var BitTests = TestSuite("Bit")
BitTests.test("Basics") {
let x = Bit.max
let y = Bit.min
expectTrue(x == 1 as Int)
expectTrue(y == 0 as Int)
expectTrue(x < Int.max)
expectGT(x, y)
expectEqual(x, x)
expectEqual(x, x ^ 0)
expectGT(x, x & 0)
expectEqual(x, x | 0)
expectLT(y, y | 1)
expectEqual(x, ~y)
expectEqual(y, ~x)
expectEqual(x, x + y)
expectGT(x, x &+ x)
expectEqual(1, x.nonzeroBitCount)
expectEqual(0, y.nonzeroBitCount)
expectEqual(0, x.leadingZeroBitCount)
expectEqual(1, y.leadingZeroBitCount)
expectEqual(0, x.trailingZeroBitCount)
expectEqual(1, y.trailingZeroBitCount)
}
var BigIntTests = TestSuite("BigInt")
BigIntTests.test("Initialization") {
let x = testBinaryInit(1_000_000 as Int)
expectEqual(x._data[0], 1_000_000)
let y = testBinaryInit(1_000 as UInt16)
expectEqual(y._data[0], 1_000)
let z = testBinaryInit(-1_000_000 as Int)
expectEqual(z._data[0], 1_000_000)
expectTrue(z.isNegative)
let z6 = testBinaryInit(z * z * z * z * z * z)
expectEqual(z6._data, [12919594847110692864, 54210108624275221])
expectFalse(z6.isNegative)
}
BigIntTests.test("Identity/Fixed point") {
let x = BigInt(repeatElement(UInt.max, count: 20))
let y = -x
expectEqual(x / x, 1)
expectEqual(x / y, -1)
expectEqual(y / x, -1)
expectEqual(y / y, 1)
expectEqual(x % x, 0)
expectEqual(x % y, 0)
expectEqual(y % x, 0)
expectEqual(y % y, 0)
expectEqual(x * 1, x)
expectEqual(y * 1, y)
expectEqual(x * -1, y)
expectEqual(y * -1, x)
expectEqual(-x, y)
expectEqual(-y, x)
expectEqual(x + 0, x)
expectEqual(y + 0, y)
expectEqual(x - 0, x)
expectEqual(y - 0, y)
expectEqual(x - x, 0)
expectEqual(y - y, 0)
}
BigIntTests.test("Max arithmetic") {
let x = BigInt(repeatElement(UInt.max, count: 50))
let y = BigInt(repeatElement(UInt.max, count: 35))
let (q, r) = x.quotientAndRemainder(dividingBy: y)
expectEqual(q * y + r, x)
expectEqual(q * y, x - r)
}
BigIntTests.test("Zero arithmetic") {
let zero: BigInt = 0
expectTrue(zero.isZero)
expectFalse(zero.isNegative)
let x: BigInt = 1
expectTrue((x - x).isZero)
expectFalse((x - x).isNegative)
let y: BigInt = -1
expectTrue(y.isNegative)
expectTrue((y - y).isZero)
expectFalse((y - y).isNegative)
expectEqual(x * zero, zero)
expectCrashLater()
_ = x / zero
}
BigIntTests.test("Conformances") {
// Comparable
let x = BigInt(Int.max)
let y = x * x * x * x * x
expectLT(y, y + 1)
expectGT(y, y - 1)
expectGT(y, 0)
let z = -y
expectLT(z, z + 1)
expectGT(z, z - 1)
expectLT(z, 0)
expectEqual(-z, y)
expectEqual(y + z, 0)
// Hashable
expectNotEqual(x.hashValue, y.hashValue)
expectNotEqual(y.hashValue, z.hashValue)
let set = Set([x, y, z])
expectTrue(set.contains(x))
expectTrue(set.contains(y))
expectTrue(set.contains(z))
expectFalse(set.contains(-x))
}
BigIntTests.test("BinaryInteger interop") {
let x: BigInt = 100
let xComp = UInt8(x)
expectTrue(x == xComp)
expectTrue(x < xComp + 1)
expectFalse(xComp + 1 < x)
let y: BigInt = -100
let yComp = Int8(y)
expectTrue(y == yComp)
expectTrue(y < yComp + (1 as Int8))
expectFalse(yComp + (1 as Int8) < y)
// should be: expectTrue(y < yComp + 1), but:
// warning: '+' is deprecated: Mixed-type addition is deprecated.
// Please use explicit type conversion.
let zComp = Int.min + 1
let z = BigInt(zComp)
expectTrue(z == zComp)
expectTrue(zComp == z)
expectFalse(zComp + 1 < z)
expectTrue(z < zComp + 1)
let w = BigInt(UInt.max)
let wComp = UInt(truncatingIfNeeded: w)
expectTrue(w == wComp)
expectTrue(wComp == w)
expectTrue(wComp - (1 as UInt) < w)
expectFalse(w < wComp - (1 as UInt))
// should be:
// expectTrue(wComp - 1 < w)
// expectTrue(w > wComp - 1)
// but crashes at runtime
}
BigIntTests.test("Huge") {
let x = BigInt(randomBits: 1_000_000)
expectGT(x, x - 1)
let y = -x
expectGT(y, y - 1)
}
BigIntTests.test("Numeric").forEach(in: [
("3GFWFN54YXNBS6K2ST8K9B89Q2AMRWCNYP4JAS5ZOPPZ1WU09MXXTIT27ZPVEG2Y",
"9Y1QXS4XYYDSBMU4N3LW7R3R1WKK",
"CIFJIVHV0K4MSX44QEX2US0MFFEAWJVQ8PJZ",
"26HILZ7GZQN8MB4O17NSPO5XN1JI"),
("7PM82EHP7ZN3ZL7KOPB7B8KYDD1R7EEOYWB6M4SEION47EMS6SMBEA0FNR6U9VAM70HPY4WKXBM8DCF1QOR1LE38NJAVOPOZEBLIU1M05",
"-202WEEIRRLRA9FULGA15RYROVW69ZPDHW0FMYSURBNWB93RNMSLRMIFUPDLP5YOO307XUNEFLU49FV12MI22MLCVZ5JH",
"-3UNIZHA6PAL30Y",
"1Y13W1HYB0QV2Z5RDV9Z7QXEGPLZ6SAA2906T3UKA46E6M4S6O9RMUF5ETYBR2QT15FJZP87JE0W06FA17RYOCZ3AYM3"),
("-ICT39SS0ONER9Z7EAPVXS3BNZDD6WJA791CV5LT8I4POLF6QYXBQGUQG0LVGPVLT0L5Z53BX6WVHWLCI5J9CHCROCKH3B381CCLZ4XAALLMD",
"6T1XIVCPIPXODRK8312KVMCDPBMC7J4K0RWB7PM2V4VMBMODQ8STMYSLIXFN9ORRXCTERWS5U4BLUNA4H6NG8O01IM510NJ5STE",
"-2P2RVZ11QF",
"-3YSI67CCOD8OI1HFF7VF5AWEQ34WK6B8AAFV95U7C04GBXN0R6W5GM5OGOO22HY0KADIUBXSY13435TW4VLHCKLM76VS51W5Z9J"),
("-326JY57SJVC",
"-8H98AQ1OY7CGAOOSG",
"0",
"-326JY57SJVC"),
("-XIYY0P3X9JIDF20ZQG2CN5D2Q5CD9WFDDXRLFZRDKZ8V4TSLE2EHRA31XL3YOHPYLE0I0ZAV2V9RF8AGPCYPVWEIYWWWZ3HVDR64M08VZTBL85PR66Z2F0W5AIDPXIAVLS9VVNLNA6I0PKM87YW4T98P0K",
"-BUBZEC4NTOSCO0XHCTETN4ROPSXIJBTEFYMZ7O4Q1REOZO2SFU62KM3L8D45Z2K4NN3EC4BSRNEE",
"2TX1KWYGAW9LAXUYRXZQENY5P3DSVXJJXK4Y9DWGNZHOWCL5QD5PLLZCE6D0G7VBNP9YGFC0Z9XIPCB",
"-3LNPZ9JK5PUXRZ2Y1EJ4E3QRMAMPKZNI90ZFOBQJM5GZUJ84VMF8EILRGCHZGXJX4AXZF0Z00YA"),
("AZZBGH7AH3S7TVRHDJPJ2DR81H4FY5VJW2JH7O4U7CH0GG2DSDDOSTD06S4UM0HP1HAQ68B2LKKWD73UU0FV5M0H0D0NSXUJI7C2HW3P51H1JM5BHGXK98NNNSHMUB0674VKJ57GVVGY4",
"1LYN8LRN3PY24V0YNHGCW47WUWPLKAE4685LP0J74NZYAIMIBZTAF71",
"6TXVE5E9DXTPTHLEAG7HGFTT0B3XIXVM8IGVRONGSSH1UC0HUASRTZX8TVM2VOK9N9NATPWG09G7MDL6CE9LBKN",
"WY37RSPBTEPQUA23AXB3B5AJRIUL76N3LXLP3KQWKFFSR7PR4E1JWH"),
("1000000000000000000000000000000000000000000000",
"1000000000000000000000000000000000000",
"1000000000",
"0"),
])
{ strings in
let x = BigInt(strings.0, radix: 36)!
let y = BigInt(strings.1, radix: 36)!
let q = BigInt(strings.2, radix: 36)!
let r = BigInt(strings.3, radix: 36)!
let (testQ, testR) = x.quotientAndRemainder(dividingBy: y)
expectEqual(testQ, q)
expectEqual(testR, r)
expectEqual(x, y * q + r)
}
BigIntTests.test("Strings") {
let x = BigInt("-3UNIZHA6PAL30Y", radix: 36)!
expectEqual(x.binaryString, "-1000111001110110011101001110000001011001110110011011110011000010010010")
expectEqual(x.decimalString, "-656993338084259999890")
expectEqual(x.hexString, "-239D9D3816766F3092")
expectEqual(x.compactString, "-3UNIZHA6PAL30Y")
expectTrue(BigInt("12345") == 12345)
expectTrue(BigInt("-12345") == -12345)
expectTrue(BigInt("-3UNIZHA6PAL30Y", radix: 10) == nil)
expectTrue(BigInt("---") == nil)
expectTrue(BigInt(" 123") == nil)
}
BigIntTests.test("Randomized arithmetic").forEach(in: Array(1...10)) { _ in
// Test x == (x / y) * x + (x % y)
let (x, y) = (
BigInt(randomBits: randomBitLength()),
BigInt(randomBits: randomBitLength()))
if !y.isZero {
let (q, r) = x.quotientAndRemainder(dividingBy: y)
expectEqual(q * y + r, x)
expectEqual(q * y, x - r)
}
// Test (x0 + y0)(x1 + y1) == x0x1 + x0y1 + y0x1 + y0y1
let (x0, y0, x1, y1) = (
BigInt(randomBits: randomBitLength()),
BigInt(randomBits: randomBitLength()),
BigInt(randomBits: randomBitLength()),
BigInt(randomBits: randomBitLength()))
let r1 = (x0 + y0) * (x1 + y1)
let r2 = ((x0 * x1) + (x0 * y1), (y0 * x1) + (y0 * y1))
expectEqual(r1, r2.0 + r2.1)
}
var BigInt8Tests = TestSuite("BigInt<UInt8>")
BigInt8Tests.test("BinaryInteger interop") {
let x: BigInt8 = 100
let xComp = UInt8(x)
expectTrue(x == xComp)
expectTrue(x < xComp + 1)
expectFalse(xComp + 1 < x)
let y: BigInt8 = -100
let yComp = Int8(y)
expectTrue(y == yComp)
expectTrue(y < yComp + (1 as Int8))
expectFalse(yComp + (1 as Int8) < y)
let zComp = Int.min + 1
let z = BigInt8(zComp)
expectTrue(z == zComp)
expectTrue(zComp == z)
expectFalse(zComp + 1 < z)
expectTrue(z < zComp + 1)
let w = BigInt8(UInt.max)
let wComp = UInt(truncatingIfNeeded: w)
expectTrue(w == wComp)
expectTrue(wComp == w)
expectTrue(wComp - (1 as UInt) < w)
expectFalse(w < wComp - (1 as UInt))
}
BigInt8Tests.test("Randomized arithmetic").forEach(in: Array(1...10)) { _ in
// Test x == (x / y) * x + (x % y)
let (x, y) = (
BigInt8(randomBits: randomBitLength()),
BigInt8(randomBits: randomBitLength()))
if !y.isZero {
let (q, r) = x.quotientAndRemainder(dividingBy: y)
expectEqual(q * y + r, x)
expectEqual(q * y, x - r)
}
// Test (x0 + y0)(x1 + y1) == x0x1 + x0y1 + y0x1 + y0y1
let (x0, y0, x1, y1) = (
BigInt8(randomBits: randomBitLength()),
BigInt8(randomBits: randomBitLength()),
BigInt8(randomBits: randomBitLength()),
BigInt8(randomBits: randomBitLength()))
let r1 = (x0 + y0) * (x1 + y1)
let r2 = ((x0 * x1) + (x0 * y1), (y0 * x1) + (y0 * y1))
expectEqual(r1, r2.0 + r2.1)
}
BigInt8Tests.test("Bitshift") {
expectEqual(BigInt8(255) << 1, 510)
expectTrue(BigInt(UInt32.max) << 16 == UInt(UInt32.max) << 16)
var (x, y) = (1 as BigInt, 1 as UInt)
for i in 0..<64 { // don't test 64-bit shift, UInt64 << 64 == 0
expectTrue(x << i == y << i)
}
(x, y) = (BigInt(UInt.max), UInt.max)
for i in 0...64 { // test 64-bit shift, should both be zero
expectTrue(x >> i == y >> i,
"\(x) as \(type(of:x)) >> \(i) => \(x >> i) != \(y) as \(type(of:y)) >> \(i) => \(y >> i)")
}
x = BigInt(-1)
let z = -1 as Int
for i in 0..<64 {
expectTrue(x << i == z << i)
}
}
BigInt8Tests.test("Bitwise").forEach(in: [
BigInt8(Int.max - 2),
BigInt8(255),
BigInt8(256),
BigInt8(UInt32.max),
])
{ value in
for x in [value, -value] {
expectTrue(x | 0 == x)
expectTrue(x & 0 == 0)
expectTrue(x & ~0 == x)
expectTrue(x ^ 0 == x)
expectTrue(x ^ ~0 == ~x)
expectTrue(x == BigInt8(Int(truncatingIfNeeded: x)))
expectTrue(~x == BigInt8(~Int(truncatingIfNeeded: x)))
}
}
var BigIntBitTests = TestSuite("BigInt<Bit>")
BigIntBitTests.test("Randomized arithmetic").forEach(in: Array(1...10)) { _ in
// Test x == (x / y) * x + (x % y)
let (x, y) = (
BigIntBit(randomBits: randomBitLength() % 100),
BigIntBit(randomBits: randomBitLength() % 100))
if !y.isZero {
let (q, r) = x.quotientAndRemainder(dividingBy: y)
expectEqual(q * y + r, x)
expectEqual(q * y, x - r)
}
// Test (x0 + y0)(x1 + y1) == x0x1 + x0y1 + y0x1 + y0y1
let (x0, y0, x1, y1) = (
BigIntBit(randomBits: randomBitLength() % 100),
BigIntBit(randomBits: randomBitLength() % 100),
BigIntBit(randomBits: randomBitLength() % 100),
BigIntBit(randomBits: randomBitLength() % 100))
let r1 = (x0 + y0) * (x1 + y1)
let r2 = ((x0 * x1) + (x0 * y1), (y0 * x1) + (y0 * y1))
expectEqual(r1, r2.0 + r2.1)
}
BigIntBitTests.test("Conformances") {
// Comparable
let x = BigIntBit(Int.max)
let y = x * x * x * x * x
expectLT(y, y + 1)
expectGT(y, y - 1)
expectGT(y, 0)
let z = -y
expectLT(z, z + 1)
expectGT(z, z - 1)
expectLT(z, 0)
expectEqual(-z, y)
expectEqual(y + z, 0)
// Hashable
expectNotEqual(x.hashValue, y.hashValue)
expectNotEqual(y.hashValue, z.hashValue)
let set = Set([x, y, z])
expectTrue(set.contains(x))
expectTrue(set.contains(y))
expectTrue(set.contains(z))
expectFalse(set.contains(-x))
}
BigIntBitTests.test("words") {
expectEqualSequence([1], (1 as BigIntBit).words)
expectEqualSequence([UInt.max, 0], BigIntBit(UInt.max).words)
expectEqualSequence([UInt.max >> 1], BigIntBit(UInt.max >> 1).words)
expectEqualSequence([0, 1], (BigIntBit(UInt.max) + 1).words)
expectEqualSequence([UInt.max], (-1 as BigIntBit).words)
}
runAllTests()
| apache-2.0 | 59297f60c5aa25605f9c63e648e6990d | 28.246656 | 161 | 0.607332 | 3.616886 | false | false | false | false |
TechnologySpeaks/smile-for-life | smile-for-life/Helpers.swift | 1 | 4663 | //
// Helpers.swift
// smile-for-life
//
// Created by Lisa Swanson on 4/28/16.
// Copyright © 2016 Technology Speaks. All rights reserved.
//
import Foundation
import UIKit
func generateRandomData() -> [[UIColor]] {
let numberOfRows = 20
let numberOfItemsPerRow = 15
return (0..<numberOfRows).map { _ in
return (0..<numberOfItemsPerRow).map { _ in UIColor.randomColor() }
}
}
extension UIColor {
class func randomColor() -> UIColor {
let hue = CGFloat(arc4random() % 100) / 100
let saturation = CGFloat(arc4random() % 100) / 100
let brightness = CGFloat(arc4random() % 100) / 100
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
}
}
class Helpers {
static func setCurrentCalendar(_ user: User) {
let defaults = UserDefaults.standard
defaults.setValue(user.name, forKey: "lastCalendarLoaded")
}
static func setCalendar(_ calendar: String) {
let defaults = UserDefaults.standard
defaults.setValue(calendar, forKey: "lastCalendarLoaded")
}
static func getLastCalenderUsed(_ lastCalendarLoaded: String) -> String {
let defaults = UserDefaults.standard
if defaults.object(forKey: lastCalendarLoaded) != nil {
let calendar = defaults.string(forKey: lastCalendarLoaded)!
return calendar
} else {
defaults.setValue("None", forKey: lastCalendarLoaded)
return defaults.string(forKey: lastCalendarLoaded)!
}
}
func tablesExist() -> Bool {
var dbExists: Bool?
let defaults = UserDefaults.standard
if defaults.object(forKey: "dbTablesExist") != nil {
dbExists = defaults.bool(forKey: "dbTablesExist")
} else {
defaults.setValue(false, forKey: "dbTablesExist")
dbExists = false
}
return dbExists!
}
static func getDateFormatter(_ templete: String) -> DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = templete
formatter.setLocalizedDateFormatFromTemplate(templete)
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}
static func convertNSDateToSqliteDate(_ date: Date) -> String {
let dateFormatter = DateFormatter()
let cal = Calendar.current
let day = cal.ordinality(of: .day, in: .year, for: date)
// print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
// print(day)
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
// let sqlite3Date = dateFormatter.string(from: date)
return dateFormatter.string(from: date)
}
static func getInstanceOfOralEvent(_ date: Date, event: String) -> OralEvent {
let eventName: String = event
let timeLabel: String = Helpers.getDateFormatter("hhmm").string(from: date)
let sectionHeaderName: String = Helpers.getDateFormatter("EEEE-MMMM-dd").string(from: date)
//Nice formatted code: it's a keeper
// let index: Int = Int(Helpers.getDateFormatter("MMdd").stringFromDate(date).stringByReplacingOccurrencesOfString("/", withString: ""))!
let dateStringified = Helpers.convertNSDateToSqliteDate(date)
let calendarOwner: Int32 = currentUser.id!
return OralEvent(date: date, eventName: eventName, timeLabel: timeLabel, sectionHeaderName: sectionHeaderName, dateStringified: dateStringified, calendarOwnerId: calendarOwner)
}
static func getOralHygieneEvent(_ date: Date, event: String) -> OralHygieneEvent {
let eventName: String = event
let timeLabel: String = Helpers.getDateFormatter("hhmm").string(from: date)
let dateStringified = Helpers.convertNSDateToSqliteDate(date)
// print(dateStringified)
return OralHygieneEvent(sortingIndex: dateStringified as String, eventName: eventName, timeLabel: timeLabel)
}
}
class DateHelpers {
static func convertStringDateToNSDate(_ date: String) -> Date {
// print("convert, convert, conert, convert")
// print(date)
let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "MM/dd/yyyy, HH:mm:ss"
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
dateFormatter.locale = Locale.current
// dateFormatter.timeZone = NSTimeZone(name: "UTC")
return dateFormatter.date(from: date)!
}
static func getSectionHeaderName(_ date: Date) -> String {
return Helpers.getDateFormatter("EEEE-MMMM-dd").string(from: date)
}
func getDate() {
let calendar = Calendar.current
var dateComponents = DateComponents()
dateComponents.month = 11
dateComponents.day = 20
dateComponents.hour = 16
dateComponents.minute = 5
}
}
| mit | 43e165f78393c422e6c57bf81f7055e4 | 29.874172 | 180 | 0.673745 | 4.222826 | false | false | false | false |
hooman/swift | test/Constraints/same_types.swift | 5 | 12369 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
protocol Fooable {
associatedtype Foo // expected-note{{protocol requires nested type 'Foo'; do you want to add it?}}
var foo: Foo { get }
}
protocol Barrable {
associatedtype Bar: Fooable
var bar: Bar { get }
}
struct X {}
struct Y: Fooable {
typealias Foo = X
var foo: X { return X() }
}
struct Z: Barrable {
typealias Bar = Y
var bar: Y { return Y() }
}
protocol TestSameTypeRequirement {
func foo<F1: Fooable>(_ f: F1) where F1.Foo == X
}
struct SatisfySameTypeRequirement : TestSameTypeRequirement {
func foo<F2: Fooable>(_ f: F2) where F2.Foo == X {}
}
func test1<T: Fooable>(_ fooable: T) -> X where T.Foo == X {
return fooable.foo
}
struct NestedConstraint<T> {
func tFoo<U: Fooable>(_ fooable: U) -> T where U.Foo == T {
return fooable.foo
}
}
func test2<T: Fooable, U: Fooable>(_ t: T, u: U) -> (X, X)
where T.Foo == X, U.Foo == T.Foo {
return (t.foo, u.foo)
}
func test2a<T: Fooable, U: Fooable>(_ t: T, u: U) -> (X, X)
where T.Foo == X, T.Foo == U.Foo {
return (t.foo, u.foo)
}
func test3<T: Fooable, U: Fooable>(_ t: T, u: U) -> (X, X)
where T.Foo == X, U.Foo == X, T.Foo == U.Foo {
// expected-warning@-1{{redundant same-type constraint 'U.Foo' == 'X'}}
// expected-note@-2{{same-type constraint 'T.Foo' == 'X' written here}}
return (t.foo, u.foo)
}
func fail1<
T: Fooable, U: Fooable
>(_ t: T, u: U) -> (X, Y)
where T.Foo == X, U.Foo == Y, T.Foo == U.Foo { // expected-error{{'U.Foo' cannot be equal to both 'Y' and 'X'}}
// expected-note@-1{{same-type constraint 'T.Foo' == 'X' written here}}
return (t.foo, u.foo) // expected-error{{cannot convert return expression of type '(X, X)' to return type '(X, Y)'}}
}
func fail2<
T: Fooable, U: Fooable
>(_ t: T, u: U) -> (X, Y)
where T.Foo == U.Foo, T.Foo == X, U.Foo == Y { // expected-error{{'U.Foo' cannot be equal to both 'Y' and 'X'}}
// expected-note@-1{{same-type constraint 'T.Foo' == 'X' written here}}
return (t.foo, u.foo) // expected-error{{cannot convert return expression of type '(X, X)' to return type '(X, Y)'}}
}
func test4<T: Barrable>(_ t: T) -> Y where T.Bar == Y {
return t.bar
}
func fail3<T: Barrable>(_ t: T) -> X
where T.Bar == X { // expected-error {{'X' does not conform to required protocol 'Fooable'}}
return t.bar // expected-error{{cannot convert return expression of type 'T.Bar' }}
}
func test5<T: Barrable>(_ t: T) -> X where T.Bar.Foo == X {
return t.bar.foo
}
func test6<T: Barrable>(_ t: T) -> (Y, X) where T.Bar == Y {
return (t.bar, t.bar.foo)
}
func test7<T: Barrable>(_ t: T) -> (Y, X) where T.Bar == Y, T.Bar.Foo == X {
// expected-warning@-1{{neither type in same-type constraint ('Y.Foo' (aka 'X') or 'X') refers to a generic parameter or associated type}}
return (t.bar, t.bar.foo)
}
func fail4<T: Barrable>(_ t: T) -> (Y, Z)
where
T.Bar == Y,
T.Bar.Foo == Z { // expected-error{{generic signature requires types 'Y.Foo' (aka 'X') and 'Z' to be the same}}
return (t.bar, t.bar.foo) // expected-error{{cannot convert return expression of type '(Y, X)' to return type '(Y, Z)'}}
}
func fail5<T: Barrable>(_ t: T) -> (Y, Z)
where
T.Bar.Foo == Z, // expected-note{{same-type constraint 'T.Bar.Foo' == 'Z' written here}}
T.Bar == Y { // expected-error{{'T.Bar.Foo' cannot be equal to both 'Y.Foo' (aka 'X') and 'Z'}}
return (t.bar, t.bar.foo) // expected-error{{cannot convert return expression of type '(Y, X)' to return type '(Y, Z)'}}
}
func test8<T: Fooable>(_ t: T)
where T.Foo == X, // expected-note{{same-type constraint 'T.Foo' == 'X' written here}}
T.Foo == Y {} // expected-error{{'T.Foo' cannot be equal to both 'Y' and 'X'}}
func testAssocTypeEquivalence<T: Fooable>(_ fooable: T) -> X.Type
where T.Foo == X {
return T.Foo.self
}
func fail6<T>(_ t: T) -> Int where T == Int { // expected-error{{same-type requirement makes generic parameter 'T' non-generic}}
return t
}
func test8<T: Barrable, U: Barrable>(_ t: T, u: U) -> (Y, Y, X, X)
where T.Bar == Y, // expected-note{{same-type constraint 'U.Bar.Foo' == 'Y.Foo' (aka 'X') implied here}}
U.Bar.Foo == X, T.Bar == U.Bar { // expected-warning{{redundant same-type constraint 'U.Bar.Foo' == 'X'}}
return (t.bar, u.bar, t.bar.foo, u.bar.foo)
}
func test8a<T: Barrable, U: Barrable>(_ t: T, u: U) -> (Y, Y, X, X)
where
T.Bar == Y, // expected-note{{same-type constraint 'U.Bar.Foo' == 'Y.Foo' (aka 'X') implied here}}
U.Bar.Foo == X, U.Bar == T.Bar { // expected-warning{{redundant same-type constraint 'U.Bar.Foo' == 'X'}}
return (t.bar, u.bar, t.bar.foo, u.bar.foo)
}
func test8b<T: Barrable, U: Barrable>(_ t: T, u: U)
where U.Bar.Foo == X, // expected-warning{{redundant same-type constraint 'U.Bar.Foo' == 'X'}}
T.Bar == Y, // expected-note{{same-type constraint 'U.Bar.Foo' == 'Y.Foo' (aka 'X') implied here}}
T.Bar == U.Bar {
}
// rdar://problem/19137463
func rdar19137463<T>(_ t: T) where T.a == T {} // expected-error{{'a' is not a member type of type 'T'}}
rdar19137463(1)
struct Brunch<U : Fooable> where U.Foo == X {}
struct BadFooable : Fooable { // expected-error{{type 'BadFooable' does not conform to protocol 'Fooable'}}
typealias Foo = DoesNotExist // expected-error{{cannot find type 'DoesNotExist' in scope}}
var foo: Foo { while true {} }
}
func bogusInOutError(d: inout Brunch<BadFooable>) {}
// Some interesting invalid cases that used to crash
protocol P {
associatedtype A
associatedtype B
}
struct Q : P {
typealias A = Int
typealias B = Int
}
struct S1<T : P> {
func foo<X, Y>(x: X, y: Y) where X == T.A, Y == T.B {
print(X.self)
print(Y.self)
print(x)
print(y)
}
}
S1<Q>().foo(x: 1, y: 2)
struct S2<T : P> where T.A == T.B {
func foo<X, Y>(x: X, y: Y) where X == T.A, Y == T.B { // expected-error{{same-type requirement makes generic parameters 'X' and 'Y' equivalent}}
print(X.self)
print(Y.self)
print(x)
print(y)
}
}
S2<Q>().foo(x: 1, y: 2)
struct S3<T : P> {
func foo<X, Y>(x: X, y: Y) where X == T.A, Y == T.A {} // expected-error{{same-type requirement makes generic parameters 'X' and 'Y' equivalent}}
}
S3<Q>().foo(x: 1, y: 2)
// Secondaries can be equated OK, even if we're imposing
// new conformances onto an outer secondary
protocol PPP {}
protocol PP {
associatedtype A : PPP
}
struct SSS : PPP {}
struct SS : PP { typealias A = SSS }
struct QQ : P {
typealias A = SSS
typealias B = Int
}
struct S4<T : P> {
func foo<X : PP>(x: X) where X.A == T.A {
print(x)
print(X.self)
}
}
S4<QQ>().foo(x: SS())
// rdar://problem/29333056 - allow deeper matching of same-type constraints.
struct X1<A, B> { }
protocol P1 {
associatedtype Assoc
}
func structuralSameType1<A: P1, B: P1, T, U, V, W>(_: A, _: B, _: T, _: U, _: V, _: W)
where A.Assoc == X1<T, U>, B.Assoc == X1<V, W>, A.Assoc == B.Assoc { }
// expected-error@-1{{same-type requirement makes generic parameters 'T' and 'V' equivalent}}
// expected-error@-2{{same-type requirement makes generic parameters 'U' and 'W' equivalent}}
typealias Tuple2<T, U> = (T, U)
func structuralSameType2<A: P1, B: P1, T, U, V, W>(_: A, _: B, _: T, _: U, _: V, _: W)
where A.Assoc == Tuple2<T, U>, B.Assoc == Tuple2<V, W>, A.Assoc == B.Assoc { }
// expected-error@-1{{same-type requirement makes generic parameters 'T' and 'V' equivalent}}
// expected-error@-2{{same-type requirement makes generic parameters 'U' and 'W' equivalent}}
func structuralSameType3<T, U, V, W>(_: T, _: U, _: V, _: W)
where X1<T, U> == X1<V, W> { }
// expected-error@-1{{same-type requirement makes generic parameters 'T' and 'V' equivalent}}
// expected-error@-2{{same-type requirement makes generic parameters 'U' and 'W' equivalent}}
// expected-warning@-3{{neither type in same-type constraint ('X1<T, U>' or 'X1<V, W>') refers to a generic parameter or associated type}}
protocol P2 {
associatedtype Assoc1
associatedtype Assoc2
}
func structuralSameTypeRecursive1<T: P2, U>(_: T, _: U)
where T.Assoc1 == Tuple2<T.Assoc1, U> // expected-error{{same-type constraint 'T.Assoc1' == '(T.Assoc1, U)' is recursive}}
{ }
protocol P3 {
}
protocol P4 {
associatedtype A
}
func test9<T>(_: T) where T.A == X, T: P4, T.A: P3 { } // expected-error{{same-type constraint type 'X' does not conform to required protocol 'P3'}}
// Same-type constraint conflict through protocol where clauses.
protocol P5 where Foo1 == Foo2 {
associatedtype Foo1
associatedtype Foo2
}
protocol P6 {
associatedtype Bar: P5
}
struct X5a {}
struct X5b { }
func test9<T: P6, U: P6>(_ t: T, u: U)
where T.Bar.Foo1 == X5a, // expected-note{{same-type constraint 'T.Bar.Foo1' == 'X5a' written here}}
U.Bar.Foo2 == X5b, // expected-error{{'U.Bar.Foo2' cannot be equal to both 'X5b' and 'X5a'}}
T.Bar == U.Bar {
}
// FIXME: Remove -verify-ignore-unknown.
// <unknown>:0: error: unexpected error produced: generic parameter τ_0_0.Bar.Foo cannot be equal to both 'Y.Foo' (aka 'X') and 'Z'
func testMetatypeSameType<T, U>(_ t: T, _ u: U)
where T.Type == U.Type { }
// expected-error@-1{{same-type requirement makes generic parameters 'T' and 'U' equivalent}}
// expected-warning@-2{{neither type in same-type constraint ('T.Type' or 'U.Type') refers to a generic parameter or associated type}}
func testSameTypeCommutativity1<U, T>(_ t: T, _ u: U)
where T.Type == U { } // Equivalent to U == T.Type
// expected-error@-1{{same-type requirement makes generic parameter 'U' non-generic}}
func testSameTypeCommutativity2<U, T: P1>(_ t: T, _ u: U)
where U? == T.Assoc { } // Ok, equivalent to T.Assoc == U?
func testSameTypeCommutativity3<U, T: P1>(_ t: T, _ u: U)
where (U) -> () == T.Assoc { } // Ok, equivalent to T.Assoc == (U) -> ()
func testSameTypeCommutativity4<U, T>(_ t: T, _ u: U)
where (U) -> () == T { } // Equivalent to T == (U) -> ()
// expected-error@-1{{same-type requirement makes generic parameter 'T' non-generic}}
func testSameTypeCommutativity5<U, T: P1>(_ t: T, _ u: U)
where PPP & P3 == T.Assoc { } // Ok, equivalent to T.Assoc == PPP & P3
// FIXME: Error emitted twice.
func testSameTypeCommutativity6<U, T: P1>(_ t: T, _ u: U)
where U & P3 == T.Assoc { } // Equivalent to T.Assoc == U & P3
// expected-error@-1 2 {{non-protocol, non-class type 'U' cannot be used within a protocol-constrained type}}
// rdar;//problem/46848889
struct Foo<A: P1, B: P1, C: P1> where A.Assoc == B.Assoc, A.Assoc == C.Assoc {}
struct Bar<A: P1, B: P1> where A.Assoc == B.Assoc {
func f<C: P1>(with other: C) -> Foo<A, B, C> where A.Assoc == C.Assoc {
// expected-note@-1 {{previous same-type constraint 'B.Assoc' == 'C.Assoc' inferred from type here}}
// expected-warning@-2 {{redundant same-type constraint 'A.Assoc' == 'C.Assoc'}}
fatalError()
}
}
protocol P7 {
associatedtype A
static func fn(args: A)
}
class R<T>: P7 where T: P7, T.A == T.Type { // expected-note {{'T' declared as parameter to type 'R'}}
typealias A = T.Type
static func fn(args: T.Type) {}
}
R.fn(args: R.self) // expected-error {{generic parameter 'T' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}}
// rdar://problem/58607155
protocol AssocType1 { associatedtype A }
protocol AssocType2 { associatedtype A }
func rdar58607155() {
func f<T1: AssocType1, T2: AssocType2>(t1: T1, t2: T2) where T1.A == T2.A {}
// expected-note@-1 2 {{where 'T2' = 'MissingConformance'}}
// expected-note@-2 2 {{where 'T1' = 'MissingConformance'}}
class Conformance: AssocType1, AssocType2 { typealias A = Int }
class MissingConformance {}
// One generic argument has a conformance failure
f(t1: MissingConformance(), t2: Conformance()) // expected-error {{local function 'f(t1:t2:)' requires that 'MissingConformance' conform to 'AssocType1'}}
f(t1: Conformance(), t2: MissingConformance()) // expected-error {{local function 'f(t1:t2:)' requires that 'MissingConformance' conform to 'AssocType2'}}
// Both generic arguments have a conformance failure
f(t1: MissingConformance(), t2: MissingConformance())
// expected-error@-1 {{local function 'f(t1:t2:)' requires that 'MissingConformance' conform to 'AssocType1'}}
// expected-error@-2 {{local function 'f(t1:t2:)' requires that 'MissingConformance' conform to 'AssocType2'}}
}
| apache-2.0 | 18a1b69ee580bdb3254d9d5d03007f68 | 33.741573 | 156 | 0.631792 | 2.905332 | false | true | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Synthesis.playground/Pages/Oscillator.xcplaygroundpage/Contents.swift | 1 | 2194 | //: ## Oscillator
//: This oscillator can be loaded with a wavetable of your own design,
//: or with one of the defaults.
import AudioKitPlaygrounds
import AudioKit
import AudioKitUI
let square = AKTable(.square, count: 256)
let triangle = AKTable(.triangle, count: 256)
let sine = AKTable(.sine, count: 256)
let sawtooth = AKTable(.sawtooth, count: 256)
//: Try changing the table to triangle, square, sine, or sawtooth.
//: This will change the shape of the oscillator's waveform.
var oscillator = AKOscillator(waveform: square)
AudioKit.output = oscillator
AudioKit.start()
var currentMIDINote: MIDINoteNumber = 0
var currentAmplitude = 0.2
var currentRampTime = 0.05
oscillator.rampTime = currentRampTime
oscillator.amplitude = currentAmplitude
class LiveView: AKLiveViewController, AKKeyboardDelegate {
override func viewDidLoad() {
addTitle("General Purpose Oscillator")
addView(AKSlider(property: "Amplitude", value: currentAmplitude) { amplitude in
currentAmplitude = amplitude
})
addView(AKSlider(property: "Ramp Time", value: currentRampTime) { time in
currentRampTime = time
})
let keyboard = AKKeyboardView(width: 440,
height: 100,
firstOctave: 4,
octaveCount: 4)
keyboard.delegate = self
addView(keyboard)
addView(AKOutputWaveformPlot.createView())
}
func noteOn(note: MIDINoteNumber) {
currentMIDINote = note
// start from the correct note if amplitude is zero
if oscillator.amplitude == 0 {
oscillator.rampTime = 0
}
oscillator.frequency = note.midiNoteToFrequency()
// Still use rampTime for volume
oscillator.rampTime = currentRampTime
oscillator.amplitude = currentAmplitude
oscillator.play()
}
func noteOff(note: MIDINoteNumber) {
if note == currentMIDINote {
oscillator.amplitude = 0
}
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
| mit | 717400fd06ae120d756522e33d2ab083 | 29.901408 | 87 | 0.658159 | 4.886414 | false | false | false | false |
rene-dohan/CS-IOS | Renetik/Renetik/Classes/Core/Classes/Controller/CSSelectNameController.swift | 1 | 2990 | //
// CSSelectNameController.swift
// Renetik
//
// Created by Rene Dohan on 2/20/19.
//
import RenetikObjc
public typealias CSNameRowType = CSNameProtocol & CustomStringConvertible & Equatable
public class CSSelectNameController<Data: CSNameRowType>:
CSMainController, UITableViewDelegate, UITableViewDataSource {
public let table = UITableView.construct()
public let search = CSSearchBarController()
public var onCellCreate: ((UITableViewCell) -> Void)? = nil
public var selectedName: Data?
private var names: [Data] = []
private var filteredData: [Data] = []
private var onSelected: ((Data) -> Void)!
private var onDelete: ((Data) -> CSResponseProtocol)?
@discardableResult
public func construct(data: [Data], onSelected: @escaping (Data) -> Void) -> Self {
self.names = data
self.onSelected = onSelected
return self
}
@discardableResult
public func addDelete<T: AnyObject>(_ onDelete: @escaping (Data) -> CSResponse<T>) -> Self {
self.onDelete = onDelete
menu(type: .edit) { $0.systemItem = self.table.toggleEditing().isEditing ? .cancel : .edit }
return self
}
public override func onViewWillAppear() {
super.onViewWillAppear()
view.add(view: table).matchParent()
table.hideEmptySeparatorsByEmptyFooter()
table.allowsMultipleSelectionDuringEditing = false
search.construct(by: self) { _ in self.reload() }
table.tableHeaderView = search.bar
table.delegates(self)
reload()
}
private func reload() {
filteredData = names.filter(bySearch: search.text)
table.reload()
}
public func tableView(_ tableView: UITableView,
cellForRowAt path: IndexPath) -> UITableViewCell {
tableView.cell(style: .default, onCreate: onCellCreate)
.also { $0.textLabel!.text = filteredData[path.row].name }
}
public func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
filteredData.count
}
public func tableView(_ tableView: UITableView,
didSelectRowAt path: IndexPath) {
selectedName = filteredData[path.row]
navigation.popViewController()
onSelected!(selectedName!)
}
public func tableView(_ tableView: UITableView,
canEditRowAt path: IndexPath) -> Bool {
onDelete.notNil
}
public func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCell.EditingStyle,
forRowAt path: IndexPath) {
if editingStyle == .delete {
let value = filteredData[path.row]
onDelete?(value).onSuccess {
self.names.remove(value)
if self.names.isEmpty { navigation.popViewController() } else { self.reload() }
}
}
}
}
| mit | 28376560aa764c7acb89375bcc9e5867 | 32.222222 | 100 | 0.621739 | 4.942149 | false | false | false | false |
cacawai/Tap2Read | tap2read/Pods/Cartography/Cartography/Distribute.swift | 11 | 2462 | //
// Distribute.swift
// Cartography
//
// Created by Robert Böhnke on 17/02/15.
// Copyright (c) 2015 Robert Böhnke. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
typealias Accumulator = ([NSLayoutConstraint], LayoutProxy)
@discardableResult private func reduce(_ first: LayoutProxy, rest: [LayoutProxy], combine: (LayoutProxy, LayoutProxy) -> NSLayoutConstraint) -> [NSLayoutConstraint] {
rest.last?.view.car_translatesAutoresizingMaskIntoConstraints = false
return rest.reduce(([], first)) { (acc, current) -> Accumulator in
let (constraints, previous) = acc
return (constraints + [ combine(previous, current) ], current)
}.0
}
/// Distributes multiple views horizontally.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter amount: The distance between the views.
/// - parameter views: The views to distribute.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func distribute(by amount: CGFloat, horizontally first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return reduce(first, rest: rest) { $0.trailing == $1.leading - amount }
}
/// Distributes multiple views horizontally from left to right.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter amount: The distance between the views.
/// - parameter views: The views to distribute.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func distribute(by amount: CGFloat, leftToRight first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return reduce(first, rest: rest) { $0.right == $1.left - amount }
}
/// Distributes multiple views vertically.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter amount: The distance between the views.
/// - parameter views: The views to distribute.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
@discardableResult public func distribute(by amount: CGFloat, vertically first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return reduce(first, rest: rest) { $0.bottom == $1.top - amount }
}
| mit | 0459bca6b949b298a7e4181b352edf0d | 35.716418 | 166 | 0.710569 | 4.353982 | false | false | false | false |
google/iosched-ios | Source/IOsched/Screens/Onboarding/OnboardingExploreViewController.swift | 1 | 1943 | //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import MaterialComponents
import GoogleSignIn
import FirebaseAuth
class OnboardingExploreViewController: BaseOnboardingViewController {
override var titleText: String {
return NSLocalizedString("Explore I/O",
comment: "Short title explaining the Explore feature.")
}
override var subtitleText: String {
return NSLocalizedString("Scan signposts to explore the conference venue in AR.",
comment: "Short promotional text describing how to use the Explore feature.")
}
override var nextButtonTitle: String {
return NSLocalizedString("Get started",
comment: "Text for button that exits the onboarding flow.")
}
override func nextButtonPressed(_ sender: Any) {
viewModel.finishOnboardingFlow()
}
override func viewDidLoad() {
super.viewDidLoad()
if let countdown = headerView as? CountdownView {
countdown.play()
}
}
override func setupHeaderView() -> UIImageView {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
let image = UIImage(named: "onboarding_explore")
imageView.image = image
imageView.contentMode = .bottom
imageView.setContentHuggingPriority(.required, for: .vertical)
return imageView
}
}
| apache-2.0 | ab22b4668e0c51335d24f76914d159e6 | 31.383333 | 106 | 0.707154 | 4.956633 | false | false | false | false |
0x8badf00d/Layers | Layers/Layers/RainforestCardCell.swift | 1 | 2956 | //
// RainforestCardCell.swift
// Layers
//
// Created by René Cacheaux on 9/1/14.
// Copyright (c) 2014 Razeware LLC. All rights reserved.
//
import UIKit
class RainforestCardCell: UICollectionViewCell {
let featureImageView = UIImageView()
let backgroundImageView = UIImageView()
let titleLabel = UILabel()
let descriptionTextView = UITextView()
let gradientView = LAGradientView()
var featureImageSizeOptional: CGSize?
override func awakeFromNib() {
super.awakeFromNib()
contentView.addSubview(backgroundImageView)
contentView.addSubview(featureImageView)
contentView.addSubview(gradientView)
contentView.addSubview(titleLabel)
contentView.addSubview(descriptionTextView)
contentView.layer.borderColor = UIColor(hue: 0, saturation: 0, brightness: 0.85, alpha: 0.2).CGColor
contentView.layer.borderWidth = 1
}
//MARK: Layout
override func sizeThatFits(size: CGSize) -> CGSize {
if let featureImageSize = featureImageSizeOptional {
return FrameCalculator.sizeThatFits(size, withImageSize: featureImageSize)
} else {
return CGSizeZero
}
}
override func layoutSubviews() {
super.layoutSubviews()
let featureImageSize = featureImageSizeOptional ?? CGSizeZero
backgroundImageView.frame = FrameCalculator.frameForBackgroundImage(containerBounds: bounds)
featureImageView.frame = FrameCalculator.frameForFeatureImage(featureImageSize: featureImageSize,
containerFrameWidth: frame.size.width)
gradientView.frame = FrameCalculator.frameForGradient(featureImageFrame: featureImageView.frame)
titleLabel.frame = FrameCalculator.frameForTitleText(containerBounds: bounds,
featureImageFrame: featureImageView.frame)
descriptionTextView.frame = FrameCalculator.frameForDescriptionText(containerBounds: bounds,
featureImageFrame: featureImageView.frame)
}
//MARK: Cell Reuse
override func prepareForReuse() {
super.prepareForReuse()
}
//MARK: Subviews
func configureCellDisplayWithCardInfo(cardInfo: RainforestCardInfo) {
let image = UIImage(named: cardInfo.imageName)
featureImageSizeOptional = image.size
featureImageView.contentMode = .ScaleAspectFit
featureImageView.image = image
backgroundImageView.contentMode = .ScaleAspectFill
backgroundImageView.image = image.applyBlurWithRadius(30, tintColor: UIColor(white: 0.5, alpha: 0.3),
saturationDeltaFactor: 1.8, maskImage: nil)
descriptionTextView.backgroundColor = UIColor.clearColor()
descriptionTextView.editable = false
descriptionTextView.scrollEnabled = false
descriptionTextView.attributedText = NSAttributedString.attributedStringForDescriptionText(cardInfo.description)
titleLabel.backgroundColor = UIColor.clearColor()
titleLabel.attributedText = NSAttributedString.attributesStringForTitleText(cardInfo.name)
gradientView.setNeedsDisplay()
}
}
| apache-2.0 | 2d48267791ce3d6837f247d87277a2e8 | 35.036585 | 116 | 0.76379 | 5.07732 | false | false | false | false |
ijovi23/JvPunchIO | JvPunchIO-Recorder/Pods/FileKit/Sources/DispatchEvent.swift | 3 | 3446 | //
// GCDFSEvent.swift
// FileKit
//
// Created by ijump on 5/2/16.
// Copyright © 2016 Nikolai Vazquez. All rights reserved.
//
import Foundation
/// File System Events.
public struct DispatchFileSystemEvents: OptionSet, CustomStringConvertible, CustomDebugStringConvertible {
// MARK: - Events
/// The file-system object was deleted from the namespace.
public static let Delete = DispatchFileSystemEvents(rawValue: DispatchSource.FileSystemEvent.delete.rawValue)
/// The file-system object data changed.
public static let Write = DispatchFileSystemEvents(rawValue: DispatchSource.FileSystemEvent.write.rawValue)
/// The file-system object changed in size.
public static let Extend = DispatchFileSystemEvents(rawValue: DispatchSource.FileSystemEvent.extend.rawValue)
/// The file-system object metadata changed.
public static let Attribute = DispatchFileSystemEvents(rawValue: DispatchSource.FileSystemEvent.attrib.rawValue)
/// The file-system object link count changed.
public static let Link = DispatchFileSystemEvents(rawValue: DispatchSource.FileSystemEvent.link.rawValue)
/// The file-system object was renamed in the namespace.
public static let Rename = DispatchFileSystemEvents(rawValue: DispatchSource.FileSystemEvent.rename.rawValue)
/// The file-system object was revoked.
public static let Revoke = DispatchFileSystemEvents(rawValue: DispatchSource.FileSystemEvent.revoke.rawValue)
/// The file-system object was created.
public static let Create = DispatchFileSystemEvents(rawValue: 0x1000)
/// All of the event IDs.
public static let All: DispatchFileSystemEvents = [.Delete, .Write, .Extend, .Attribute, .Link, .Rename, .Revoke, .Create]
// MARK: - All Events
/// An array of all of the events.
public static let allEvents: [DispatchFileSystemEvents] = [
.Delete, .Write, .Extend, .Attribute, .Link, .Rename, .Revoke, .Create
]
/// The names of all of the events.
public static let allEventNames: [String] = [
"Delete", "Write", "Extend", "Attribute", "Link", "Rename", "Revoke", "Create"
]
// MARK: - Properties
/// The raw event value.
public let rawValue: UInt
/// A textual representation of `self`.
public var description: String {
var result = ""
for (index, element) in DispatchFileSystemEvents.allEvents.enumerated() {
if self.contains(element) {
let name = DispatchFileSystemEvents.allEventNames[index]
result += result.isEmpty ? "\(name)": ", \(name)"
}
}
return String(describing: type(of: self)) + "[\(result)]"
}
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
var result = ""
for (index, element) in DispatchFileSystemEvents.allEvents.enumerated() {
if self.contains(element) {
let name = DispatchFileSystemEvents.allEventNames[index] + "(\(element.rawValue))"
result += result.isEmpty ? "\(name)": ", \(name)"
}
}
return String(describing: type(of: self)) + "[\(result)]"
}
// MARK: - Initialization
/// Creates a set of events from a raw value.
///
/// - Parameter rawValue: The raw value to initialize from.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
}
| mit | d8becffe4a89a3536e3f809ffd416a2e | 36.043011 | 126 | 0.672279 | 4.649123 | false | false | false | false |
hoanganh6491/Net | Net/NetUploadTask.swift | 2 | 4045 | //
// NetUploadTask.swift
// Net
//
// Created by Le Van Nghia on 8/4/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import Foundation
protocol UploadTaskDelegate {
func didCreateUploadTask(task: NSURLSessionUploadTask, uploadTask: UploadTask)
func didRemoveUploadTask(task: NSURLSessionUploadTask)
}
class UploadTask
{
enum State {
case Init, Uploading, Suspending, Canceled, Completed, Failed
}
typealias ProgressHandler = (Float) -> ()
typealias CompletionHandler = (NSError?) -> ()
private var session: NSURLSession
private var delegate: UploadTaskDelegate
private var task: NSURLSessionUploadTask!
private var request: NSMutableURLRequest
private var progressHandler: ProgressHandler?
private var completionHandler: CompletionHandler
private var state: State = .Init
init(_ session: NSURLSession,_ delegate: UploadTaskDelegate,_ absoluteUrl: String,_ progressHandler: ProgressHandler?,_ completionHandler: CompletionHandler) {
self.session = session
self.delegate = delegate
let url = NSURL(string: absoluteUrl)
self.request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = HttpMethod.POST.rawValue
self.progressHandler = progressHandler
self.completionHandler = completionHandler
}
convenience init(session: NSURLSession, delegate: UploadTaskDelegate, absoluteUrl: String, data: NSData, progressHandler: ProgressHandler?, completionHandler: CompletionHandler) {
self.init(session, delegate, absoluteUrl, progressHandler, completionHandler)
// TODO: config for request
request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
task = session.uploadTaskWithRequest(request, fromData: data)
delegate.didCreateUploadTask(task, uploadTask: self)
}
convenience init(session: NSURLSession, delegate: UploadTaskDelegate, absoluteUrl: String, params: NSDictionary, progressHandler: ProgressHandler?, completionHandler: CompletionHandler) {
self.init(session, delegate, absoluteUrl, progressHandler, completionHandler)
let boundary = "NET-UPLOAD-boundary-\(arc4random())-\(arc4random())"
let paramsData = NetHelper.dataFromParamsWithBoundary(params, boundary: boundary)
let contentType = "multipart/form-data; boundary=\(boundary)"
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.setValue("\(paramsData.length)", forHTTPHeaderField: "Content-Length")
task = session.uploadTaskWithRequest(request, fromData: paramsData)
delegate.didCreateUploadTask(task, uploadTask: self)
}
convenience init(session: NSURLSession, delegate: UploadTaskDelegate, absoluteUrl: String, fromFile: NSURL, progressHandler: ProgressHandler?, completionHandler: CompletionHandler) {
self.init(session, delegate, absoluteUrl, progressHandler, completionHandler)
task = session.uploadTaskWithRequest(request, fromFile: fromFile)
delegate.didCreateUploadTask(task, uploadTask: self)
}
func setHttpMethod(method: HttpMethod) {
request.HTTPMethod = method.rawValue
}
func setValue(value: String, forHttpHeaderField field: String) {
request.setValue(value, forHTTPHeaderField: field)
}
func resume() {
task.resume()
state = .Uploading
}
func suspend() {
if state == .Uploading {
task.suspend()
state = .Suspending
}
}
func cancel() {
if state == .Uploading {
task.cancel()
state = .Canceled
}
}
func updateProgress(progress: Float) {
self.progressHandler?(progress)
}
func didComplete(error: NSError?) {
state = error != nil ? .Failed : .Completed
completionHandler(error)
}
} | mit | cf603a6d9ad1d46b9ae361080e4fd504 | 34.182609 | 191 | 0.67466 | 5.364721 | false | false | false | false |
jeremyabannister/JABSwiftCore | JABSwiftCore/iOSStringSizeCalculator.swift | 1 | 1015 | //
// iOSStringSizeCalculator.swift
// JABSwiftCore
//
// Created by Jeremy Bannister on 6/8/18.
// Copyright © 2018 Jeremy Bannister. All rights reserved.
//
import UIKit
public class iOSStringSizeCalculator: StringSizeCalculator {
public func size (of string: String, constrainedToWidth width: Double?, usingFont font: Font) -> Size {
var attributes: [NSAttributedStringKey: Any] = [.font: UIFont(font) as Any]
attributes[.kern] = font.characterSpacing
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = CGFloat(font.lineHeightMultiple)
attributes[.paragraphStyle] = paragraphStyle
return (string as NSString).boundingRect(with: CGSize(width: width ?? 0, height: Double.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: attributes,
context: nil).size.asSize
}
}
| mit | f6302377938a0c20c2461415e51e33f6 | 41.25 | 117 | 0.658777 | 5.253886 | false | false | false | false |
practicalswift/swift | test/TypeDecoder/foreign_types.swift | 1 | 4488 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -I %S/../ClangImporter/Inputs/custom-modules -I %S/../Inputs/custom-modules -emit-executable -emit-module %s -g -o %t/foreign_types
// RUN: sed -ne '/\/\/ *DEMANGLE-TYPE: /s/\/\/ *DEMANGLE-TYPE: *//p' < %s > %t/input
// RUN: %lldb-moduleimport-test-with-sdk %t/foreign_types -type-from-mangled=%t/input | %FileCheck %s --check-prefix=CHECK-TYPE
// RUN: sed -ne '/\/\/ *DEMANGLE-DECL: /s/\/\/ *DEMANGLE-DECL: *//p' < %s > %t/input
// RUN: %lldb-moduleimport-test-with-sdk %t/foreign_types -decl-from-mangled=%t/input | %FileCheck %s --check-prefix=CHECK-DECL
// REQUIRES: objc_interop
import Foundation
import CoreCooling
import ErrorEnums
extension CCRefrigerator {
struct InternalNestedType {}
fileprivate struct PrivateNestedType {}
}
/*
do {
let x1 = CCRefrigeratorCreate(kCCPowerStandard)
let x2 = MyError.good
let x3 = MyError.Code.good
let x4 = RenamedError.good
let x5 = RenamedError.Code.good
let x6 = Wrapper.MemberEnum.A
let x7 = WrapperByAttribute(0)
let x8 = IceCube(width: 0, height: 0, depth: 0)
let x9 = BlockOfIce(width: 0, height: 0, depth: 0)
}
do {
let x1 = CCRefrigerator.self
let x2 = MyError.self
let x3 = MyError.Code.self
let x4 = RenamedError.self
let x5 = RenamedError.Code.self
let x6 = Wrapper.MemberEnum.self
let x7 = WrapperByAttribute.self
let x8 = IceCube.self
let x9 = BlockOfIce.self
}
*/
// DEMANGLE-TYPE: $sSo17CCRefrigeratorRefaD
// DEMANGLE-TYPE: $sSo7MyErrorVD
// DEMANGLE-TYPE: $sSo7MyErrorLeVD
// DEMANGLE-TYPE: $sSo14MyRenamedErrorVD
// DEMANGLE-TYPE: $sSo14MyRenamedErrorLeVD
// DEMANGLE-TYPE: $sSo12MyMemberEnumVD
// DEMANGLE-TYPE: $sSo18WrapperByAttributeaD
// DEMANGLE-TYPE: $sSo7IceCubeVD
// DEMANGLE-TYPE: $sSo10BlockOfIceaD
// DEMANGLE-TYPE: $sSo17CCRefrigeratorRefa13foreign_typesE18InternalNestedTypeVD
// DEMANGLE-TYPE: $sSo17CCRefrigeratorRefa13foreign_typesE17PrivateNestedType33_5415CB6AE6FCD935BF2278A4C9A5F9C3LLVD
// CHECK-TYPE: CCRefrigerator
// CHECK-TYPE: MyError.Code
// CHECK-TYPE: MyError
// CHECK-TYPE: RenamedError.Code
// CHECK-TYPE: RenamedError
// CHECK-TYPE: Wrapper.MemberEnum
// CHECK-TYPE: WrapperByAttribute
// CHECK-TYPE: IceCube
// CHECK-TYPE: BlockOfIce
// CHECK-TYPE: CCRefrigerator.InternalNestedType
// CHECK-TYPE: CCRefrigerator.PrivateNestedType
// DEMANGLE-TYPE: $sSo17CCRefrigeratorRefamD
// DEMANGLE-TYPE: $sSo7MyErrorVmD
// DEMANGLE-TYPE: $sSC7MyErrorLeVmD
// DEMANGLE-TYPE: $sSo14MyRenamedErrorVmD
// DEMANGLE-TYPE: $sSC14MyRenamedErrorLeVmD
// DEMANGLE-TYPE: $sSo12MyMemberEnumVmD
// DEMANGLE-TYPE: $sSo18WrapperByAttributeamD
// DEMANGLE-TYPE: $sSo7IceCubeVmD
// DEMANGLE-TYPE: $sSo10BlockOfIceamD
// DEMANGLE-TYPE: $sSo17CCRefrigeratorRefa13foreign_typesE18InternalNestedTypeVmD
// DEMANGLE-TYPE: $sSo17CCRefrigeratorRefa13foreign_typesE17PrivateNestedType33_5415CB6AE6FCD935BF2278A4C9A5F9C3LLVmD
// CHECK-TYPE: CCRefrigerator.Type
// CHECK-TYPE: MyError.Code.Type
// CHECK-TYPE: MyError.Type
// CHECK-TYPE: RenamedError.Code.Type
// CHECK-TYPE: RenamedError.Type
// CHECK-TYPE: Wrapper.MemberEnum.Type
// CHECK-TYPE: WrapperByAttribute.Type
// CHECK-TYPE: IceCube.Type
// CHECK-TYPE: BlockOfIce.Type
// CHECK-TYPE: CCRefrigerator.InternalNestedType.Type
// CHECK-TYPE: CCRefrigerator.PrivateNestedType.Type
// DEMANGLE-DECL: $sSo17CCRefrigeratorRefa
// DEMANGLE-DECL: $sSo7MyErrorV
// DEMANGLE-DECL: $sSo7MyErrorLeV
// DEMANGLE-DECL: $sSo14MyRenamedErrorV
// DEMANGLE-DECL: $sSo14MyRenamedErrorLeV
// DEMANGLE-DECL: $sSo12MyMemberEnumV
// DEMANGLE-DECL: $sSo18WrapperByAttributea
// DEMANGLE-DECL: $sSo7IceCubeV
// DEMANGLE-DECL: $sSo10BlockOfIcea
// DEMANGLE-DECL: $sSo17CCRefrigeratorRefa13foreign_typesE18InternalNestedTypeV
// DEMANGLE-DECL: $sSo17CCRefrigeratorRefa13foreign_typesE17PrivateNestedType33_5415CB6AE6FCD935BF2278A4C9A5F9C3LLV
// CHECK-DECL: CoreCooling.(file).CCRefrigerator
// CHECK-DECL: ErrorEnums.(file).MyError.Code
// CHECK-DECL: ErrorEnums.(file).MyError.Code
// CHECK-DECL: ErrorEnums.(file).RenamedError.Code
// CHECK-DECL: ErrorEnums.(file).RenamedError.Code
// CHECK-DECL: ErrorEnums.(file).Wrapper extension.MemberEnum
// CHECK-DECL: ErrorEnums.(file).WrapperByAttribute
// CHECK-DECL: CoreCooling.(file).IceCube
// CHECK-DECL: CoreCooling.(file).BlockOfIce
// CHECK-DECL: foreign_types.(file).CCRefrigerator extension.InternalNestedType
// CHECK-DECL: foreign_types.(file).CCRefrigerator extension.PrivateNestedType
| apache-2.0 | 6ec7b34e7adbba46ba9545a9e5bf5bd3 | 37.033898 | 159 | 0.761141 | 3.212598 | false | false | false | false |
practicalswift/swift | test/Generics/conditional_conformances_objc.swift | 40 | 2360 | // RUN: %target-typecheck-verify-swift -import-objc-header %S/Inputs/conditional_conformances_objc.h
// REQUIRES: objc_interop
protocol Foo {}
extension ObjC: Foo where ObjectType == ObjC2 {}
// expected-error@-1{{type 'ObjC<ObjectType>' cannot conditionally conform to protocol 'Foo' because the type uses the Objective-C generics model}}
protocol Bar {}
extension ObjC: Bar where ObjectType: Bar {}
// expected-error@-1{{type 'ObjC<ObjectType>' cannot conditionally conform to protocol 'Bar' because the type uses the Objective-C generics model}}
extension ObjC {
struct Struct {
enum Enum {}
}
class Class<T> {}
}
extension ObjC.Struct: Foo where ObjectType == ObjC2 {}
// expected-error@-1{{type 'ObjC<ObjectType>.Struct' cannot conditionally conform to protocol 'Foo' because the type uses the Objective-C generics model}}
extension ObjC.Struct: Bar where ObjectType: Bar {}
// expected-error@-1{{type 'ObjC<ObjectType>.Struct' cannot conditionally conform to protocol 'Bar' because the type uses the Objective-C generics model}}
extension ObjC.Struct.Enum: Foo where ObjectType == ObjC2 {}
// expected-error@-1{{type 'ObjC<ObjectType>.Struct.Enum' cannot conditionally conform to protocol 'Foo' because the type uses the Objective-C generics model}}
extension ObjC.Struct.Enum: Bar where ObjectType: Bar {}
// expected-error@-1{{type 'ObjC<ObjectType>.Struct.Enum' cannot conditionally conform to protocol 'Bar' because the type uses the Objective-C generics model}}
extension ObjC.Class: Foo where T == ObjC2 {}
// expected-error@-1{{type 'ObjC<ObjectType>.Class<T>' cannot conditionally conform to protocol 'Foo' because the type uses the Objective-C generics model}}
extension ObjC.Class: Bar where T: Bar {}
// expected-error@-1{{type 'ObjC<ObjectType>.Class<T>' cannot conditionally conform to protocol 'Bar' because the type uses the Objective-C generics model}}
@objc protocol AtObjCProtocol {}
class X<T> {}
extension X: ObjCProtocol where T: Foo {}
// expected-error@-1{{type 'X<T>' cannot conditionally conform to @objc protocol 'ObjCProtocol' because Objective-C does not support conditional conformances}}
extension X: AtObjCProtocol where T: Foo {}
// expected-error@-1{{type 'X<T>' cannot conditionally conform to @objc protocol 'AtObjCProtocol' because Objective-C does not support conditional conformances}}
| apache-2.0 | 32a759ea91cff1aaed9ac2290693f377 | 55.190476 | 161 | 0.755932 | 4.169611 | false | false | false | false |
arthurhammer/Rulers | Rulers/Model/PropertyListRepresentable/WindowConfig+PropertyListRepresentable.swift | 1 | 1711 | import Foundation
import class AppKit.NSColor
extension WindowConfig: PropertyListRepresentable {
var propertyListValue: PropertyList {
return [
"size": size.propertyListValue,
"mouseOffset": mouseOffset.propertyListValue,
"canMoveOffscreen": canMoveOffscreen,
"color": color.archived(),
"alpha": alpha,
"cornerRadius": cornerRadius,
"hasShadow": hasShadow,
"joinsAllSpaces": joinsAllSpaces,
"ignoresMouseEvents": ignoresMouseEvents
]
}
init?(propertyList: PropertyList) {
let p = propertyList
guard
let size = (p["size"] as? PropertyList).flatMap(CGSize.init(propertyList:)),
let mouseOffset = (p["mouseOffset"] as? PropertyList).flatMap(Offset.init(propertyList:)),
let canMoveOffscreen = p["canMoveOffscreen"] as? Bool,
let color = (p["color"] as? Data).flatMap(NSColor.unarchived),
let alpha = p["alpha"] as? Double,
let cornerRadius = p["cornerRadius"] as? Double,
let hasShadow = p["hasShadow"] as? Bool,
let joinsAllSpaces = p["joinsAllSpaces"] as? Bool,
let ignoresMouseEvents = p["ignoresMouseEvents"] as? Bool
else {
return nil
}
self = WindowConfig(
size: size,
mouseOffset: mouseOffset,
canMoveOffscreen: canMoveOffscreen,
color: color,
alpha: alpha,
cornerRadius: cornerRadius,
hasShadow: hasShadow,
joinsAllSpaces: joinsAllSpaces,
ignoresMouseEvents: ignoresMouseEvents
)
}
}
| mit | 9080900cde63242be185068f9d333714 | 33.918367 | 102 | 0.584454 | 5.153614 | false | false | false | false |
Witcast/witcast-ios | Pods/Material/Sources/iOS/Layout.swift | 1 | 41811 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public class Layout {
/// Parent UIView context.
internal weak var parent: UIView?
/// Child UIView context.
internal weak var child: UIView?
/**
An initializer that takes in a parent context.
- Parameter parent: An optional parent UIView.
*/
public init(parent: UIView?) {
self.parent = parent
}
/**
An initializer that takes in a parent context and child context.
- Parameter parent: An optional parent UIView.
- Parameter child: An optional child UIView.
*/
public init(parent: UIView?, child: UIView?) {
self.parent = parent
self.child = child
}
/**
Prints a debug message when the parent context is not available.
- Parameter function: A String representation of the function that
caused the issue.
- Returns: The current Layout instance.
*/
internal func debugParentNotAvailableMessage(function: String = #function) -> Layout {
debugPrint("[Material Layout Error: Parent view context is not available for \(function).")
return self
}
/**
Prints a debug message when the child context is not available.
- Parameter function: A String representation of the function that
caused the issue.
- Returns: The current Layout instance.
*/
internal func debugChildNotAvailableMessage(function: String = #function) -> Layout {
debugPrint("[Material Layout Error: Child view context is not available for \(function).")
return self
}
/**
Sets the width of a view.
- Parameter child: A child UIView to layout.
- Parameter width: A CGFloat value.
- Returns: The current Layout instance.
*/
@discardableResult
public func width(_ child: UIView, width: CGFloat) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.width(parent: v, child: child, width: width)
return self
}
/**
Sets the width of a view assuming a child context view.
- Parameter width: A CGFloat value.
- Returns: The current Layout instance.
*/
@discardableResult
public func width(_ width: CGFloat) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.width(v, width: width)
}
/**
Sets the height of a view.
- Parameter child: A child UIView to layout.
- Parameter height: A CGFloat value.
- Returns: The current Layout instance.
*/
@discardableResult
public func height(_ child: UIView, height: CGFloat) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.height(parent: v, child: child, height: height)
return self
}
/**
Sets the height of a view assuming a child context view.
- Parameter height: A CGFloat value.
- Returns: The current Layout instance.
*/
@discardableResult
public func height(_ height: CGFloat) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.height(v, height: height)
}
/**
Sets the width and height of a view.
- Parameter child: A child UIView to layout.
- Parameter size: A CGSize value.
- Returns: The current Layout instance.
*/
@discardableResult
public func size(_ child: UIView, size: CGSize) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.size(parent: v, child: child, size: size)
return self
}
/**
Sets the width and height of a view assuming a child context view.
- Parameter size: A CGSize value.
- Returns: The current Layout instance.
*/
@discardableResult
public func size(_ size: CGSize = CGSize.zero) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.size(v, size: size)
}
/**
A collection of children views are horizontally stretched with optional left,
right padding and interim interimSpace.
- Parameter children: An Array UIView to layout.
- Parameter left: A CGFloat value for padding the left side.
- Parameter right: A CGFloat value for padding the right side.
- Parameter interimSpace: A CGFloat value for interim interimSpace.
- Returns: The current Layout instance.
*/
@discardableResult
public func horizontally(_ children: [UIView], left: CGFloat = 0, right: CGFloat = 0, interimSpace: InterimSpace = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
Layout.horizontally(parent: v, children: children, left: left, right: right, interimSpace: interimSpace)
return self
}
/**
A collection of children views are vertically stretched with optional top,
bottom padding and interim interimSpace.
- Parameter children: An Array UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter interimSpace: A CGFloat value for interim interimSpace.
- Returns: The current Layout instance.
*/
@discardableResult
public func vertically(_ children: [UIView], top: CGFloat = 0, bottom: CGFloat = 0, interimSpace: InterimSpace = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
Layout.vertically(parent: v, children: children, top: top, bottom: bottom, interimSpace: interimSpace)
return self
}
/**
A child view is horizontally stretched with optional left and right padding.
- Parameter child: A child UIView to layout.
- Parameter left: A CGFloat value for padding the left side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func horizontally(_ child: UIView, left: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.horizontally(parent: v, child: child, left: left, right: right)
return self
}
/**
A child view is horizontally stretched with optional left and right padding.
- Parameter left: A CGFloat value for padding the left side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func horizontally(left: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return horizontally(v, left: left, right: right)
}
/**
A child view is vertically stretched with optional left and right padding.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Returns: The current Layout instance.
*/
@discardableResult
public func vertically(_ child: UIView, top: CGFloat = 0, bottom: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.vertically(parent: v, child: child, top: top, bottom: bottom)
return self
}
/**
A child view is vertically stretched with optional left and right padding.
- Parameter top: A CGFloat value for padding the top side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Returns: The current Layout instance.
*/
@discardableResult
public func vertically(top: CGFloat = 0, bottom: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return vertically(v, top: top, bottom: bottom)
}
/**
A child view is vertically and horizontally stretched with optional top, left, bottom and right padding.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter left: A CGFloat value for padding the left side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func edges(_ child: UIView, top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.edges(parent: v, child: child, top: top, left: left, bottom: bottom, right: right)
return self
}
/**
A child view is vertically and horizontally stretched with optional top, left, bottom and right padding.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter left: A CGFloat value for padding the left side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func edges(top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return edges(v, top: top, left: left, bottom: bottom, right: right)
}
/**
A child view is aligned from the top with optional top padding.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Returns: The current Layout instance.
*/
@discardableResult
public func top(_ child: UIView, top: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.top(parent: v, child: child, top: top)
return self
}
/**
A child view is aligned from the top with optional top padding.
- Parameter top: A CGFloat value for padding the top side.
- Returns: The current Layout instance.
*/
@discardableResult
public func top(_ top: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.top(v, top: top)
}
/**
A child view is aligned from the left with optional left padding.
- Parameter child: A child UIView to layout.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
@discardableResult
public func left(_ child: UIView, left: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.left(parent: v, child: child, left: left)
return self
}
/**
A child view is aligned from the left with optional left padding.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
@discardableResult
public func left(_ left: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.left(v, left: left)
}
/**
A child view is aligned from the bottom with optional bottom padding.
- Parameter child: A child UIView to layout.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Returns: The current Layout instance.
*/
@discardableResult
public func bottom(_ child: UIView, bottom: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.bottom(parent: v, child: child, bottom: bottom)
return self
}
/**
A child view is aligned from the bottom with optional bottom padding.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Returns: The current Layout instance.
*/
@discardableResult
public func bottom(_ bottom: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.bottom(v, bottom: bottom)
}
/**
A child view is aligned from the right with optional right padding.
- Parameter child: A child UIView to layout.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func right(_ child: UIView, right: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.right(parent: v, child: child, right: right)
return self
}
/**
A child view is aligned from the right with optional right padding.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func right(_ right: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.right(v, right: right)
}
/**
A child view is aligned from the top left with optional top and left padding.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
@discardableResult
public func topLeft(_ child: UIView, top: CGFloat = 0, left: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.topLeft(parent: v, child: child, top: top, left: left)
return self
}
/**
A child view is aligned from the top left with optional top and left padding.
- Parameter top: A CGFloat value for padding the top side.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
@discardableResult
public func topLeft(top: CGFloat = 0, left: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return topLeft(v, top: top, left: left)
}
/**
A child view is aligned from the top right with optional top and right padding.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func topRight(_ child: UIView, top: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.topRight(parent: v, child: child, top: top, right: right)
return self
}
/**
A child view is aligned from the top right with optional top and right padding.
- Parameter top: A CGFloat value for padding the top side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func topRight(top: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return topRight(v, top: top, right: right)
}
/**
A child view is aligned from the bottom left with optional bottom and left padding.
- Parameter child: A child UIView to layout.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
@discardableResult
public func bottomLeft(_ child: UIView, bottom: CGFloat = 0, left: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.bottomLeft(parent: v, child: child, bottom: bottom, left: left)
return self
}
/**
A child view is aligned from the bottom left with optional bottom and left padding.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
@discardableResult
public func bottomLeft(bottom: CGFloat = 0, left: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return bottomLeft(v, bottom: bottom, left: left)
}
/**
A child view is aligned from the bottom right with optional bottom and right padding.
- Parameter child: A child UIView to layout.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func bottomRight(_ child: UIView, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.bottomRight(parent: v, child: child, bottom: bottom, right: right)
return self
}
/**
A child view is aligned from the bottom right with optional bottom and right padding.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func bottomRight(bottom: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return bottomRight(v, bottom: bottom, right: right)
}
/**
A child view is aligned at the center with an optional offsetX and offsetY value.
- Parameter child: A child UIView to layout.
- Parameter offsetX: A CGFloat value for the offset along the x axis.
- Parameter offsetX: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
@discardableResult
public func center(_ child: UIView, offsetX: CGFloat = 0, offsetY: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.center(parent: v, child: child, offsetX: offsetX, offsetY: offsetY)
return self
}
/**
A child view is aligned at the center with an optional offsetX and offsetY value.
- Parameter offsetX: A CGFloat value for the offset along the x axis.
- Parameter offsetX: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
@discardableResult
public func center(offsetX: CGFloat = 0, offsetY: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return center(v, offsetX: offsetX, offsetY: offsetY)
}
/**
A child view is aligned at the center horizontally with an optional offset value.
- Parameter child: A child UIView to layout.
- Parameter offset: A CGFloat value for the offset along the x axis.
- Returns: The current Layout instance.
*/
@discardableResult
public func centerHorizontally(_ child: UIView, offset: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.centerHorizontally(parent: v, child: child, offset: offset)
return self
}
/**
A child view is aligned at the center horizontally with an optional offset value.
- Parameter offset: A CGFloat value for the offset along the x axis.
- Returns: The current Layout instance.
*/
@discardableResult
public func centerHorizontally(offset: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return centerHorizontally(v, offset: offset)
}
/**
A child view is aligned at the center vertically with an optional offset value.
- Parameter child: A child UIView to layout.
- Parameter offset: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
@discardableResult
public func centerVertically(_ child: UIView, offset: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.centerVertically(parent: v, child: child, offset: offset)
return self
}
/**
A child view is aligned at the center vertically with an optional offset value.
- Parameter offset: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
@discardableResult
public func centerVertically(offset: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return centerVertically(v, offset: offset)
}
}
/// Layout
extension Layout {
/**
Sets the width of a view.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter width: A CGFloat value.
*/
public class func width(parent: UIView, child: UIView, width: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: width))
child.updateConstraints()
child.setNeedsLayout()
child.layoutIfNeeded()
}
/**
Sets the height of a view.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter height: A CGFloat value.
*/
public class func height(parent: UIView, child: UIView, height: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: height))
child.updateConstraints()
child.setNeedsLayout()
child.layoutIfNeeded()
}
/**
Sets the width and height of a view.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter size: A CGSize value.
*/
public class func size(parent: UIView, child: UIView, size: CGSize = CGSize.zero) {
Layout.width(parent: parent, child: child, width: size.width)
Layout.height(parent: parent, child: child, height: size.height)
}
/**
A collection of children views are horizontally stretched with optional left,
right padding and interim interimSpace.
- Parameter parent: A parent UIView context.
- Parameter children: An Array UIView to layout.
- Parameter left: A CGFloat value for padding the left side.
- Parameter right: A CGFloat value for padding the right side.
- Parameter interimSpace: A CGFloat value for interim interimSpace.
*/
public class func horizontally(parent: UIView, children: [UIView], left: CGFloat = 0, right: CGFloat = 0, interimSpace: InterimSpace = 0) {
prepareForConstraint(parent, children: children)
if 0 < children.count {
parent.addConstraint(NSLayoutConstraint(item: children[0], attribute: .left, relatedBy: .equal, toItem: parent, attribute: .left, multiplier: 1, constant: left))
for i in 1..<children.count {
parent.addConstraint(NSLayoutConstraint(item: children[i], attribute: .left, relatedBy: .equal, toItem: children[i - 1], attribute: .right, multiplier: 1, constant: interimSpace))
parent.addConstraint(NSLayoutConstraint(item: children[i], attribute: .width, relatedBy: .equal, toItem: children[0], attribute: .width, multiplier: 1, constant: 0))
}
parent.addConstraint(NSLayoutConstraint(item: children[children.count - 1], attribute: .right, relatedBy: .equal, toItem: parent, attribute: .right, multiplier: 1, constant: -right))
}
for child in children {
child.updateConstraints()
child.setNeedsLayout()
child.layoutIfNeeded()
}
}
/**
A collection of children views are vertically stretched with optional top,
bottom padding and interim interimSpace.
- Parameter parent: A parent UIView context.
- Parameter children: An Array UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter interimSpace: A CGFloat value for interim interimSpace.
*/
public class func vertically(parent: UIView, children: [UIView], top: CGFloat = 0, bottom: CGFloat = 0, interimSpace: InterimSpace = 0) {
prepareForConstraint(parent, children: children)
if 0 < children.count {
parent.addConstraint(NSLayoutConstraint(item: children[0], attribute: .top, relatedBy: .equal, toItem: parent, attribute: .top, multiplier: 1, constant: top))
for i in 1..<children.count {
parent.addConstraint(NSLayoutConstraint(item: children[i], attribute: .top, relatedBy: .equal, toItem: children[i - 1], attribute: .bottom, multiplier: 1, constant: interimSpace))
parent.addConstraint(NSLayoutConstraint(item: children[i], attribute: .height, relatedBy: .equal, toItem: children[0], attribute: .height, multiplier: 1, constant: 0))
}
parent.addConstraint(NSLayoutConstraint(item: children[children.count - 1], attribute: .bottom, relatedBy: .equal, toItem: parent, attribute: .bottom, multiplier: 1, constant: -bottom))
}
for child in children {
child.updateConstraints()
child.setNeedsLayout()
child.layoutIfNeeded()
}
}
/**
A child view is horizontally stretched with optional left and right padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter left: A CGFloat value for padding the left side.
- Parameter right: A CGFloat value for padding the right side.
*/
public class func horizontally(parent: UIView, child: UIView, left: CGFloat = 0, right: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .left, relatedBy: .equal, toItem: parent, attribute: .left, multiplier: 1, constant: left))
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .right, relatedBy: .equal, toItem: parent, attribute: .right, multiplier: 1, constant: -right))
child.updateConstraints()
child.setNeedsLayout()
child.layoutIfNeeded()
}
/**
A child view is vertically stretched with optional left and right padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter bottom: A CGFloat value for padding the bottom side.
*/
public class func vertically(parent: UIView, child: UIView, top: CGFloat = 0, bottom: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .top, relatedBy: .equal, toItem: parent, attribute: .top, multiplier: 1, constant: top))
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .bottom, relatedBy: .equal, toItem: parent, attribute: .bottom, multiplier: 1, constant: -bottom))
child.updateConstraints()
child.setNeedsLayout()
child.layoutIfNeeded()
}
/**
A child view is vertically and horizontally stretched with optional top, left, bottom and right padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter left: A CGFloat value for padding the left side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter right: A CGFloat value for padding the right side.
*/
public class func edges(parent: UIView, child: UIView, top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) {
horizontally(parent: parent, child: child, left: left, right: right)
vertically(parent: parent, child: child, top: top, bottom: bottom)
}
/**
A child view is aligned from the top with optional top padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Returns: The current Layout instance.
*/
public class func top(parent: UIView, child: UIView, top: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .top, relatedBy: .equal, toItem: parent, attribute: .top, multiplier: 1, constant: top))
child.updateConstraints()
child.setNeedsLayout()
child.layoutIfNeeded()
}
/**
A child view is aligned from the left with optional left padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
public class func left(parent: UIView, child: UIView, left: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .left, relatedBy: .equal, toItem: parent, attribute: .left, multiplier: 1, constant: left))
child.updateConstraints()
child.setNeedsLayout()
child.layoutIfNeeded()
}
/**
A child view is aligned from the bottom with optional bottom padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Returns: The current Layout instance.
*/
public class func bottom(parent: UIView, child: UIView, bottom: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .bottom, relatedBy: .equal, toItem: parent, attribute: .bottom, multiplier: 1, constant: -bottom))
child.updateConstraints()
child.setNeedsLayout()
child.layoutIfNeeded()
}
/**
A child view is aligned from the right with optional right padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
public class func right(parent: UIView, child: UIView, right: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .right, relatedBy: .equal, toItem: parent, attribute: .right, multiplier: 1, constant: -right))
child.updateConstraints()
child.setNeedsLayout()
child.layoutIfNeeded()
}
/**
A child view is aligned from the top left with optional top and left padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
public class func topLeft(parent: UIView, child: UIView, top t: CGFloat = 0, left l: CGFloat = 0) {
top(parent: parent, child: child, top: t)
left(parent: parent, child: child, left: l)
}
/**
A child view is aligned from the top right with optional top and right padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
public class func topRight(parent: UIView, child: UIView, top t: CGFloat = 0, right r: CGFloat = 0) {
top(parent: parent, child: child, top: t)
right(parent: parent, child: child, right: r)
}
/**
A child view is aligned from the bottom left with optional bottom and left padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
public class func bottomLeft(parent: UIView, child: UIView, bottom b: CGFloat = 0, left l: CGFloat = 0) {
bottom(parent: parent, child: child, bottom: b)
left(parent: parent, child: child, left: l)
}
/**
A child view is aligned from the bottom right with optional bottom and right padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
public class func bottomRight(parent: UIView, child: UIView, bottom b: CGFloat = 0, right r: CGFloat = 0) {
bottom(parent: parent, child: child, bottom: b)
right(parent: parent, child: child, right: r)
}
/**
A child view is aligned at the center with an optional offsetX and offsetY value.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter offsetX: A CGFloat value for the offset along the x axis.
- Parameter offsetX: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
public class func center(parent: UIView, child: UIView, offsetX: CGFloat = 0, offsetY: CGFloat = 0) {
centerHorizontally(parent: parent, child: child, offset: offsetX)
centerVertically(parent: parent, child: child, offset: offsetY)
}
/**
A child view is aligned at the center horizontally with an optional offset value.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter offset: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
public class func centerHorizontally(parent: UIView, child: UIView, offset: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .centerX, relatedBy: .equal, toItem: parent, attribute: .centerX, multiplier: 1, constant: offset))
child.updateConstraints()
child.setNeedsLayout()
child.layoutIfNeeded()
}
/**
A child view is aligned at the center vertically with an optional offset value.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter offset: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
public class func centerVertically(parent: UIView, child: UIView, offset: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .centerY, relatedBy: .equal, toItem: parent, attribute: .centerY, multiplier: 1, constant: offset))
child.updateConstraints()
child.setNeedsLayout()
child.layoutIfNeeded()
}
/**
Creats an Array with a NSLayoutConstraint value.
- Parameter format: The VFL format string.
- Parameter options: Additional NSLayoutFormatOptions.
- Parameter metrics: An optional Dictionary<String, Any> of metric key / value pairs.
- Parameter views: A Dictionary<String, Any> of view key / value pairs.
- Returns: The Array<NSLayoutConstraint> instance.
*/
public class func constraint(format: String, options: NSLayoutFormatOptions, metrics: [String: Any]?, views: [String: Any]) -> [NSLayoutConstraint] {
for (_, a) in views {
if let v = a as? UIView {
v.translatesAutoresizingMaskIntoConstraints = false
}
}
return NSLayoutConstraint.constraints(
withVisualFormat: format,
options: options,
metrics: metrics,
views: views
)
}
/**
Prepares the relationship between the parent view context and child view
to layout. If the child is not already added to the view hierarchy as the
parent's child, then it is added.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
*/
private class func prepareForConstraint(_ parent: UIView, child: UIView) {
if parent != child.superview {
child.removeFromSuperview()
parent.addSubview(child)
}
child.translatesAutoresizingMaskIntoConstraints = false
}
/**
Prepares the relationship between the parent view context and an Array of
child UIViews.
- Parameter parent: A parent UIView context.
- Parameter children: An Array of UIViews.
*/
private class func prepareForConstraint(_ parent: UIView, children: [UIView]) {
for v in children {
prepareForConstraint(parent, child: v)
}
}
}
/// A memory reference to the LayoutKey instance for UIView extensions.
fileprivate var LayoutKey: UInt8 = 0
/// Layout extension for UIView.
extension UIView {
/// Layout reference.
public private(set) var layout: Layout {
get {
return AssociatedObject.get(base: self, key: &LayoutKey) {
return Layout(parent: self)
}
}
set(value) {
AssociatedObject.set(base: self, key: &LayoutKey, value: value)
}
}
/**
Used to chain layout constraints on a child context.
- Parameter child: A child UIView to layout.
- Returns: The current Layout instance.
*/
public func layout(_ child: UIView) -> Layout {
return Layout(parent: self, child: child)
}
}
| apache-2.0 | 86cf9ce4791919033e81cebc52045c42 | 40.071709 | 197 | 0.651144 | 4.837556 | false | false | false | false |
tectijuana/patrones | Bloque1SwiftArchivado/PracticasSwift/GonzalezEsparzaLuisManuel/2.swift | 1 | 651 | // Write some awesome Swift code, or import libraries like "Foundation",
// "Dispatch", or "Glibc"
// link de donde los hice en linea http://swift.sandbox.bluemix.net/#/repl/58b7d995cb7993767588ce10
import Glibc
print("2) ");
print("8.23 Una mujer arroja su libro de bolsillo desde lo alto de la torre de Sears (con 1451 pies de altura). Escribir un programa para determinar la velocidad de impacto al nivel del piso. Usart la formula V= sqrt2gh, donde la h es la altura de la torre y g = 32 pies/seg^2 es la constante gravitacional de la tierra");
var g: Double
var h: Double
var v: Double
g=32;
h=1451;
v=sqrt(2*g*h)
print(v,"pies/seg cuadrado"); | gpl-3.0 | 51a98b2c933faa18135d0efcc1a6f181 | 45.571429 | 322 | 0.740399 | 2.830435 | false | false | false | false |
andrebocchini/SwiftChattyOSX | SwiftChattyOSX/Threads/ThreadPostTableCell.swift | 1 | 4020 | //
// ThreadPostTableCell.swift
// SwiftChattyOSX
//
// Created by Andre Bocchini on 2/8/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.
//
import Cocoa
import SwiftChatty
class ThreadPostTableCell: NSView, Reusable, DeSpoiling {
// MARK: Outlets
@IBOutlet private weak var postTextLabel: NSTextField!
@IBOutlet private weak var leadingLabelConstraint: NSLayoutConstraint!
@IBOutlet private weak var authorLabel: NSTextField!
@IBOutlet private weak var lolLabel: NSTextField!
@IBOutlet private weak var infLabel: NSTextField!
@IBOutlet private weak var unfLabel: NSTextField!
@IBOutlet private weak var tagLabel: NSTextField!
@IBOutlet private weak var wtfLabel: NSTextField!
// MARK: Constants
private let indentationWidth: CGFloat = 15.0
// MARK: Variables
private var post: Post?
func configure(post: Post, depth: Int, participant: Bool, originalPoster: Bool, unread: Bool) {
setIndentationLevel(depth)
self.postTextLabel.stringValue = post.htmlAndSpoilerFreeBody
if unread {
self.postTextLabel.textColor = NSColor.unreadTextColor
self.postTextLabel.font = NSFont.unreadThreadFont
} else {
self.postTextLabel.textColor = NSColor.readTextColor
self.postTextLabel.font = NSFont.normalThreadFont
}
authorLabel.stringValue = post.author
if post.author == "Shacknews" {
self.authorLabel.textColor = NSColor.shacknewsPosterColor
} else if originalPoster {
self.authorLabel.textColor = NSColor.originalPosterColor
} else {
self.authorLabel.textColor = NSColor.regularPosterColor
}
if participant {
self.wantsLayer = true
self.layer?.backgroundColor = NSColor.participantBackgroundColor.CGColor
} else {
self.wantsLayer = false
}
resetLols()
configureWithLols(post.lols)
}
private func setIndentationLevel(level: Int) {
var indentationLevel: CGFloat = 0.0
if level >= 0 {
indentationLevel = CGFloat(level)
}
self.leadingLabelConstraint.constant = indentationLevel * indentationWidth + 8
}
// MARK: LOLs
private func resetLols() {
self.lolLabel.hidden = true
self.lolLabel.stringValue = "[lol]"
self.infLabel.hidden = true
self.infLabel.stringValue = "[inf]"
self.unfLabel.hidden = true
self.unfLabel.stringValue = "[unf]"
self.tagLabel.hidden = true
self.tagLabel.stringValue = "[tag]"
self.wtfLabel.hidden = true
self.wtfLabel.stringValue = "[wtf]"
}
private func configureWithLols(lols: [LOL]) {
for lol in lols {
configureLabelWithLolTag(lol)
}
}
private func configureLabelWithLolTag(lol: LOL) {
if lol.count > 0 {
let lolString = "[\(lol.tag.rawValue) x \(lol.count)]"
switch(lol.tag) {
case .Lol:
self.lolLabel.hidden = false
self.lolLabel.textColor = NSColor.lolColor
self.lolLabel.stringValue = lolString
case .Inf:
self.infLabel.hidden = false
self.infLabel.textColor = NSColor.infColor
self.infLabel.stringValue = lolString
case .Unf:
self.unfLabel.hidden = false
self.unfLabel.textColor = NSColor.unfColor
self.unfLabel.stringValue = lolString
case .Tag:
self.tagLabel.hidden = false
self.tagLabel.textColor = NSColor.tagColor
self.tagLabel.stringValue = lolString
case .Wtf:
self.wtfLabel.hidden = false
self.wtfLabel.textColor = NSColor.wtfColor
self.wtfLabel.stringValue = lolString
default:
break
}
}
}
}
| mit | f27b620f9c43bb7c461aedf6b6068827 | 31.41129 | 99 | 0.613585 | 4.531003 | false | false | false | false |
vimeo/VimeoNetworking | Tests/Shared/GCSTests.swift | 1 | 3171 | //
// GCSTests.swift
// Vimeo
//
// Created by Nguyen, Van on 11/8/18.
// Copyright © 2018 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
import OHHTTPStubs
@testable import VimeoNetworking
class GCSTests: XCTestCase {
override func setUp() {
super.setUp()
}
func test_gcsResponse_getsParsedIntoGCSObject() {
let request = Request<GCS>(path: "/videos/" + Constants.CensoredId)
stub(condition: isPath("/videos/" + Constants.CensoredId)) { _ in
let stubPath = OHPathForFile("gcs.json", type(of: self))
return fixture(filePath: stubPath!, headers: ["Content-Type":"application/json"])
}
let expectation = self.expectation(description: "Network call expectation")
let client = makeVimeoClient()
_ = client.request(request) { response in
switch response {
case .success(let result):
let gcs = result.model
XCTAssertEqual(gcs.uploadLink, "https://www.google.com", "The upload link should have been `https://www.google.com`.")
XCTAssertEqual(gcs.startByte?.int64Value, 0, "The start byte should have been `0`.")
XCTAssertEqual(gcs.endByte?.int64Value, 377296827, "The end byte should have been `377296827`.")
let uploadAttemptConnection = gcs.connections[.uploadAttempt]
XCTAssertEqual(uploadAttemptConnection?.uri, "/fake/upload/attempt", "The connection's uri should have been `/fake/upload/attempt`.")
XCTAssertEqual(uploadAttemptConnection?.options as? [String], ["GET"], "The connection's options should have been `[GET]`.")
case .failure(let error):
XCTFail("\(error)")
}
expectation.fulfill()
}
self.waitForExpectations(timeout: 1.0) { error in
if let unWrappedError = error {
XCTFail("\(unWrappedError)")
}
}
}
}
| mit | 0f404375feef20dd1e9b1f6248177ad0 | 41.837838 | 149 | 0.640694 | 4.594203 | false | true | false | false |
FranDepascuali/ProyectoAlimentar | ProyectoAlimentar/Repositories/NetworkManager.swift | 1 | 2300 | //
// NetworkExecutorRepository.swift
// ProyectoAlimentar
//
// Created by Francisco Depascuali on 11/12/16.
// Copyright © 2016 Alimentar. All rights reserved.
//
import Foundation
import ReactiveSwift
//import Alamofire
import enum Result.NoError
public typealias JSON = AnyObject
public protocol NetworkManagerType {
// init(baseURL: String)
func request() -> SignalProducer<JSON, NoError>
}
open class NetworkManager: NetworkManagerType {
public init(baseURL: String) {
}
public func request() -> SignalProducer<JSON, NoError> {
return .empty
}
}
//
//open class NetworkManager: NetworkManagerType {
//
// fileprivate let _baseURL: String
//
// public required init(baseURL: String = CredentialsManager.sharedInstance[.ApiURL]!) {
// print("Network manager initialized using URL: " + baseURL)
// _baseURL = baseURL
// }
//
// open func request(_ method: Alamofire.Method,
// URL URLString: String,
// parameters: [String : AnyObject]? = nil,
// encoding: Alamofire.ParameterEncoding = .json,
// headers: [String : String]? = nil) -> SignalProducer<JSON, NoError> {
//// return SignalProducer { [unowned self] observer, _ in
//// print(self._baseURL + URLString)
//// Alamofire.request(method, self._baseURL + URLString, parameters: parameters, encoding: encoding, headers: headers)
//// .responseJSON { response in
//// print(response.request) // original URL request
//// print(response.response) // URL response
//// print(response.data) // server data
//// print(response.result) // result of response serialization
////
////
//// if let JSON = response.result.value {
//// print("JSON: \(JSON)")
//// observer.sendNext(JSON)
//// observer.sendCompleted()
//// } else {
//// print("Error: \(response.result.debugDescription)")
//// }
//// }
//// }
// }
//}
| apache-2.0 | 4472ecb695853bf0164e87eb9e34d676 | 32.318841 | 130 | 0.53893 | 4.75 | false | false | false | false |
GTMYang/GTMRouter | GTMRouterExample/ViewController.swift | 1 | 3351 | //
// ViewController.swift
// GTMRouterExample
//
// Created by luoyang on 2016/12/19.
// Copyright © 2016年 luoyang. All rights reserved.
//
import UIKit
import GTMRouter
class ViewController: UIViewController {
let label: UILabel = {
let lab = UILabel()
lab.text = "A"
lab.textAlignment = .center
lab.textColor = UIColor.red
lab.font = UIFont.systemFont(ofSize: 38)
return lab
}()
let nextBButton: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("ViewControllerB", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.addTarget(self, action: #selector(onNextBTouch), for: .touchUpInside)
return btn
}()
let nextCButton: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("ViewControllerC", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.addTarget(self, action: #selector(onNextCTouch), for: .touchUpInside)
return btn
}()
let nextDButton: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("ViewControllerD", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.addTarget(self, action: #selector(onNextDTouch), for: .touchUpInside)
return btn
}()
let nextWebButton: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("WebViewController", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.addTarget(self, action: #selector(onNextWebTouch), for: .touchUpInside)
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = "GTMRouter Demo"
self.view.addSubview(self.label)
self.label.frame = self.view.bounds
let h = self.view.bounds.size.height, w = self.view.bounds.size.width
self.view.addSubview(self.nextBButton)
self.view.addSubview(self.nextCButton)
self.view.addSubview(self.nextDButton)
self.view.addSubview(self.nextWebButton)
self.nextDButton.frame = CGRect(x: 0, y: h-100, width: w, height: 50)
self.nextCButton.frame = CGRect(x: 0, y: h-150, width: w, height: 50)
self.nextBButton.frame = CGRect(x: 0, y: h-200, width: w, height: 50)
self.nextWebButton.frame = CGRect(x: 0, y: h-250, width: w, height: 50)
// 支持网页
GTMRouter.setWebVCFactory(factory: WebViewControllerFactory())
}
// MARK: - Events
@objc func onNextBTouch() {
GTMRouter.push(url: "router://GTMRouterExample/ViewControllerB")
}
@objc func onNextCTouch() {
let params:[String:Any] = ["image": UIImage(named: "logo.png") as Any]
GTMRouter.push(url: "router://GTMRouterExample/ViewControllerC?ip=1&fp=1.2345&dp=12222.2345&bp=true&name=GTMYang,你好", parameter: params)
}
@objc func onNextDTouch() {
GTMRouter.push(url: "router://GTMRouterExample/ViewControllerD")
}
@objc func onNextWebTouch() {
GTMRouter.push(url: "https://www.baidu.com", parameter: ["title": "测试网页传参数"])
}
}
| mit | 68923facd84dc3637ab3d8768e70bc2c | 31.568627 | 144 | 0.612583 | 3.844907 | false | false | false | false |
mobgeek/swift | Crie Seu Primeiro App/Playgrounds/Aula 02.playground/Contents.swift | 2 | 5214 | // Playground - noun: a place where people can play
import UIKit
/*
__ __
__ \ / __
/ \ | / \
\|/ Mobgeek
_,.---v---._
/\__/\ / \ Curso Swift em 4 semanas
\_ _/ / \
\ \_| @ __|
\ \_
\ ,__/ /
~~~`~~~~~~~~~~~~~~/~~~~
*/
/*:
# Aula 02
## **Operadores Básicos**
Operadores são apenas símbolos especiais que você irá usar para checar, modificar ou combinar valores. Vamos ver alguns deles.
### **Atribuição**
Armazenar valores em variáveis ou constantes
*/
let taxaMinima = 150
/*:
### **Aritiméticos**
Realizar operações conhecidas da matemática (soma, subtração, divisão, multiplicação, resto)
*/
1 + 1
7 - 6
5 * 7
15.0 / 7.5
7 % 3
/*:
### **Pré/pós incremento/decremento**
Uma forma rápida de aumentar/dimunir em 1 valores armazenados em variáveis
Optamos pelo **pré incremento/decremento** quando queremos primeiro modificar o valor contido na variável para depois fazer algo com ele.
*/
var pontosTotalAntes = 300
let pontosBonusAntes = ++pontosTotalAntes //Primeiro incrementa para depois atribuir
pontosTotalAntes
pontosBonusAntes
//:Quando escolhemos usar **pós incremento/decremento**, o valor armazenado na variável só será alterado após ser feito algo com o valor antigo.
var pontosTotalDepois = 300
let pontosBonusDepois = pontosTotalDepois++ //Primeiro atribui para depois incrementar
pontosTotalDepois
pontosBonusDepois
/*:
### **Compostos**
Uma forma simplifica de atualizar o valor de uma variável com seu próprio valor
*/
var passos = 1500
passos += 350
passos -= 350
passos *= 3
passos /= 3
/*:
### **Operadores de Comparação**
Comparar 2 valores e retorna verdadeiro (true) ou falso (false)
*/
1 > 3
10 < 11
3.5 >= 3.5
2.86 <= 2
4 == 4
3 != 5
/*:
### **Operador de concatenação**
Uma segunda utilidade do operador +. Quando utlizado entre 2 Strings, ele concatena, ou seja, junta as 2 em uma String apenas.
*/
let saudação = "Oi, "
var nome = "Renan"
saudação + nome
nome = "Mariana"
saudação + nome
/*:
### **Range**
Representar intervalos de valores (... , ..<)
*/
var intervalo = 1...10
var novoIntervalor = 1..<5
/*:
## Fluxo de Controle
Swift nos disponibiliza diversas formas de definir o fluxo de execução do nosso código. Para isso, usaremos basicamente 2 grupos de estruturas diferentes.
## **Estruturas Condicionais:**
Usadas para decidir qual conjunto de instruções será executado com base em certas condições que podemos estabelecer.
### **If-Else**
"SE" isso, então faça aquilo, "SENAO" faça aquilo outro
*/
var temperatura = 35
if temperatura >= 35 {
"Tá quente! Partiu praia! ;-)"
} else if temperatura <= 25 {
"Cariocas, preparem os seus casacos!"
} else {
"Pessoal, ainda não esquentou de verdade."
}
/*:
Podemos ainda, estabelecer mais de uma condição para a mesma expressão `if` usando os operadores lógicos (&&, ||, !).
### **"E" Lógico (&&)**
A expressão retornará verdadeiro se **todas** as partes forem verdadeiras.
*/
var estarDisposto = true
if temperatura >= 35 && estarDisposto {
"Tá quente! Partiu praia! ;-)"
}
/*:
### **"OU" Lógico (||)**
A expressão retornará verdadeiro se **pelo menos** uma das partes for vardadeira.
:*/
estarDisposto = false
if temperatura >= 35 || estarDisposto {
"Tá quente! Partiu praia! ;-)"
}
/*:
### **"Negação" (!)**
Simplesmente troca de true para false e vice versa
:*/
if !estarDisposto {
"Tá quente! Partiu praia! ;-)"
}
/*:
### **Switch**
"ESCOLHA" esse valor, "CASO" seja isso, então faça aquilo, ...
*/
var count = 346
var contadorNatural: String
switch count {
case 0...9:
contadorNatural = "algumas vezes"
case 10...99:
contadorNatural = "dezenas de vezes"
default:
contadorNatural = "um monte de vezes"
}
let mensagem = "Você me ligou \(contadorNatural)"
/*:
## **Estruturas de Repetição (Loops):**
Ideais para quando precisamos repetir um conjunto de instruções múltiplas vezes.
### **For-in**
"PARA" valor "EM" sequência
*/
for elemento in 1...9 {
//elemento é uma constante temporária, isto é, ela só existe durante a execução deste loop!
println("\(elemento) vezes 6 é \(elemento * 6)")
}
for character in "Cafe" {
println("Letra é \(character)")
}
//: Repare que as constantes elemento e character definidas nos loops, não são do tipo String mas sim do tipo Character. Para verificar, use "option + click" em cima das constantes para ver seu tipo.
/*:
### **For-Condição-Incremento**
"PARA" um valor inicial "ENQUANTO" condição verdadeira "INCREMENTA" valor
*/
for var tentativa = 0; tentativa < 3; ++tentativa {
println("Tentativa número: \(tentativa)")
}
/*:
### **While**
"ENQUANTO" isso, faça aquilo
*/
var dinheiro = 5
while dinheiro > 3 {
println("Pode pedir a última! Saldo:\(dinheiro)")
--dinheiro
}
/*:
### **Do-While**
"FAÇA" isso, "ENQUANTO" aquilo
*/
dinheiro = 10
do {
println("Grana: \(dinheiro)")
--dinheiro
} while dinheiro < 3
| mit | 062383e60398a3a325e238f23dfbcbf9 | 21.751111 | 199 | 0.642313 | 2.780554 | false | false | false | false |
brentdax/swift | test/SILOptimizer/access_enforcement_selection.swift | 1 | 4324 | // RUN: %target-swift-frontend -enforce-exclusivity=checked -Onone -emit-sil -parse-as-library %s -Xllvm -debug-only=access-enforcement-selection -swift-version 3 2>&1 | %FileCheck %s
// REQUIRES: asserts
// This is a source-level test because it helps bring up the entire -Onone pipeline with the access markers.
public func takesInout(_ i: inout Int) {
i = 42
}
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection10takesInoutyySizF
// CHECK: Static Access: %{{.*}} = begin_access [modify] [static] %{{.*}} : $*Int
// Helper taking a basic, no-escape closure.
func takeClosure(_: ()->Int) {}
// Helper taking an escaping closure.
func takeClosureAndInout(_: inout Int, _: @escaping ()->Int) {}
// Helper taking an escaping closure.
func takeEscapingClosure(_: @escaping ()->Int) {}
// Generate an alloc_stack that escapes into a closure.
public func captureStack() -> Int {
// Use a `var` so `x` isn't treated as a literal.
var x = 3
takeClosure { return x }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection12captureStackSiyF
// Dynamic access for `return x`. Since the closure is non-escaping, using
// dynamic enforcement here is more conservative than it needs to be -- static
// is sufficient here.
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection12captureStackSiyFSiyXEfU_
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
// Generate an alloc_stack that does not escape into a closure.
public func nocaptureStack() -> Int {
var x = 3
takeClosure { return 5 }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection14nocaptureStackSiyF
// Static access for `return x`.
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
//
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection14nocaptureStackSiyFSiyXEfU_
// Generate an alloc_stack that escapes into a closure while an access is
// in progress.
public func captureStackWithInoutInProgress() -> Int {
// Use a `var` so `x` isn't treated as a literal.
var x = 3
takeClosureAndInout(&x) { return x }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection31captureStackWithInoutInProgressSiyF
// Access for `return x`.
// CHECK-DAG: Dynamic Access: %{{.*}} = begin_access [read] [dynamic] %{{.*}} : $*Int
// Access for `&x`.
// CHECK-DAG: Dynamic Access: %{{.*}} = begin_access [modify] [dynamic] %{{.*}} : $*Int
//
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection31captureStackWithInoutInProgressSiyF
// CHECK: Dynamic Access: %{{.*}} = begin_access [read] [dynamic] %{{.*}} : $*Int
// Generate an alloc_box that escapes into a closure.
// FIXME: `x` is eventually promoted to an alloc_stack even though it has dynamic enforcement.
// We should ensure that alloc_stack variables are statically enforced.
public func captureBox() -> Int {
var x = 3
takeEscapingClosure { x = 4; return x }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection10captureBoxSiyF
// Dynamic access for `return x`.
// CHECK: Dynamic Access: %{{.*}} = begin_access [read] [dynamic] %{{.*}} : $*Int
// CHECK-LABEL: $s28access_enforcement_selection10captureBoxSiyFSiycfU_
// Generate a closure in which the @inout_aliasing argument
// escapes to an @inout function `bar`.
public func recaptureStack() -> Int {
var x = 3
takeClosure { takesInout(&x); return x }
return x
}
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection14recaptureStackSiyF
//
// Static access for `return x`.
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
// CHECK-LABEL: Access Enforcement Selection in $s28access_enforcement_selection14recaptureStackSiyFSiyXEfU_
//
// The first [modify] access inside the closure is static. It enforces the
// @inout argument.
// CHECK: Static Access: %{{.*}} = begin_access [modify] [static] %{{.*}} : $*Int
//
// The second [read] access is static. Same as `captureStack` above.
//
// CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int
| apache-2.0 | 4c6ff9905420429b9a21512951100c43 | 42.24 | 183 | 0.703747 | 3.773124 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Parse Dashboard for iOS/SectionControllers/SearchSectionController.swift | 1 | 3011 | /**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
protocol SearchSectionControllerDelegate: class {
func searchSectionController(_ sectionController: SearchSectionController, didChangeText text: String)
}
final class SearchSectionController: ListSectionController, UISearchBarDelegate, ListScrollDelegate {
weak var delegate: SearchSectionControllerDelegate?
weak var stretchyView: UIView?
override init() {
super.init()
scrollDelegate = self
}
override func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 60)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCell(of: SearchCell.self, for: self, at: index) as? SearchCell else {
fatalError()
}
cell.searchBar.delegate = self
stretchyView = cell.stretchyView
return cell
}
// MARK: UISearchBarDelegate
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
delegate?.searchSectionController(self, didChangeText: searchText)
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
delegate?.searchSectionController(self, didChangeText: searchBar.text!)
}
// MARK: ListScrollDelegate
func listAdapter(_ listAdapter: ListAdapter, didScroll sectionController: ListSectionController) {
if let searchBar = (collectionContext?.cellForItem(at: 0, sectionController: self) as? SearchCell)?.searchBar {
searchBar.resignFirstResponder()
}
guard let collectionView = listAdapter.collectionView else { return }
let yOffset = collectionView.contentOffset.y + collectionView.contentInset.top
guard yOffset <= 0 else { return }
let scale = 1 + (-yOffset/sizeForItem(at: 0).height)
stretchyView?.transform = CGAffineTransform(scaleX: scale, y: scale).concatenating(CGAffineTransform(translationX: 0, y: yOffset/2))
}
func listAdapter(_ listAdapter: ListAdapter, willBeginDragging sectionController: ListSectionController) {}
func listAdapter(_ listAdapter: ListAdapter,
didEndDragging sectionController: ListSectionController,
willDecelerate decelerate: Bool) {}
}
| mit | db32fa0c23a6cb80573d2221ff0f060a | 38.618421 | 140 | 0.720359 | 5.45471 | false | false | false | false |
iceVeryCold/DouYuZhiBo | DYDemo/DYDemo/Classes/Main/View/PageTitleView.swift | 1 | 6581 | //
// PageTitleView.swift
// DYDemo
//
// Created by 这个夏天有点冷 on 2017/3/8.
// Copyright © 2017年 YLT. All rights reserved.
//
import UIKit
// MARK:定义协议
protocol PageTitleViewDelegate : class { // 后跟class,表示只能被类遵守
func pageTitleView(titleView : PageTitleView, selectedIndex index : Int)
}
// MARK:定义常亮
private let kScrollLineH : CGFloat = 2
private let kNomalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85)
private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0)
// MARK:定义类
class PageTitleView: UIView {
// MARK:定义属性
var currentIndex : Int = 0
var titles : [String]
// 定义代理
weak var delegate : PageTitleViewDelegate?
// MARK: 懒加载属性
lazy var titleLabels : [UILabel] = [UILabel]()
lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView.init()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
// 创建底部滑动线
lazy var scrollLine : UIView = {
let scrollLine = UIView.init()
scrollLine.backgroundColor = UIColor.init(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
return scrollLine
}()
// MARK: 自定义构造函数
init(frame: CGRect, titles:[String]) {
self.titles = titles
super.init(frame: frame)
// 设置界面
setUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: 设置UI界面
extension PageTitleView {
func setUI() {
// 1.添加scrollView
addSubview(scrollView)
scrollView.frame = bounds
// 2.设置title对应的label
setupTitleLabels()
// 3.设置底线和滚动的滑块
setupBottomMenuAndScrollLine()
}
// 设置label
func setupTitleLabels() {
let labelW : CGFloat = frame.width / CGFloat(titles.count)
let labelH : CGFloat = frame.height - kScrollLineH
let labelY : CGFloat = 0
for (index, title) in titles.enumerated() {
// 创建label
let label = UILabel.init()
// 设置label的属性
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = UIColor.init(r: kNomalColor.0, g: kNomalColor.1, b: kNomalColor.2)
label.textAlignment = .center
// 设置frame
let labelX : CGFloat = labelW * CGFloat(index)
label.frame = CGRect.init(x: labelX, y: labelY, width: labelW, height: labelH)
// 将label添加到scrollView中
scrollView.addSubview(label)
titleLabels.append(label)
// 给label添加手势
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer.init(target: self, action: #selector(self.titleLabelClicked(tapGes:)))
label.addGestureRecognizer(tapGes)
}
}
func setupBottomMenuAndScrollLine() {
// 创建底线
let bottomLine = UIView.init()
bottomLine.backgroundColor = UIColor.lightGray
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect.init(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
// 添加scrollLine
guard let firstLabel = titleLabels.first else {
return
}
firstLabel.textColor = UIColor.init(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect.init(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.size.width, height: kScrollLineH)
}
}
// MARK: 监听label的点击
extension PageTitleView {
// 如果是事件监听,需要用到@objc
@objc func titleLabelClicked(tapGes : UITapGestureRecognizer) {
// 1.获取当前label的下标值
guard let currentLabel = tapGes.view as? UILabel else { return }
// 重复点击同一个title直接返回
if currentLabel.tag == currentIndex {
return
}
// 2.获取之前的label
let oldLabel = titleLabels[currentIndex]
// 3.切换文字的颜色
currentLabel.textColor = UIColor.init(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
oldLabel.textColor = UIColor.init(r: kNomalColor.0, g: kNomalColor.1, b: kNomalColor.2)
// 4.保存最新label的下标志
currentIndex = currentLabel.tag
// 5.滚动条位置发生改变
let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width
UIView.animate(withDuration: 0.15) {
self.scrollLine.frame.origin.x = scrollLineX
}
// 6.通知代理做事情
delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex)
}
}
// MARK:对外暴露方法
extension PageTitleView {
func setTitleWithProgress(prog : CGFloat, sourceIndex : Int, targerIndex : Int) {
// 1、取出sourceLabel/targetLabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targerIndex]
// 2.处理滑块逻辑
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * prog
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
// 3.颜色渐变
// 3.1 取出变化范围
let colorDelta = (kSelectColor.0 - kNomalColor.0, kSelectColor.1 - kNomalColor.1, kSelectColor.2 - kNomalColor.2)
// 3.2 变化sourceLabel
sourceLabel.textColor = UIColor.init(r: kSelectColor.0 - colorDelta.0 * prog, g: kSelectColor.1 - colorDelta.1 * prog, b: kSelectColor.2 - colorDelta.2 * prog)
// 3.3 变化targetLabel
targetLabel.textColor = UIColor.init(r: kNomalColor.0 + colorDelta.0 * prog, g: kNomalColor.1 + colorDelta.1 * prog, b: kNomalColor.2 + colorDelta.2 * prog)
// 4.记录最新的index
currentIndex = targerIndex
}
}
| mit | 9bbf2de915fa624fc6349d4e621658e9 | 30.538462 | 167 | 0.595935 | 4.300699 | false | false | false | false |
tjw/swift | stdlib/public/core/StringIndex.swift | 1 | 5874 | //===--- StringIndex.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
//
//===----------------------------------------------------------------------===//
extension String {
/// A position of a character or code unit in a string.
@_fixed_layout // FIXME(sil-serialize-all)
public struct Index {
@usableFromInline // FIXME(sil-serialize-all)
internal var _compoundOffset : UInt64
@usableFromInline
internal var _cache: _Cache
internal typealias _UTF8Buffer = _ValidUTF8Buffer<UInt64>
@_frozen // FIXME(sil-serialize-all)
@usableFromInline
internal enum _Cache {
case utf16
case utf8(buffer: _UTF8Buffer)
case character(stride: UInt16)
case unicodeScalar(value: Unicode.Scalar)
}
}
}
/// Convenience accessors
extension String.Index._Cache {
@inlinable // FIXME(sil-serialize-all)
internal var utf16: Void? {
if case .utf16 = self { return () } else { return nil }
}
@inlinable // FIXME(sil-serialize-all)
internal var utf8: String.Index._UTF8Buffer? {
if case .utf8(let r) = self { return r } else { return nil }
}
@inlinable // FIXME(sil-serialize-all)
internal var character: UInt16? {
if case .character(let r) = self { return r } else { return nil }
}
@inlinable // FIXME(sil-serialize-all)
internal var unicodeScalar: UnicodeScalar? {
if case .unicodeScalar(let r) = self { return r } else { return nil }
}
}
extension String.Index : Equatable {
@inlinable // FIXME(sil-serialize-all)
public static func == (lhs: String.Index, rhs: String.Index) -> Bool {
return lhs._compoundOffset == rhs._compoundOffset
}
}
extension String.Index : Comparable {
@inlinable // FIXME(sil-serialize-all)
public static func < (lhs: String.Index, rhs: String.Index) -> Bool {
return lhs._compoundOffset < rhs._compoundOffset
}
}
extension String.Index : Hashable {
@inlinable // FIXME(sil-serialize-all)
public var hashValue: Int {
return _compoundOffset.hashValue
}
}
extension String.Index {
internal typealias _Self = String.Index
/// Creates a new index at the specified UTF-16 offset.
///
/// - Parameter offset: An offset in UTF-16 code units.
@inlinable // FIXME(sil-serialize-all)
public init(encodedOffset offset: Int) {
_compoundOffset = UInt64(offset << _Self._strideBits)
_cache = .utf16
}
@inlinable // FIXME(sil-serialize-all)
internal init(encodedOffset o: Int, transcodedOffset: Int = 0, _ c: _Cache) {
_compoundOffset = UInt64(o << _Self._strideBits | transcodedOffset)
_cache = c
}
@inlinable // FIXME(sil-serialize-all)
internal static var _strideBits : Int { return 2 }
@inlinable // FIXME(sil-serialize-all)
internal static var _mask : UInt64 { return (1 &<< _Self._strideBits) &- 1 }
@inlinable // FIXME(sil-serialize-all)
internal mutating func _setEncodedOffset(_ x: Int) {
_compoundOffset = UInt64(x << _Self._strideBits)
}
/// The offset into a string's UTF-16 encoding for this index.
@inlinable // FIXME(sil-serialize-all)
public var encodedOffset : Int {
return Int(_compoundOffset >> _Self._strideBits)
}
/// The offset of this index within whatever encoding this is being viewed as
@inlinable // FIXME(sil-serialize-all)
internal var _transcodedOffset : Int {
get {
return Int(_compoundOffset & _Self._mask)
}
set {
let extended = UInt64(newValue)
_sanityCheck(extended <= _Self._mask)
_compoundOffset &= ~_Self._mask
_compoundOffset |= extended
}
}
}
// SPI for Foundation
extension String.Index {
@inlinable // FIXME(sil-serialize-all)
@available(swift, deprecated: 3.2)
@available(swift, obsoleted: 4.0)
public // SPI(Foundation)
init(_position: Int) {
self.init(encodedOffset: _position)
}
@inlinable // FIXME(sil-serialize-all)
@available(swift, deprecated: 3.2)
@available(swift, obsoleted: 4.0)
public // SPI(Foundation)
init(_offset: Int) {
self.init(encodedOffset: _offset)
}
@inlinable // FIXME(sil-serialize-all)
@available(swift, deprecated: 3.2)
@available(swift, obsoleted: 4.0)
public // SPI(Foundation)
init(_base: String.Index, in c: String.CharacterView) {
self = _base
}
/// The integer offset of this index in UTF-16 code units.
@inlinable // FIXME(sil-serialize-all)
@available(swift, deprecated: 3.2)
@available(swift, obsoleted: 4.0)
public // SPI(Foundation)
var _utf16Index: Int {
return self.encodedOffset
}
/// The integer offset of this index in UTF-16 code units.
@inlinable // FIXME(sil-serialize-all)
@available(swift, deprecated: 3.2)
@available(swift, obsoleted: 4.0)
public // SPI(Foundation)
var _offset: Int {
return self.encodedOffset
}
}
// backward compatibility for index interchange.
extension Optional where Wrapped == String.Index {
@inlinable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices")
public static func ..<(
lhs: String.Index?, rhs: String.Index?
) -> Range<String.Index> {
return lhs! ..< rhs!
}
@inlinable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices")
public static func ...(
lhs: String.Index?, rhs: String.Index?
) -> ClosedRange<String.Index> {
return lhs! ... rhs!
}
}
| apache-2.0 | 644b69315d151581bc7fe8b3e419aa50 | 29.915789 | 104 | 0.659687 | 3.821731 | false | false | false | false |
kalvish21/AndroidMessenger | AndroidMessengerMacDesktopClient/Pods/Swifter/Sources/File.swift | 1 | 5561 | //
// File.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Foundation
#endif
public enum FileError: ErrorType {
case OpenFailed(String)
case WriteFailed(String)
case ReadFailed(String)
case SeekFailed(String)
case GetCurrentWorkingDirectoryFailed(String)
case IsDirectoryFailed(String)
case OpenDirFailed(String)
}
public class File {
public static func openNewForWriting(path: String) throws -> File {
return try openFileForMode(path, "wb")
}
public static func openForReading(path: String) throws -> File {
return try openFileForMode(path, "rb")
}
public static func openForWritingAndReading(path: String) throws -> File {
return try openFileForMode(path, "r+b")
}
public static func openFileForMode(path: String, _ mode: String) throws -> File {
let file = path.withCString({ pathPointer in mode.withCString({ fopen(pathPointer, $0) }) })
guard file != nil else {
throw FileError.OpenFailed(descriptionOfLastError())
}
return File(file)
}
public static func isDirectory(path: String) throws -> Bool {
var s = stat()
guard path.withCString({ stat($0, &s) }) == 0 else {
throw FileError.IsDirectoryFailed(descriptionOfLastError())
}
return s.st_mode & S_IFMT == S_IFDIR
}
public static func currentWorkingDirectory() throws -> String {
let path = getcwd(nil, 0)
if path == nil {
throw FileError.GetCurrentWorkingDirectoryFailed(descriptionOfLastError())
}
guard let result = String.fromCString(path) else {
throw FileError.GetCurrentWorkingDirectoryFailed("Could not convert getcwd(...)'s result to String.")
}
return result
}
public static func exists(path: String) throws -> Bool {
var buffer = stat()
return path.withCString({ stat($0, &buffer) == 0 })
}
public static func list(path: String) throws -> [String] {
let dir = path.withCString { opendir($0) }
if dir == nil {
throw FileError.OpenDirFailed(descriptionOfLastError())
}
defer { closedir(dir) }
var results = [String]()
while true {
let ent = readdir(dir)
if ent == nil {
break
}
var name = ent.memory.d_name
let fileName = withUnsafePointer(&name) { (ptr) -> String? in
#if os(Linux)
return String.fromCString([CChar](UnsafeBufferPointer<CChar>(start: UnsafePointer(unsafeBitCast(ptr, UnsafePointer<CChar>.self)), count: Int(NAME_MAX))))
#else
var buffer = [CChar](UnsafeBufferPointer(start: unsafeBitCast(ptr, UnsafePointer<CChar>.self), count: Int(ent.memory.d_namlen)))
buffer.append(0)
return String.fromCString(buffer)
#endif
}
if let fileName = fileName {
results.append(fileName)
}
}
return results
}
let pointer: UnsafeMutablePointer<FILE>
public init(_ pointer: UnsafeMutablePointer<FILE>) {
self.pointer = pointer
}
public func close() -> Void {
fclose(pointer)
}
public func read(inout data: [UInt8]) throws -> Int {
if data.count <= 0 {
return data.count
}
let count = fread(&data, 1, data.count, self.pointer)
if count == data.count {
return count
}
if feof(self.pointer) != 0 {
return count
}
if ferror(self.pointer) != 0 {
throw FileError.ReadFailed(File.descriptionOfLastError())
}
throw FileError.ReadFailed("Unknown file read error occured.")
}
public func write(data: [UInt8]) throws -> Void {
if data.count <= 0 {
return
}
try data.withUnsafeBufferPointer {
if fwrite($0.baseAddress, 1, data.count, self.pointer) != data.count {
throw FileError.WriteFailed(File.descriptionOfLastError())
}
}
}
public func seek(offset: Int) throws -> Void {
if fseek(self.pointer, offset, SEEK_SET) != 0 {
throw FileError.SeekFailed(File.descriptionOfLastError())
}
}
private static func descriptionOfLastError() -> String {
return String.fromCString(UnsafePointer(strerror(errno))) ?? "Error: \(errno)"
}
}
extension File {
public static func withNewFileOpenedForWriting<Result>(path: String, _ f: File throws -> Result) throws -> Result {
return try withFileOpenedForMode(path, mode: "wb", f)
}
public static func withFileOpenedForReading<Result>(path: String, _ f: File throws -> Result) throws -> Result {
return try withFileOpenedForMode(path, mode: "rb", f)
}
public static func withFileOpenedForWritingAndReading<Result>(path: String, _ f: File throws -> Result) throws -> Result {
return try withFileOpenedForMode(path, mode: "r+b", f)
}
public static func withFileOpenedForMode<Result>(path: String, mode: String, _ f: File throws -> Result) throws -> Result {
let file = try File.openFileForMode(path, mode)
defer {
file.close()
}
return try f(file)
}
}
| mit | 9f4603d4cd044d9b504a575a7d036cca | 31.899408 | 173 | 0.590108 | 4.491115 | false | false | false | false |
cburrows/swift-protobuf | Tests/SwiftProtobufTests/Test_Duration.swift | 1 | 11895 | // Tests/SwiftProtobufTests/Test_Duration.swift - Exercise well-known Duration type
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Duration type includes custom JSON format, some hand-implemented convenience
/// methods, and arithmetic operators.
///
// -----------------------------------------------------------------------------
import XCTest
import SwiftProtobuf
import Foundation
class Test_Duration: XCTestCase, PBTestHelpers {
typealias MessageTestType = Google_Protobuf_Duration
func testJSON_encode() throws {
assertJSONEncode("\"100s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 0
}
// Always prints exactly 3, 6, or 9 digits
assertJSONEncode("\"100.100s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 100000000
}
assertJSONEncode("\"100.001s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 1000000
}
assertJSONEncode("\"100.000100s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 100000
}
assertJSONEncode("\"100.000001s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 1000
}
assertJSONEncode("\"100.000000100s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 100
}
assertJSONEncode("\"100.000000001s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 1
}
// Negative durations
assertJSONEncode("\"-100.100s\"") { (o: inout MessageTestType) in
o.seconds = -100
o.nanos = -100000000
}
}
func testJSON_decode() throws {
assertJSONDecodeSucceeds("\"1.000000000s\"") {(o:MessageTestType) in
o.seconds == 1 && o.nanos == 0
}
assertJSONDecodeSucceeds("\"-315576000000.999999999s\"") {(o:MessageTestType) in
o.seconds == -315576000000 && o.nanos == -999999999
}
assertJSONDecodeFails("\"-315576000001s\"")
assertJSONDecodeSucceeds("\"315576000000.999999999s\"") {(o:MessageTestType) in
o.seconds == 315576000000 && o.nanos == 999999999
}
assertJSONDecodeFails("\"315576000001s\"")
assertJSONDecodeFails("\"999999999999999999999.999999999s\"")
assertJSONDecodeFails("\"\"")
assertJSONDecodeFails("100.100s")
assertJSONDecodeFails("\"-100.-100s\"")
assertJSONDecodeFails("\"100.001\"")
assertJSONDecodeFails("\"100.001sXXX\"")
}
func testSerializationFailure() throws {
let maxOutOfRange = Google_Protobuf_Duration(seconds:-315576000001)
XCTAssertThrowsError(try maxOutOfRange.jsonString())
let minInRange = Google_Protobuf_Duration(seconds:-315576000000, nanos: -999999999)
let _ = try minInRange.jsonString() // Assert does not throw
let maxInRange = Google_Protobuf_Duration(seconds:315576000000, nanos: 999999999)
let _ = try maxInRange.jsonString() // Assert does not throw
let minOutOfRange = Google_Protobuf_Duration(seconds:315576000001)
XCTAssertThrowsError(try minOutOfRange.jsonString())
}
// Make sure durations work correctly when stored in a field
func testJSON_durationField() throws {
do {
let valid = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalDuration\": \"1.001s\"}")
XCTAssertEqual(valid.optionalDuration, Google_Protobuf_Duration(seconds: 1, nanos: 1000000))
} catch {
XCTFail("Should have decoded correctly")
}
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalDuration\": \"-315576000001.000000000s\"}"))
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalDuration\": \"315576000001.000000000s\"}"))
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalDuration\": \"1.001\"}"))
}
func testFieldMember() throws {
// Verify behavior when a duration appears as a field on a larger object
let json1 = "{\"optionalDuration\": \"-315576000000.999999999s\"}"
let m1 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json1)
XCTAssertEqual(m1.optionalDuration.seconds, -315576000000)
XCTAssertEqual(m1.optionalDuration.nanos, -999999999)
let json2 = "{\"repeatedDuration\": [\"1.5s\", \"-1.5s\"]}"
let expected2 = [Google_Protobuf_Duration(seconds:1, nanos:500000000), Google_Protobuf_Duration(seconds:-1, nanos:-500000000)]
let actual2 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json2)
XCTAssertEqual(actual2.repeatedDuration, expected2)
}
func testTranscode() throws {
let jsonMax = "{\"optionalDuration\": \"315576000000.999999999s\"}"
let parsedMax = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: jsonMax)
XCTAssertEqual(parsedMax.optionalDuration.seconds, 315576000000)
XCTAssertEqual(parsedMax.optionalDuration.nanos, 999999999)
XCTAssertEqual(try parsedMax.serializedData(), Data([234, 18, 13, 8, 128, 188, 174, 206, 151, 9, 16, 255, 147, 235, 220, 3]))
let jsonMin = "{\"optionalDuration\": \"-315576000000.999999999s\"}"
let parsedMin = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: jsonMin)
XCTAssertEqual(parsedMin.optionalDuration.seconds, -315576000000)
XCTAssertEqual(parsedMin.optionalDuration.nanos, -999999999)
XCTAssertEqual(try parsedMin.serializedData(), Data([234, 18, 22, 8, 128, 196, 209, 177, 232, 246, 255, 255, 255, 1, 16, 129, 236, 148, 163, 252, 255, 255, 255, 255, 1]))
}
func testConformance() throws {
let tooSmall = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: Data([234, 18, 11, 8, 255, 195, 209, 177, 232, 246, 255, 255, 255, 1]))
XCTAssertEqual(tooSmall.optionalDuration.seconds, -315576000001)
XCTAssertEqual(tooSmall.optionalDuration.nanos, 0)
XCTAssertThrowsError(try tooSmall.jsonString())
let tooBig = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: Data([234, 18, 7, 8, 129, 188, 174, 206, 151, 9]))
XCTAssertEqual(tooBig.optionalDuration.seconds, 315576000001)
XCTAssertEqual(tooBig.optionalDuration.nanos, 0)
XCTAssertThrowsError(try tooBig.jsonString())
}
func testBasicArithmetic() throws {
let an2_n2 = Google_Protobuf_Duration(seconds: -2, nanos: -2)
let an1_n1 = Google_Protobuf_Duration(seconds: -1, nanos: -1)
let a0 = Google_Protobuf_Duration()
let a1_1 = Google_Protobuf_Duration(seconds: 1, nanos: 1)
let a2_2 = Google_Protobuf_Duration(seconds: 2, nanos: 2)
let a3_3 = Google_Protobuf_Duration(seconds: 3, nanos: 3)
let a4_4 = Google_Protobuf_Duration(seconds: 4, nanos: 4)
XCTAssertEqual(a1_1, a0 + a1_1)
XCTAssertEqual(a1_1, a1_1 + a0)
XCTAssertEqual(a2_2, a1_1 + a1_1)
XCTAssertEqual(a3_3, a1_1 + a2_2)
XCTAssertEqual(a1_1, a4_4 - a3_3)
XCTAssertEqual(an1_n1, a3_3 - a4_4)
XCTAssertEqual(an1_n1, a3_3 + -a4_4)
XCTAssertEqual(an1_n1, -a1_1)
XCTAssertEqual(a2_2, -an2_n2)
XCTAssertEqual(a2_2, -an2_n2)
}
func testArithmeticNormalizes() throws {
// Addition normalizes the result
XCTAssertEqual(Google_Protobuf_Duration() + Google_Protobuf_Duration(seconds: 0, nanos: 2000000001),
Google_Protobuf_Duration(seconds: 2, nanos: 1))
// Subtraction normalizes the result
XCTAssertEqual(Google_Protobuf_Duration() - Google_Protobuf_Duration(seconds: 0, nanos: 2000000001),
Google_Protobuf_Duration(seconds: -2, nanos: -1))
// Unary minus normalizes the result
XCTAssertEqual(-Google_Protobuf_Duration(seconds: 0, nanos: 2000000001),
Google_Protobuf_Duration(seconds: -2, nanos: -1))
XCTAssertEqual(-Google_Protobuf_Duration(seconds: 0, nanos: -2000000001),
Google_Protobuf_Duration(seconds: 2, nanos: 1))
XCTAssertEqual(-Google_Protobuf_Duration(seconds: 1, nanos: -2000000001),
Google_Protobuf_Duration(seconds: 1, nanos: 1))
XCTAssertEqual(-Google_Protobuf_Duration(seconds: -1, nanos: 2000000001),
Google_Protobuf_Duration(seconds: -1, nanos: -1))
XCTAssertEqual(-Google_Protobuf_Duration(seconds: -1, nanos: -2000000001),
Google_Protobuf_Duration(seconds: 3, nanos: 1))
XCTAssertEqual(-Google_Protobuf_Duration(seconds: 1, nanos: 2000000001),
Google_Protobuf_Duration(seconds: -3, nanos: -1))
}
func testFloatLiteralConvertible() throws {
var a: Google_Protobuf_Duration = 1.5
XCTAssertEqual(a, Google_Protobuf_Duration(seconds: 1, nanos: 500000000))
a = 100.000000001
XCTAssertEqual(a, Google_Protobuf_Duration(seconds: 100, nanos: 1))
a = 1.9999999991
XCTAssertEqual(a, Google_Protobuf_Duration(seconds: 1, nanos: 999999999))
a = 1.9999999999
XCTAssertEqual(a, Google_Protobuf_Duration(seconds: 2, nanos: 0))
var c = ProtobufTestMessages_Proto3_TestAllTypesProto3()
c.optionalDuration = 100.000000001
XCTAssertEqual(Data([234, 18, 4, 8, 100, 16, 1]), try c.serializedData())
XCTAssertEqual("{\"optionalDuration\":\"100.000000001s\"}", try c.jsonString())
}
func testInitializationByTimeIntervals() throws {
// Negative interval
let t1 = Google_Protobuf_Duration(timeInterval: -123.456)
XCTAssertEqual(t1.seconds, -123)
XCTAssertEqual(t1.nanos, -456000000)
// Full precision
let t2 = Google_Protobuf_Duration(timeInterval: -123.999999999)
XCTAssertEqual(t2.seconds, -123)
XCTAssertEqual(t2.nanos, -999999999)
// Round up
let t3 = Google_Protobuf_Duration(timeInterval: -123.9999999994)
XCTAssertEqual(t3.seconds, -123)
XCTAssertEqual(t3.nanos, -999999999)
// Round down
let t4 = Google_Protobuf_Duration(timeInterval: -123.9999999996)
XCTAssertEqual(t4.seconds, -124)
XCTAssertEqual(t4.nanos, 0)
let t5 = Google_Protobuf_Duration(timeInterval: 0)
XCTAssertEqual(t5.seconds, 0)
XCTAssertEqual(t5.nanos, 0)
// Positive interval
let t6 = Google_Protobuf_Duration(timeInterval: 123.456)
XCTAssertEqual(t6.seconds, 123)
XCTAssertEqual(t6.nanos, 456000000)
// Full precision
let t7 = Google_Protobuf_Duration(timeInterval: 123.999999999)
XCTAssertEqual(t7.seconds, 123)
XCTAssertEqual(t7.nanos, 999999999)
// Round down
let t8 = Google_Protobuf_Duration(timeInterval: 123.9999999994)
XCTAssertEqual(t8.seconds, 123)
XCTAssertEqual(t8.nanos, 999999999)
// Round up
let t9 = Google_Protobuf_Duration(timeInterval: 123.9999999996)
XCTAssertEqual(t9.seconds, 124)
XCTAssertEqual(t9.nanos, 0)
}
func testGetters() throws {
let t1 = Google_Protobuf_Duration(seconds: -123, nanos: -123456789)
XCTAssertEqual(t1.timeInterval, -123.123456789)
let t2 = Google_Protobuf_Duration(seconds: 123, nanos: 123456789)
XCTAssertEqual(t2.timeInterval, 123.123456789)
}
}
| apache-2.0 | 974148efa90a7e6359015f922be3806f | 45.104651 | 178 | 0.646995 | 4.408821 | false | true | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Blogging Reminders/BloggingRemindersFlowIntroViewController.swift | 1 | 8449 | import UIKit
class BloggingRemindersFlowIntroViewController: UIViewController {
// MARK: - Subviews
private let stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.spacing = Metrics.stackSpacing
stackView.axis = .vertical
stackView.alignment = .center
stackView.distribution = .equalSpacing
return stackView
}()
private let imageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: Images.celebrationImageName))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.tintColor = .systemYellow
return imageView
}()
private let titleLabel: UILabel = {
let label = UILabel()
label.adjustsFontForContentSizeCategory = true
label.adjustsFontSizeToFitWidth = true
label.font = WPStyleGuide.serifFontForTextStyle(.title1, fontWeight: .semibold)
label.numberOfLines = 2
label.textAlignment = .center
label.text = TextContent.introTitle
return label
}()
private let promptLabel: UILabel = {
let label = UILabel()
label.adjustsFontForContentSizeCategory = true
label.adjustsFontSizeToFitWidth = true
label.font = .preferredFont(forTextStyle: .body)
label.numberOfLines = 5
label.textAlignment = .center
return label
}()
private let getStartedButton: UIButton = {
let button = FancyButton()
button.isPrimary = true
button.setTitle(TextContent.introButtonTitle, for: .normal)
button.addTarget(self, action: #selector(getStartedTapped), for: .touchUpInside)
return button
}()
private let dismissButton: UIButton = {
let button = UIButton(type: .custom)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(.gridicon(.cross), for: .normal)
button.tintColor = .secondaryLabel
button.addTarget(self, action: #selector(dismissTapped), for: .touchUpInside)
return button
}()
// MARK: - Initializers
private let blog: Blog
private let tracker: BloggingRemindersTracker
private let source: BloggingRemindersTracker.FlowStartSource
private var introDescription: String {
switch source {
case .publishFlow:
return TextContent.postPublishingintroDescription
case .blogSettings:
return TextContent.siteSettingsIntroDescription
}
}
init(for blog: Blog, tracker: BloggingRemindersTracker, source: BloggingRemindersTracker.FlowStartSource) {
self.blog = blog
self.tracker = tracker
self.source = source
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
// This VC is designed to be instantiated programmatically. If we ever need to initialize this VC
// from a coder, we can implement support for it - but I don't think it's necessary right now.
// - diegoreymendez
fatalError("Use init(tracker:) instead")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .basicBackground
view.addSubview(dismissButton)
configureStackView()
configureConstraints()
promptLabel.text = introDescription
}
override func viewDidAppear(_ animated: Bool) {
tracker.screenShown(.main)
super.viewDidAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// If a parent VC is being dismissed, and this is the last view shown in its navigation controller, we'll assume
// the flow was interrupted.
if isBeingDismissedDirectlyOrByAncestor() && navigationController?.viewControllers.last == self {
tracker.flowDismissed(source: .main)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
calculatePreferredContentSize()
}
private func calculatePreferredContentSize() {
let size = CGSize(width: view.bounds.width, height: UIView.layoutFittingCompressedSize.height)
preferredContentSize = view.systemLayoutSizeFitting(size)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
view.setNeedsLayout()
}
// MARK: - View Configuration
private func configureStackView() {
view.addSubview(stackView)
stackView.addArrangedSubviews([
imageView,
titleLabel,
promptLabel,
getStartedButton
])
stackView.setCustomSpacing(Metrics.afterPromptSpacing, after: promptLabel)
}
private func configureConstraints() {
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Metrics.edgeMargins.left),
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Metrics.edgeMargins.right),
stackView.topAnchor.constraint(equalTo: view.topAnchor, constant: Metrics.edgeMargins.top),
stackView.bottomAnchor.constraint(lessThanOrEqualTo: view.safeBottomAnchor, constant: -Metrics.edgeMargins.bottom),
getStartedButton.heightAnchor.constraint(greaterThanOrEqualToConstant: Metrics.getStartedButtonHeight),
getStartedButton.widthAnchor.constraint(equalTo: stackView.widthAnchor),
dismissButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Metrics.edgeMargins.right),
dismissButton.topAnchor.constraint(equalTo: view.topAnchor, constant: Metrics.edgeMargins.right)
])
}
@objc private func getStartedTapped() {
tracker.buttonPressed(button: .continue, screen: .main)
do {
let flowSettingsViewController = try BloggingRemindersFlowSettingsViewController(for: blog, tracker: tracker)
navigationController?.pushViewController(flowSettingsViewController, animated: true)
} catch {
DDLogError("Could not instantiate the blogging reminders settings VC: \(error.localizedDescription)")
dismiss(animated: true, completion: nil)
}
}
}
extension BloggingRemindersFlowIntroViewController: BloggingRemindersActions {
@objc private func dismissTapped() {
dismiss(from: .dismiss, screen: .main, tracker: tracker)
}
}
// MARK: - DrawerPresentable
extension BloggingRemindersFlowIntroViewController: DrawerPresentable {
var collapsedHeight: DrawerHeight {
return .intrinsicHeight
}
}
// MARK: - ChildDrawerPositionable
extension BloggingRemindersFlowIntroViewController: ChildDrawerPositionable {
var preferredDrawerPosition: DrawerPosition {
return .collapsed
}
}
// MARK: - Constants
private enum TextContent {
static let introTitle = NSLocalizedString("Set your blogging reminders",
comment: "Title of the Blogging Reminders Settings screen.")
static let postPublishingintroDescription = NSLocalizedString("Your post is publishing... in the meantime, set up your blogging reminders on days you want to post.",
comment: "Description on the first screen of the Blogging Reminders Settings flow called aftet post publishing.")
static let siteSettingsIntroDescription = NSLocalizedString("Set up your blogging reminders on days you want to post.",
comment: "Description on the first screen of the Blogging Reminders Settings flow called from site settings.")
static let introButtonTitle = NSLocalizedString("Set reminders",
comment: "Title of the set goals button in the Blogging Reminders Settings flow.")
}
private enum Images {
static let celebrationImageName = "reminders-celebration"
}
private enum Metrics {
static let edgeMargins = UIEdgeInsets(top: 46, left: 20, bottom: 20, right: 20)
static let stackSpacing: CGFloat = 20.0
static let afterPromptSpacing: CGFloat = 24.0
static let getStartedButtonHeight: CGFloat = 44.0
}
| gpl-2.0 | b2b0b2a693e070fbde44b291a2e8730b | 35.895197 | 170 | 0.683513 | 5.475697 | false | false | false | false |
abertelrud/swift-package-manager | Sources/LLBuildManifest/ManifestWriter.swift | 2 | 5105 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TSCBasic
public struct ManifestWriter {
let fileSystem: FileSystem
public init(fileSystem: FileSystem) {
self.fileSystem = fileSystem
}
public func write(
_ manifest: BuildManifest,
at path: AbsolutePath
) throws {
let stream = BufferedOutputByteStream()
stream <<< """
client:
name: basic
tools: {}
targets:\n
"""
for (_, target) in manifest.targets.sorted(by: { $0.key < $1.key }) {
stream <<< " " <<< Format.asJSON(target.name)
stream <<< ": " <<< Format.asJSON(target.nodes.map{ $0.name }.sorted()) <<< "\n"
}
stream <<< "default: " <<< Format.asJSON(manifest.defaultTarget) <<< "\n"
// We need to explicitly configure the directory structure nodes.
let directoryStructureNodes = Set(manifest.commands
.values
.flatMap{ $0.tool.inputs }
.filter{ $0.kind == .directoryStructure }
)
if !directoryStructureNodes.isEmpty {
stream <<< "nodes:\n"
}
let namesToExclude = [".git", ".build"]
for node in directoryStructureNodes.sorted(by: { $0.name < $1.name }) {
stream <<< " " <<< Format.asJSON(node) <<< ":\n"
stream <<< " is-directory-structure: true\n"
stream <<< " content-exclusion-patterns: " <<< Format.asJSON(namesToExclude) <<< "\n"
}
stream <<< "commands:\n"
for (_, command) in manifest.commands.sorted(by: { $0.key < $1.key }) {
stream <<< " " <<< Format.asJSON(command.name) <<< ":\n"
let tool = command.tool
let manifestToolWriter = ManifestToolStream(stream)
manifestToolWriter["tool"] = tool
manifestToolWriter["inputs"] = tool.inputs
manifestToolWriter["outputs"] = tool.outputs
tool.write(to: manifestToolWriter)
stream <<< "\n"
}
try self.fileSystem.writeFileContents(path, bytes: stream.bytes)
}
}
public final class ManifestToolStream {
private let stream: OutputByteStream
fileprivate init(_ stream: OutputByteStream) {
self.stream = stream
}
public subscript(key: String) -> Int {
get { fatalError() }
set {
stream <<< " \(key): " <<< Format.asJSON(newValue) <<< "\n"
}
}
public subscript(key: String) -> String {
get { fatalError() }
set {
stream <<< " \(key): " <<< Format.asJSON(newValue) <<< "\n"
}
}
public subscript(key: String) -> ToolProtocol {
get { fatalError() }
set {
stream <<< " \(key): " <<< type(of: newValue).name <<< "\n"
}
}
public subscript(key: String) -> AbsolutePath {
get { fatalError() }
set {
stream <<< " \(key): " <<< Format.asJSON(newValue.pathString) <<< "\n"
}
}
public subscript(key: String) -> [AbsolutePath] {
get { fatalError() }
set {
stream <<< " \(key): " <<< Format.asJSON(newValue.map{$0.pathString}) <<< "\n"
}
}
public subscript(key: String) -> [Node] {
get { fatalError() }
set {
stream <<< " \(key): " <<< Format.asJSON(newValue) <<< "\n"
}
}
public subscript(key: String) -> Bool {
get { fatalError() }
set {
stream <<< " \(key): " <<< Format.asJSON(newValue) <<< "\n"
}
}
public subscript(key: String) -> [String] {
get { fatalError() }
set {
stream <<< " \(key): " <<< Format.asJSON(newValue) <<< "\n"
}
}
public subscript(key: String) -> [String: String] {
get { fatalError() }
set {
stream <<< " \(key):\n"
for (key, value) in newValue.sorted(by: { $0.key < $1.key }) {
stream <<< " " <<< Format.asJSON(key) <<< ": " <<< Format.asJSON(value) <<< "\n"
}
}
}
}
extension Format {
static func asJSON(_ items: [Node]) -> ByteStreamable {
return asJSON(items.map { $0.encodingName })
}
static func asJSON(_ item: Node) -> ByteStreamable {
return asJSON(item.encodingName)
}
}
extension Node {
fileprivate var encodingName: String {
switch kind {
case .virtual, .file:
return name
case .directory, .directoryStructure:
return name + "/"
}
}
}
| apache-2.0 | 44141200890ddb3dbb0900b28dcabb34 | 28.853801 | 101 | 0.500881 | 4.352089 | false | false | false | false |
kickstarter/ios-oss | Library/Tracking/Vendor/BrazeDebounceMiddleware.swift | 1 | 2111 | import Foundation
import Segment
private let __brazeIntegrationName = "Appboy"
/// Ref: https://github.com/segmentio/segment-braze-mobile-middleware
class BrazeDebounceMiddleware: Middleware {
var previousIdentifyPayload: IdentifyPayload?
func context(_ context: Context, next: @escaping SEGMiddlewareNext) {
var workingContext = context
// only process identify payloads.
guard let identify = workingContext.payload as? IdentifyPayload else {
next(workingContext)
return
}
if self.shouldSendToBraze(payload: identify) {
// we don't need to do anything, it's different content.
} else {
// append to integrations such that this will not be sent to braze.
var integrations = identify.integrations
integrations[__brazeIntegrationName] = false
// provide the list of integrations to a new copy of the payload to pass along.
workingContext = workingContext.modify { ctx in
ctx.payload = IdentifyPayload(
userId: identify.userId,
anonymousId: identify.anonymousId,
traits: identify.traits,
context: identify.context,
integrations: integrations
)
}
}
self.previousIdentifyPayload = identify
next(workingContext)
}
func shouldSendToBraze(payload: IdentifyPayload) -> Bool {
// if userID has changed, send it to braze.
if payload.userId != self.previousIdentifyPayload?.userId {
return true
}
// if anonymousID has changed, send it to braze.
if payload.anonymousId != self.previousIdentifyPayload?.anonymousId {
return true
}
// if the traits haven't changed, don't send it to braze.
if self.traitsEqual(lhs: payload.traits, rhs: self.previousIdentifyPayload?.traits) {
return false
}
return true
}
func traitsEqual(lhs: [String: Any]?, rhs: [String: Any]?) -> Bool {
var result = false
if lhs == nil, rhs == nil {
result = true
}
if let lhs = lhs, let rhs = rhs {
result = NSDictionary(dictionary: lhs).isEqual(to: rhs)
}
return result
}
}
| apache-2.0 | d39cf7f40e3bf51e754c3473ac70f8d6 | 27.917808 | 89 | 0.669351 | 4.397917 | false | false | false | false |
ZhaoBingDong/CYPhotosLibrary | CYPhotoKit/Controller/CYPhotoGroupController.swift | 1 | 6113 | //
// CYPhotoGroupController.swift
// CYPhotosKit
//
// Created by 董招兵 on 2017/8/7.
// Copyright © 2017年 大兵布莱恩特. All rights reserved.
//
import UIKit
import Photos
public class CYPhotoGroupController: UIViewController {
private var sectionFetchResults : [CYPhotosCollection] = [CYPhotosCollection]()
lazy private var tableView : UITableView = {
let tableView = UITableView(frame: CGRect.init(x: 0.0, y: 0.0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height), style:.plain)
tableView.tableFooterView = UIView()
return tableView
}()
override public func viewDidLoad() {
super.viewDidLoad()
setup()
reqeustAuthorization()
}
@objc func dismissViewController() {
NotificationCenter.default.post(name: NSNotification.Name("photosViewControllDismiss"), object: nil, userInfo: nil)
}
private func setup() {
self.view.backgroundColor = .white
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(dismissViewController))
title = "照片"
view.addSubview(tableView)
tableView.register(CYPhotoLibrayGroupCell.self, forCellReuseIdentifier: "CYPhotoLibrayGroupCell")
tableView.rowHeight = 80.0
tableView.delegate = self
tableView.dataSource = self
}
/*
请求访问相册的权限
*/
private func reqeustAuthorization() {
let authorizedStatus = PHPhotoLibrary.authorizationStatus()
guard authorizedStatus != .authorized else {
photosAuthorizedSuccess()
return
}
PHPhotoLibrary.requestAuthorization { (status) in
switch status {
case .authorized:
NSLog("用户允许当前应用访问相册")
self.perform(#selector(self.photosAuthorizedSuccess), on: Thread.main, with: nil, waitUntilDone: true)
break
case .denied :
self.perform(#selector(self.showAuthorizationViewController), on: Thread.main, with: nil, waitUntilDone: true)
NSLog("用户拒绝当前应用访问相册,我们需要提醒用户打开访问开关")
break
case .notDetermined :
self.perform(#selector(self.showAuthorizationViewController), on: Thread.main, with: nil, waitUntilDone: true)
NSLog("用户还没有做出选择")
break
case .restricted :
self.perform(#selector(self.showAuthorizationViewController), on: Thread.main, with: nil, waitUntilDone: true)
NSLog("家长控制,不允许访问")
break
}
}
}
/*
获取相册权限成功
*/
@objc private func photosAuthorizedSuccess() {
let photosManager = CYPhotosManager.default
let dataArray = photosManager.allCollections
if let photoCollection = dataArray.first {
self.openPhotosListViewController(with: photoCollection, animated: false)
}
self.sectionFetchResults = dataArray
self.tableView.reloadData()
NotificationCenter.default.addObserver(self, selector: #selector(photoLibraryDidChange), name: Notification.Name.init("PHPhotoLibraryChangeObserver"), object: nil)
}
@objc private func showAuthorizationViewController(_ viewController : CYAuthorizedFailureViewController) {
let authorizationVC = CYAuthorizedFailureViewController()
self.navigationController?.pushViewController(authorizationVC, animated: false)
}
private func openPhotosListViewController(with photosCollection : CYPhotosCollection ,animated :Bool) {
guard photosCollection.fetchResult?.count != nil else { return }
let photoDetailVC = CYPhotoListViewController()
photoDetailVC.fetchResult = photosCollection.allObjects
photoDetailVC.title = photosCollection.localizedTitle
self.navigationController?.pushViewController(photoDetailVC, animated: animated)
}
deinit {
// NSLog("self dealloc ")
NotificationCenter.default.removeObserver(self)
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
}
//MARK: UITableViewDelegate & UITableViewDataSource
extension CYPhotoGroupController : UITableViewDelegate , UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sectionFetchResults.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : CYPhotoLibrayGroupCell = tableView.dequeueReusableCell(withIdentifier: "CYPhotoLibrayGroupCell") as! CYPhotoLibrayGroupCell
let photosCollection = self.sectionFetchResults[indexPath.row]
cell.photoImageView.image = photosCollection.thumbnail
cell.titleLabel.text = String.init(format: "%@ (%@)", arguments: [photosCollection.localizedTitle!,photosCollection.count!])
photosCollection.getSelectImageCount(close: { (count) in
cell.badgeValue.isHidden = count == 0
print("IndexPath : \(indexPath.row) count :\(count)")
})
return cell
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let photosCollection = self.sectionFetchResults[indexPath.item]
openPhotosListViewController(with: photosCollection, animated: true)
}
}
// MARK: PHPhotoLibraryChangeObserver
extension CYPhotoGroupController {
@objc public func photoLibraryDidChange() {
self.sectionFetchResults = CYPhotosManager.default.allCollections
}
}
| apache-2.0 | 268a0fcf29a5ae549b2ecf314808c7a6 | 36.582278 | 171 | 0.656113 | 5.150043 | false | false | false | false |
adamfraser/ImageSlideshow | Pod/Classes/InputSources/AlamofireSource.swift | 1 | 806 | //
// AlamofireSource.swift
// Pods
//
// Created by Petr Zvoníček on 14.01.16.
//
//
import Alamofire
import AlamofireImage
public class AlamofireSource: NSObject, InputSource {
var url: NSURL!
public init(url: NSURL) {
self.url = url
super.init()
}
public init?(urlString: String) {
if let validUrl = NSURL(string: urlString) {
self.url = validUrl
super.init()
} else {
super.init()
return nil
}
}
public func setToImageView(imageView: UIImageView) {
Alamofire.request(.GET, self.url)
.responseImage { response in
if let image = response.result.value {
imageView.image = image
}
}
}
}
| mit | 229c3210fcecbb7de8240f474a343e57 | 19.615385 | 56 | 0.529851 | 4.253968 | false | false | false | false |
brentsimmons/Frontier | BeforeTheRename/FrontierVerbs/FrontierVerbs/VerbParams.swift | 1 | 1338 | //
// VerbParameters.swift
// FrontierVerbs
//
// Created by Brent Simmons on 4/12/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Cocoa
import FrontierData
public typealias NamedParams = [String: Value]
public struct VerbParams {
static let empty = VerbParams([])
let ordered: [Value]
let named: NamedParams
let count: Int
public init(_ ordered: [Value], named: NamedParams = NamedParams()) {
self.ordered = ordered
self.named = named
self.count = ordered.count
}
// MARK: Common Cases
func singleParam() throws -> Value {
guard count == 1 else {
throw paramCountError(1)
}
return ordered[0]
}
func binaryParams() throws -> (Value, Value) {
guard count == 2 else {
throw paramCountError(2)
}
return (ordered[0], ordered[1])
}
func trinaryParams() throws -> (Value, Value, Value) {
guard count == 3 else {
throw paramCountError(3)
}
return (ordered[0], ordered[1], ordered[2])
}
// MARK: Errors
func paramCountError(_ expected: Int) -> LangError {
assert(expected != count)
if expected < count {
return LangError(.notEnoughParameters)
}
return LangError(.tooManyParameters)
}
func throwParamCountErrorIfNeeded(_ expected: Int) throws {
if expected != count {
throw paramCountError(expected)
}
}
}
| gpl-2.0 | 784c33645230012abef2c1ab874591d7 | 17.315068 | 70 | 0.666417 | 3.402036 | false | false | false | false |
lukaszwas/mcommerce-api | Sources/App/Models/Stripe/Models/Outcome.swift | 1 | 1934 | //
// Outcome.swift
// Stripe
//
// Created by Anthony Castelli on 4/15/17.
//
//
import Foundation
import Vapor
/*
Outcome
https://stripe.com/docs/api/curl#charge_object-outcome
*/
public enum NetworkStatus: String {
case approvedByNetwork = "approved_by_network"
case declinedByNetwork = "declined_by_network"
case notSentToNetwork = "not_sent_to_network"
case reversedAfterApproval = "reversed_after_approval"
}
public enum RiskLevel: String {
case normal = "normal"
case elevated = "elevated"
case highest = "highest"
case notAssessed = "not_assessed"
case unknown = "unknown"
}
public enum OutcomeType: String {
case authorized = "authorized"
case manualReview = "manual_review"
case issuerDeclined = "issuer_declined"
case blocked = "blocked"
case invalid = "invalid"
}
public final class Outcome: StripeModelProtocol {
public let networkStatus: NetworkStatus?
public let reason: String?
public let riskLevel: RiskLevel?
public let rule: String?
public let sellerMessage: String
public let type: OutcomeType?
public init(node: Node) throws {
self.networkStatus = try NetworkStatus(rawValue: node.get("network_status"))
self.reason = try node.get("reason")
self.riskLevel = try RiskLevel(rawValue: node.get("risk_level"))
self.rule = try node.get("rule")
self.sellerMessage = try node.get("seller_message")
self.type = try OutcomeType(rawValue: node.get("type"))
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"network_status": self.networkStatus?.rawValue,
"reason": self.reason ?? nil,
"risk_level": self.riskLevel?.rawValue,
"rule": self.rule ?? nil,
"seller_message": self.sellerMessage,
"type": self.type?.rawValue
])
}
}
| mit | 98e94d616e729a115eda2717c874f957 | 27.441176 | 84 | 0.649431 | 3.91498 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Binary Search/744_Find Smallest Letter Greater Than Target.swift | 1 | 2460 | // 744_Find Smallest Letter Greater Than Target
// https://leetcode.com/problems/find-smallest-letter-greater-than-target/
//
// Created by Honghao Zhang on 9/16/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target.
//
//Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'.
//
//Examples:
//
//Input:
//letters = ["c", "f", "j"]
//target = "a"
//Output: "c"
//
//Input:
//letters = ["c", "f", "j"]
//target = "c"
//Output: "f"
//
//Input:
//letters = ["c", "f", "j"]
//target = "d"
//Output: "f"
//
//Input:
//letters = ["c", "f", "j"]
//target = "g"
//Output: "j"
//
//Input:
//letters = ["c", "f", "j"]
//target = "j"
//Output: "c"
//
//Input:
//letters = ["c", "f", "j"]
//target = "k"
//Output: "c"
//Note:
//
//letters has a length in range [2, 10000].
//letters consists of lowercase letters, and contains at least 2 unique letters.
//target is a lowercase letter.
//
import Foundation
class Num744 {
/// Binary search to find the last index of the target
func nextGreatestLetter(_ letters: [Character], _ target: Character) -> Character {
assert(letters.count >= 2)
// find the last index of the target
var start = 0
var end = letters.count - 1
while start + 1 < end {
let mid = start + (end - start) / 2
if letters[mid] < target {
start = mid
}
else if letters[mid] > target {
end = mid
}
else {
// if equal, move start
start = mid
}
}
// if found
if letters[start] == target {
// if start/end is same
if letters[end] == target {
// wraps around
return letters[0]
}
// if start/ned is not the same
else {
return letters[end]
}
}
else if letters[end] == target {
// wraps around
return letters[0]
}
// if not found
else {
// target is smaller than start
if target < letters[start] {
return letters[start]
}
// target is between start and end
else if letters[start] < target, target < letters[end] {
return letters[end]
}
// target is greater than end
else {
return letters[0]
}
}
}
}
| mit | f2f687385810551d19ae9d0c751dd100 | 22.419048 | 189 | 0.569337 | 3.483003 | false | false | false | false |
shridharmalimca/iOSDev | iOS/Swift 4.0/CustomTableviewCell/CustomTableviewCell/RegistrationModel.swift | 2 | 1651 | //
// RegistrationModel.swift
// CustomTableviewCell
//
// Created by Shridhar Mali on 1/28/18.
// Copyright © 2018 Shridhar Mali. All rights reserved.
//
import UIKit
class RegistrationModel: NSObject {
var userInfo = [User]()
var fields = ["FirstName",
"LastName",
"Password",
"Confirm Password",
"Email",
"Mobile"]
var errorMsg = ["Please enter name",
"Please enter last name",
"Please enter password",
"Please enter confirm password",
"Please enter email",
"Please enter mobile number"]
var textFieldSuggesstions = ["First name allows only chars",
"Last name allows only chars",
"Password with 1 special char, 1 digit, max length 4",
"Confirm password with 1 special char, 1 digit, max length 4",
"Email allow '@' & '.com' only",
"Mobile number allow only 10 digits"]
func configureCell() -> [User] {
for (index, field) in fields.enumerated() {
let user = User()
user.fieldValue = field
user.fieldErrorMsg = errorMsg[index]
user.isValid = true
user.suggesstionMsg = textFieldSuggesstions[index]
userInfo.append(user)
}
return userInfo
}
}
class User {
var fieldValue: String?
var fieldErrorMsg: String?
var placeholder: String?
var isValid: Bool = false
var suggesstionMsg: String?
}
| apache-2.0 | 600ec2ce691b2363a1600302167fe025 | 29 | 82 | 0.530303 | 4.852941 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Controller/LinearEquations/CLinearEquationsPlot.swift | 1 | 6855 | import UIKit
class CLinearEquationsPlot:CController
{
let model:MLinearEquationsPlot
weak var viewPlot:VLinearEquationsPlot!
private let kIndeterminatesWidth:CGFloat = 350
private let kEquationsMargin:CGFloat = 20
private let kTextTop:CGFloat = 9
init(stepDone:MLinearEquationsSolutionStepDone)
{
model = MLinearEquationsPlot(stepDone:stepDone)
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
override func loadView()
{
let viewPlot:VLinearEquationsPlot = VLinearEquationsPlot(controller:self)
self.viewPlot = viewPlot
view = viewPlot
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidAppear(animated)
guard
let device:MTLDevice = viewPlot.viewMetal?.device
else
{
return
}
if model.modelRender == nil
{
model.makeRender(device:device)
viewPlot.viewMenu.refresh()
}
parentController.viewParent.panRecognizer.isEnabled = false
}
override func viewWillTransition(to size:CGSize, with coordinator:UIViewControllerTransitionCoordinator)
{
model.modelRender?.updateProjection(
width:size.width,
height:size.height)
}
//MARK: private
private func shareTexture()
{
guard
let texture:UIImage = viewPlot.viewMetal?.currentDrawable?.texture.exportImage(),
let modelMenu:MLinearEquationsPlotMenu = model.modelMenu
else
{
finishLoading()
return
}
let textureWidth:CGFloat = texture.size.width
let textureHeight:CGFloat = texture.size.height
let totalWidth:CGFloat = textureWidth + kIndeterminatesWidth
let totalSize:CGSize = CGSize(width:totalWidth, height:textureHeight)
let totalFrame:CGRect = CGRect(origin:CGPoint.zero, size:totalSize)
let textureFrame:CGRect = CGRect(origin:CGPoint.zero, size:texture.size)
UIGraphicsBeginImageContextWithOptions(totalSize, true, 1)
guard
let context:CGContext = UIGraphicsGetCurrentContext()
else
{
UIGraphicsEndImageContext()
finishLoading()
return
}
context.setFillColor(UIColor.white.cgColor)
context.fill(totalFrame)
texture.draw(in:textureFrame)
let textAttributes:[String:AnyObject] = [
NSFontAttributeName:UIFont.numericBold(size:30),
NSForegroundColorAttributeName:UIColor.black]
let equationIcon:UIImage = #imageLiteral(resourceName: "assetTexturePoint")
let iconWidth:CGFloat = equationIcon.size.width
let iconHeight:CGFloat = equationIcon.size.height
let textWidth:CGFloat = kIndeterminatesWidth - (iconWidth + kEquationsMargin + kEquationsMargin)
let currentX:CGFloat = textureWidth + kEquationsMargin
var currentY:CGFloat = kEquationsMargin
for menuItem:MLinearEquationsPlotMenuItem in modelMenu.items
{
guard
let menuItem:MLinearEquationsPlotMenuItemEquation = menuItem as? MLinearEquationsPlotMenuItemEquation
else
{
continue
}
let iconRect:CGRect = CGRect(
x:currentX,
y:currentY,
width:iconWidth,
height:iconHeight)
let textRect:CGRect = CGRect(
x:currentX + iconWidth + kEquationsMargin,
y:currentY + kTextTop,
width:textWidth,
height:iconHeight)
let rawString:String = menuItem.title.string
let attributedString:NSAttributedString = NSAttributedString(
string:rawString,
attributes:textAttributes)
context.setBlendMode(CGBlendMode.normal)
equationIcon.draw(in:iconRect)
context.setBlendMode(CGBlendMode.color)
context.setFillColor(menuItem.color.cgColor)
context.fill(iconRect)
context.setBlendMode(CGBlendMode.normal)
attributedString.draw(in:textRect)
currentY += iconHeight
currentY += kEquationsMargin
}
guard
let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()
else
{
UIGraphicsEndImageContext()
finishLoading()
return
}
UIGraphicsEndImageContext()
DispatchQueue.main.async
{ [weak self] in
self?.finishSharing(image:image)
}
}
private func finishSharing(image:UIImage)
{
let activity:UIActivityViewController = UIActivityViewController(
activityItems:[image],
applicationActivities:nil)
if let popover:UIPopoverPresentationController = activity.popoverPresentationController
{
popover.sourceView = viewPlot
popover.sourceRect = CGRect.zero
popover.permittedArrowDirections = UIPopoverArrowDirection.up
}
finishLoading()
present(activity, animated:true)
AnalyticsManager.sharedInstance?.trackShare(action:AnalyticsManager.ShareAction.plot)
}
private func finishLoading()
{
DispatchQueue.main.async
{ [weak self] in
self?.viewPlot.stopLoading()
}
}
//MARK: public
func back()
{
parentController.pop(horizontal:CParent.TransitionHorizontal.fromRight)
}
func share()
{
viewPlot.startLoading()
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.shareTexture()
}
}
func help()
{
let modelHelp:MHelpLinearEquationsPlot = MHelpLinearEquationsPlot()
let controllerHelp:CHelp = CHelp(model:modelHelp)
parentController.push(
controller:controllerHelp,
vertical:CParent.TransitionVertical.fromTop,
background:false)
}
func updateZoom(zoom:Double)
{
let increase:Double = model.updateZoom(zoom:zoom)
DispatchQueue.main.async
{ [weak self] in
self?.viewPlot.increaseAndRefresh(delta:increase)
}
}
}
| mit | 600463682b0ab76d75f8b6961e3e0169 | 28.170213 | 117 | 0.580598 | 5.67937 | false | false | false | false |
achappell/tacky-tower | TackyTower/TackyTower/GameScene.swift | 1 | 2675 | //
// GameScene.swift
// TackyTower
//
// Created by Amanda Chappell on 9/4/14.
// Copyright (c) 2014 AmplifiedProjects. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, MenuDelegate {
var menuLabelNode : SKLabelNode
var menuNode : MenuNode
var draggingNode : RoomNode?
var grid : Grid!
required init?(coder aDecoder: NSCoder) {
self.menuLabelNode = SKLabelNode(text: "Menu")
self.menuNode = MenuNode(openMenuAction: SKAction.moveByX(256, y: 0, duration: 0.5), closeMenuAction: SKAction.moveByX(-256, y: 0, duration: 0.5))
super.init(coder: aDecoder)
}
override func didMoveToView(view: SKView) {
self.menuNode.centerRect = CGRectMake(12.0/28.0,12.0/28.0,4.0/28.0,4.0/28.0)
self.menuNode.xScale = 4
self.menuNode.yScale = 4
self.menuNode.position = CGPoint(x: -128.0, y: 200.0)
self.menuNode.userInteractionEnabled = true
self.addChild(self.menuNode)
self.menuNode.delegate = self
self.menuLabelNode.position = CGPoint(x: 20, y: 30)
self.menuLabelNode.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Left
self.addChild(menuLabelNode)
self.grid = Grid(rows: 40, columns: 60, size: self.frame.size)
}
override func mouseDown(theEvent: NSEvent) {
let location = theEvent.locationInNode(self)
if CGRectContainsPoint(self.menuLabelNode.frame, location) {
self.menuNode.toggleMenu()
}
if let aDraggingNode = self.draggingNode {
self.draggingNode = nil
}
super.mouseDown(theEvent)
}
override func mouseMoved(theEvent: NSEvent) {
if let aDraggingNode = self.draggingNode {
let position = theEvent.locationInNode(self)
let topLeftPoint = CGPoint(x: position.x - aDraggingNode.size.width / 2.0, y: position.y - aDraggingNode.size.height)
let newPosition = self.grid.snapToGridPositionForPosition(topLeftPoint)
aDraggingNode.position = CGPoint(x: newPosition.x + aDraggingNode.size.width / 2.0, y: newPosition.y + aDraggingNode.size.height)
}
super.mouseMoved(theEvent)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
// MARK: MenuDelegate
func menu(menu: MenuNode, didChooseItem item: RoomNode) {
self.draggingNode = item
item.xScale = 4
item.yScale = 4
item.zPosition = 1000
self.addChild(item)
}
}
| mit | 1d17887ef4d07e15af4865e5f48cdd49 | 32.024691 | 154 | 0.625794 | 4.102761 | false | false | false | false |
dynamsoftsamples/swift-barcode-reader | command-line-tool/DBRConsole/main.swift | 2 | 1216 | //
// main.swift
//
// Created by Ling Xiao on 15/8/19.
//
import Foundation
var file: String = "/Applications/Dynamsoft/Barcode Reader 3.0 Trial/Images/AllSupportedBarcodeTypes.tif" // barcode file
//let namePtr = strdup(filePath.bridgeToObjectiveC().UTF8String)
var filePtr = strdup(file.cStringUsingEncoding(NSUTF8StringEncoding)!)
var fileName: UnsafeMutablePointer<CChar> = UnsafeMutablePointer(filePtr)
var result : pBarcodeResultArray = dbr_decodeBarcodeFile(fileName)
free(filePtr)
println("Total barcode: \(String(result.move().iBarcodeCount))\n.......")
var count = result.move().iBarcodeCount
var pBarcodeResult: pBarcodeResult = nil
var barcodeIndex = 1
// print barcode recognition results
for i in 0..<Int(count) {
pBarcodeResult = result.move().ppBarcodes.advancedBy(i).move()
println("Barcode: \(barcodeIndex++)")
println("Page: \(String(pBarcodeResult.move().iPageNum))")
var lFormat: __int64 = pBarcodeResult.move().llFormat
var format = String.fromCString(GetFormatStr(lFormat))
println("Type: \(format!)")
println("Value: \(String.fromCString(pBarcodeResult.move().pBarcodeData)!)")
println(".......")
}
// free C memory
dbr_release_memory(result)
| mit | 6520988f2e538aca3c342a7fb315a5a2 | 30.179487 | 121 | 0.726974 | 3.640719 | false | false | false | false |
lw8516649/DouYuImitation | DouYuTV/DouYuTV/Classes/Home/Controller/RecommendedViewController.swift | 1 | 3067 | //
// RecommendedViewController.swift
// DouYuTV
//
// Created by LW on 16/12/12.
// Copyright © 2016年 LW. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10;
private let kItemW = (kScreenW - 3 * kItemMargin) / 2;
private let KItemH = kItemW * 3 / 4;
private let kHeaderViewH :CGFloat = 50;
private let kNormalCellID = "kNormalCellID";
private let kHeaderViewCellID = "kHeaderViewCellID";
class RecommendedViewController: UIViewController {
fileprivate lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout();
layout.itemSize = CGSize(width: kItemW, height: KItemH);
layout.minimumLineSpacing = 0;
layout.minimumInteritemSpacing = kItemMargin ;
layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin);
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH);
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout);
collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth];
collectionView.backgroundColor = UIColor.white;
collectionView.dataSource = self;
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewCellID)
return collectionView;
}()
//系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.purple;
setUI();
}
}
extension RecommendedViewController {
fileprivate func setUI() {
view.addSubview(collectionView);
}
}
extension RecommendedViewController :UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 12 ;
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 8;
}
return 4 ;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath);
return cell;
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewCellID, for: indexPath);
return headerView;
}
}
| mit | 692cf9db82bd708a182be732dbc1880a | 26.495495 | 190 | 0.655636 | 6.043564 | false | false | false | false |
MattKiazyk/Operations | framework/Operations/Operations/BlockOperation.swift | 1 | 1199 | //
// BlockOperation.swift
// Operations
//
// Created by Daniel Thorpe on 18/07/2015.
// Copyright © 2015 Daniel Thorpe. All rights reserved.
//
import Foundation
public class BlockOperation: Operation {
public typealias ContinuationBlockType = Void -> Void
public typealias BlockType = (ContinuationBlockType) -> Void
private let block: BlockType?
/**
Designated initializer.
- parameter block: The closure to run when the operation executes.
If this block is nil, the operation will immediately finish.
*/
public init(block: BlockType? = .None) {
self.block = block
super.init()
}
/**
Convenience initializer.
- paramter block: a dispatch block which is run on the main thread.
*/
public convenience init(mainQueueBlock: dispatch_block_t) {
self.init(block: { continuation in
dispatch_async(Queue.Main.queue) {
mainQueueBlock()
continuation()
}
})
}
public override func execute() {
if let block = block {
block { self.finish() }
}
else {
finish()
}
}
}
| mit | 7afc1eb37d0da0288a550f8cc64a159e | 20.781818 | 71 | 0.593489 | 4.735178 | false | false | false | false |
mperovic/my41 | my41/Classes/DebugerMenu.swift | 1 | 4127 | //
// DebugerMenu.swift
// my41
//
// Created by Miroslav Perovic on 11/15/14.
// Copyright (c) 2014 iPera. All rights reserved.
//
import Foundation
import Cocoa
class DebugMenuViewController: NSViewController {
var registersView: SelectedDebugView?
var memoryView: SelectedDebugView?
var debugContainerViewController: DebugContainerViewController?
@IBOutlet weak var menuView: NSView!
override func viewWillAppear() {
self.view.layer = CALayer()
self.view.layer?.backgroundColor = NSColor(calibratedRed: 0.4824, green: 0.6667, blue: 0.2941, alpha: 1.0).cgColor
self.view.wantsLayer = true
registersView = SelectedDebugView(frame: CGRect(x: 0, y: self.menuView.frame.size.height - 35, width: 184, height: 24))
registersView?.text = "Registers"
registersView?.selected = true
self.menuView.addSubview(registersView!)
memoryView = SelectedDebugView(frame: CGRect(x: 0, y: self.menuView.frame.size.height - 59, width: 184, height: 24))
memoryView?.text = "Memory"
memoryView?.selected = false
self.menuView.addSubview(memoryView!)
}
@IBAction func registersAction(sender: AnyObject) {
registersView!.selected = true
memoryView!.selected = false
registersView!.setNeedsDisplay(registersView!.bounds)
memoryView!.setNeedsDisplay(memoryView!.bounds)
debugContainerViewController?.loadCPUViewController()
}
@IBAction func memoryAction(sender: AnyObject) {
registersView!.selected = false
memoryView!.selected = true
registersView!.setNeedsDisplay(registersView!.bounds)
memoryView!.setNeedsDisplay(memoryView!.bounds)
debugContainerViewController?.loadMemoryViewController()
}
}
class DebugerMenuView: NSView {
}
class SelectedDebugView: NSView {
var text: NSString?
var selected: Bool?
override func draw(_ dirtyRect: NSRect) {
//// Color Declarations
let backColor = NSColor(calibratedRed: 1, green: 1, blue: 1, alpha: 0.95)
let textColor = NSColor(calibratedRed: 0.147, green: 0.222, blue: 0.162, alpha: 1)
let font = NSFont(name: "Helvetica Bold", size: 14.0)
let textRect: NSRect = NSMakeRect(5, 3, 125, 18)
let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = .left
if selected! {
//// Rectangle Drawing
let rectangleCornerRadius: CGFloat = 5
let rectangleRect = NSMakeRect(0, 0, 184, 24)
let rectangleInnerRect = NSInsetRect(rectangleRect, rectangleCornerRadius, rectangleCornerRadius)
let rectanglePath = NSBezierPath()
rectanglePath.move(to: NSMakePoint(NSMinX(rectangleRect), NSMinY(rectangleRect)))
rectanglePath.appendArc(
withCenter: NSMakePoint(NSMaxX(rectangleInnerRect), NSMinY(rectangleInnerRect)),
radius: rectangleCornerRadius,
startAngle: 270,
endAngle: 360
)
rectanglePath.appendArc(
withCenter: NSMakePoint(NSMaxX(rectangleInnerRect), NSMaxY(rectangleInnerRect)),
radius: rectangleCornerRadius,
startAngle: 0,
endAngle: 90
)
rectanglePath.line(to: NSMakePoint(NSMinX(rectangleRect), NSMaxY(rectangleRect)))
rectanglePath.close()
backColor.setFill()
rectanglePath.fill()
if let actualFont = font {
let textFontAttributes: NSDictionary = [
NSAttributedString.Key.font: actualFont,
NSAttributedString.Key.foregroundColor: textColor,
NSAttributedString.Key.paragraphStyle: textStyle
]
text?.draw(in: NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes as? [String : AnyObject])
}
} else {
if let actualFont = font {
let textFontAttributes: NSDictionary = [
NSAttributedString.Key.font: actualFont,
NSAttributedString.Key.foregroundColor: backColor,
NSAttributedString.Key.paragraphStyle: textStyle
]
text?.draw(in: NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes as? [String : AnyObject])
}
}
}
}
//MARK: -
class DebugMenuLabelView: NSView {
override func awakeFromNib() {
let viewLayer: CALayer = CALayer()
viewLayer.backgroundColor = CGColor(red: 0.5412, green: 0.7098, blue: 0.3804, alpha: 1.0)
self.wantsLayer = true
self.layer = viewLayer
}
}
| bsd-3-clause | bc30f597a000a361ac9786b2f5b04593 | 30.746154 | 121 | 0.737582 | 3.824838 | false | false | false | false |
matteobruni/OAuthSwift | Sources/OAuthSwiftError.swift | 1 | 5046 | //
// OAuthSwiftError.swift
// OAuthSwift
//
// Created by phimage on 02/10/16.
// Copyright © 2016 Dongri Jin. All rights reserved.
//
import Foundation
// MARK: - OAuthSwift errors
public enum OAuthSwiftError: Error {
// Configuration problem with oauth provider.
case configurationError(message: String)
// The provided token is expired, retrieve new token by using the refresh token
case tokenExpired(error: Error?)
// State missing from request (you can set allowMissingStateCheck = true to ignore)
case missingState
// Returned state value is wrong
case stateNotEqual(state: String, responseState: String)
// Error from server
case serverError(message: String)
// Failed to create URL \(urlString) not convertible to URL, please encode
case encodingError(urlString: String)
case authorizationPending
// Failed to create request with \(urlString)
case requestCreation(message: String)
// Authentification failed. No token
case missingToken
// Please retain OAuthSwift object or handle
case retain
// Request error
case requestError(error: Error, request: URLRequest)
// Request cancelled
case cancelled
public static let Domain = "OAuthSwiftError"
public static let ResponseDataKey = "OAuthSwiftError.response.data"
public static let ResponseKey = "OAuthSwiftError.response"
fileprivate enum Code: Int {
case configurationError = -1
case tokenExpired = -2
case missingState = -3
case stateNotEqual = -4
case serverError = -5
case encodingError = -6
case authorizationPending = -7
case requestCreation = -8
case missingToken = -9
case retain = -10
case requestError = -11
case cancelled = -12
}
fileprivate var code: Code {
switch self {
case .configurationError: return Code.configurationError
case .tokenExpired: return Code.tokenExpired
case .missingState: return Code.missingState
case .stateNotEqual: return Code.stateNotEqual
case .serverError: return Code.serverError
case .encodingError: return Code.encodingError
case .authorizationPending: return Code.authorizationPending
case .requestCreation: return Code.requestCreation
case .missingToken: return Code.missingToken
case .retain: return Code.retain
case .requestError: return Code.requestError
case .cancelled : return Code.cancelled
}
}
public var underlyingError: Error? {
switch self {
case .tokenExpired(let e): return e
case .requestError(let e, _): return e
default: return nil
}
}
public var underlyingMessage: String? {
switch self {
case .serverError(let m): return m
case .configurationError(let m): return m
case .requestCreation(let m): return m
default: return nil
}
}
}
extension OAuthSwiftError: CustomStringConvertible {
public var description: String {
switch self {
case .configurationError(let m): return "configurationError[\(m)]"
case .tokenExpired(let e): return "tokenExpired[\(e)]"
case .missingState: return "missingState"
case .stateNotEqual(let s, let e): return "stateNotEqual[\(s)<>\(e)]"
case .serverError(let m): return "serverError[\(m)]"
case .encodingError(let urlString): return "encodingError[\(urlString)]"
case .authorizationPending: return "authorizationPending"
case .requestCreation(let m): return "requestCreation[\(m)]"
case .missingToken: return "missingToken"
case .retain: return "retain"
case .requestError(let e, _): return "requestError[\(e)]"
case .cancelled : return "cancelled"
}
}
}
extension OAuthSwift {
static func retainError(_ failureHandler: FailureHandler?) {
#if !OAUTH_NO_RETAIN_ERROR
failureHandler?(OAuthSwiftError.retain)
#endif
}
}
// MARK NSError
extension OAuthSwiftError: CustomNSError {
public static var errorDomain: String { return OAuthSwiftError.Domain }
public var errorCode: Int { return self.code.rawValue }
/// The user-info dictionary.
public var errorUserInfo: [String : Any] {
switch self {
case .configurationError(let m): return ["message": m]
case .serverError(let m): return ["message": m]
case .requestCreation(let m): return ["message": m]
case .tokenExpired(let e): return ["error": e as Any]
case .requestError(let e, let request): return ["error": e, "request": request]
case .encodingError(let urlString): return ["url": urlString]
case .stateNotEqual(let s, let e): return ["state": s, "expected": e]
default: return [:]
}
}
public var _code: Int {
return self.code.rawValue
}
public var _domain: String {
return OAuthSwiftError.Domain
}
}
| mit | 24ddc9e6512c951e3968e14ba83903df | 31.973856 | 87 | 0.65669 | 4.921951 | false | true | false | false |
erinshihshih/ETripTogether | Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQUIView+IQKeyboardToolbar.swift | 3 | 51257 | //
// IQUIView+IQKeyboardToolbar.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
private var kIQShouldHidePlaceholderText = "kIQShouldHidePlaceholderText"
private var kIQPlaceholderText = "kIQPlaceholderText"
private var kIQTitleInvocationTarget = "kIQTitleInvocationTarget"
private var kIQTitleInvocationSelector = "kIQTitleInvocationSelector"
private var kIQPreviousInvocationTarget = "kIQPreviousInvocationTarget"
private var kIQPreviousInvocationSelector = "kIQPreviousInvocationSelector"
private var kIQNextInvocationTarget = "kIQNextInvocationTarget"
private var kIQNextInvocationSelector = "kIQNextInvocationSelector"
private var kIQDoneInvocationTarget = "kIQDoneInvocationTarget"
private var kIQDoneInvocationSelector = "kIQDoneInvocationSelector"
/**
UIView category methods to add IQToolbar on UIKeyboard.
*/
public extension UIView {
///-------------------------
/// MARK: Title and Distance
///-------------------------
/**
If `shouldHidePlaceholderText` is YES, then title will not be added to the toolbar. Default to NO.
*/
public var shouldHidePlaceholderText: Bool {
get {
let aValue: AnyObject? = objc_getAssociatedObject(self, &kIQShouldHidePlaceholderText)
if let unwrapedValue = aValue as? Bool {
return unwrapedValue
} else {
return false
}
}
set(newValue) {
objc_setAssociatedObject(self, &kIQShouldHidePlaceholderText, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if let toolbar = self.inputAccessoryView as? IQToolbar {
if self.respondsToSelector(Selector("placeholder")) {
toolbar.title = self.drawingPlaceholderText
}
}
}
}
/**
`placeholderText` to override default `placeholder` text when drawing text on toolbar.
*/
public var placeholderText: String? {
get {
let aValue = objc_getAssociatedObject(self, &kIQPlaceholderText) as? String
return aValue
}
set(newValue) {
objc_setAssociatedObject(self, &kIQPlaceholderText, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if let toolbar = self.inputAccessoryView as? IQToolbar {
if self.respondsToSelector(Selector("placeholder")) {
toolbar.title = self.drawingPlaceholderText
}
}
}
}
/**
`drawingPlaceholderText` will be actual text used to draw on toolbar. This would either `placeholder` or `placeholderText`.
*/
public var drawingPlaceholderText: String? {
if (self.shouldHidePlaceholderText)
{
return nil
}
else if (self.placeholderText?.isEmpty == false) {
return self.placeholderText
}
else if self.respondsToSelector(Selector("placeholder")) {
if let textField = self as? UITextField {
return textField.placeholder
} else if let textView = self as? IQTextView {
return textView.placeholder
} else {
return nil
}
}
else {
return nil
}
}
/**
Optional target & action to behave toolbar title button as clickable button
@param target Target object.
@param action Target Selector.
*/
public func setTitleTarget(target: AnyObject?, action: Selector?) {
titleInvocation = (target, action)
}
/**
Customized Invocation to be called on title button action. titleInvocation is internally created using setTitleTarget:action: method.
*/
public var titleInvocation : (target: AnyObject?, action: Selector?) {
get {
let target: AnyObject? = objc_getAssociatedObject(self, &kIQTitleInvocationTarget)
var action : Selector?
if let selectorString = objc_getAssociatedObject(self, &kIQTitleInvocationSelector) as? String {
action = NSSelectorFromString(selectorString)
}
return (target: target, action: action)
}
set(newValue) {
objc_setAssociatedObject(self, &kIQTitleInvocationTarget, newValue.target, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if let unwrappedSelector = newValue.action {
objc_setAssociatedObject(self, &kIQTitleInvocationSelector, NSStringFromSelector(unwrappedSelector), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
} else {
objc_setAssociatedObject(self, &kIQTitleInvocationSelector, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
///-----------------------------------------
/// TODO: Customised Invocation Registration
///-----------------------------------------
/**
Additional target & action to do get callback action. Note that setting custom `previous` selector doesn't affect native `previous` functionality, this is just used to notifiy user to do additional work according to need.
@param target Target object.
@param action Target Selector.
*/
public func setCustomPreviousTarget(target: AnyObject?, action: Selector?) {
previousInvocation = (target, action)
}
/**
Additional target & action to do get callback action. Note that setting custom `next` selector doesn't affect native `next` functionality, this is just used to notifiy user to do additional work according to need.
@param target Target object.
@param action Target Selector.
*/
public func setCustomNextTarget(target: AnyObject?, action: Selector?) {
nextInvocation = (target, action)
}
/**
Additional target & action to do get callback action. Note that setting custom `done` selector doesn't affect native `done` functionality, this is just used to notifiy user to do additional work according to need.
@param target Target object.
@param action Target Selector.
*/
public func setCustomDoneTarget(target: AnyObject?, action: Selector?) {
doneInvocation = (target, action)
}
/**
Customized Invocation to be called on previous arrow action. previousInvocation is internally created using setCustomPreviousTarget:action: method.
*/
public var previousInvocation : (target: AnyObject?, action: Selector?) {
get {
let target: AnyObject? = objc_getAssociatedObject(self, &kIQPreviousInvocationTarget)
var action : Selector?
if let selectorString = objc_getAssociatedObject(self, &kIQPreviousInvocationSelector) as? String {
action = NSSelectorFromString(selectorString)
}
return (target: target, action: action)
}
set(newValue) {
objc_setAssociatedObject(self, &kIQPreviousInvocationTarget, newValue.target, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if let unwrappedSelector = newValue.action {
objc_setAssociatedObject(self, &kIQPreviousInvocationSelector, NSStringFromSelector(unwrappedSelector), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
} else {
objc_setAssociatedObject(self, &kIQPreviousInvocationSelector, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
/**
Customized Invocation to be called on next arrow action. nextInvocation is internally created using setCustomNextTarget:action: method.
*/
public var nextInvocation : (target: AnyObject?, action: Selector?) {
get {
let target: AnyObject? = objc_getAssociatedObject(self, &kIQNextInvocationTarget)
var action : Selector?
if let selectorString = objc_getAssociatedObject(self, &kIQNextInvocationSelector) as? String {
action = NSSelectorFromString(selectorString)
}
return (target: target, action: action)
}
set(newValue) {
objc_setAssociatedObject(self, &kIQNextInvocationTarget, newValue.target, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if let unwrappedSelector = newValue.action {
objc_setAssociatedObject(self, &kIQNextInvocationSelector, NSStringFromSelector(unwrappedSelector), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
} else {
objc_setAssociatedObject(self, &kIQNextInvocationSelector, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
/**
Customized Invocation to be called on done action. doneInvocation is internally created using setCustomDoneTarget:action: method.
*/
public var doneInvocation : (target: AnyObject?, action: Selector?) {
get {
let target: AnyObject? = objc_getAssociatedObject(self, &kIQDoneInvocationTarget)
var action : Selector?
if let selectorString = objc_getAssociatedObject(self, &kIQDoneInvocationSelector) as? String {
action = NSSelectorFromString(selectorString)
}
return (target: target, action: action)
}
set(newValue) {
objc_setAssociatedObject(self, &kIQDoneInvocationTarget, newValue.target, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if let unwrappedSelector = newValue.action {
objc_setAssociatedObject(self, &kIQDoneInvocationSelector, NSStringFromSelector(unwrappedSelector), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
} else {
objc_setAssociatedObject(self, &kIQDoneInvocationSelector, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
///---------------------
/// MARK: Private helper
///---------------------
private static func flexibleBarButtonItem () -> IQBarButtonItem {
struct Static {
static let nilButton = IQBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
}
return Static.nilButton
}
///------------
/// MARK: Done
///------------
/**
Helper function to add Done button on keyboard.
@param target Target object for selector.
@param action Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
*/
public func addDoneOnKeyboardWithTarget(target : AnyObject?, action : Selector) {
addDoneOnKeyboardWithTarget(target, action: action, titleText: nil)
}
/**
Helper function to add Done button on keyboard.
@param target Target object for selector.
@param action Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addDoneOnKeyboardWithTarget (target : AnyObject?, action : Selector, titleText: String?) {
//If can't set InputAccessoryView. Then return
if self.respondsToSelector(Selector("setInputAccessoryView:")) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = IQToolbar()
var items : [UIBarButtonItem] = []
//Title button
let title = IQTitleBarButtonItem(title: shouldHidePlaceholderText == true ? nil : titleText)
items.append(title)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Done button
let doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: action)
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
toolbar.toolbarTitleInvocation = self.titleInvocation
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
}
}
}
/**
Helper function to add Done button on keyboard.
@param target Target object for selector.
@param action Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
*/
public func addDoneOnKeyboardWithTarget (target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingPlaceholderText
}
addDoneOnKeyboardWithTarget(target, action: action, titleText: title)
}
///------------
/// MARK: Right
///------------
/**
Helper function to add Right button on keyboard.
@param image Image icon to use as right button.
@param target Target object for selector.
@param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addRightButtonOnKeyboardWithImage (image : UIImage, target : AnyObject?, action : Selector, titleText: String?) {
//If can't set InputAccessoryView. Then return
if self.respondsToSelector(Selector("setInputAccessoryView:")) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = IQToolbar()
toolbar.doneImage = image
var items : [UIBarButtonItem] = []
//Title button
let title = IQTitleBarButtonItem(title: shouldHidePlaceholderText == true ? nil : titleText)
items.append(title)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Right button
let doneButton = IQBarButtonItem(image: image, style: UIBarButtonItemStyle.Done, target: target, action: action)
doneButton.accessibilityLabel = "Toolbar Done Button"
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
toolbar.toolbarTitleInvocation = self.titleInvocation
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
}
}
}
/**
Helper function to add Right button on keyboard.
@param image Image icon to use as right button.
@param target Target object for selector.
@param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
*/
public func addRightButtonOnKeyboardWithImage (image : UIImage, target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingPlaceholderText
}
addRightButtonOnKeyboardWithImage(image, target: target, action: action, titleText: title)
}
/**
Helper function to add Right button on keyboard.
@param text Title for rightBarButtonItem, usually 'Done'.
@param target Target object for selector.
@param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
*/
public func addRightButtonOnKeyboardWithText (text : String, target : AnyObject?, action : Selector) {
addRightButtonOnKeyboardWithText(text, target: target, action: action, titleText: nil)
}
/**
Helper function to add Right button on keyboard.
@param text Title for rightBarButtonItem, usually 'Done'.
@param target Target object for selector.
@param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addRightButtonOnKeyboardWithText (text : String, target : AnyObject?, action : Selector, titleText: String?) {
//If can't set InputAccessoryView. Then return
if self.respondsToSelector(Selector("setInputAccessoryView:")) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = IQToolbar()
toolbar.doneTitle = text
var items : [UIBarButtonItem] = []
//Title button
let title = IQTitleBarButtonItem(title: shouldHidePlaceholderText == true ? nil : titleText)
items.append(title)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Right button
let doneButton = IQBarButtonItem(title: text, style: UIBarButtonItemStyle.Done, target: target, action: action)
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
toolbar.toolbarTitleInvocation = self.titleInvocation
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
}
}
}
/**
Helper function to add Right button on keyboard.
@param text Title for rightBarButtonItem, usually 'Done'.
@param target Target object for selector.
@param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
*/
public func addRightButtonOnKeyboardWithText (text : String, target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingPlaceholderText
}
addRightButtonOnKeyboardWithText(text, target: target, action: action, titleText: title)
}
///------------------
/// MARK: Cancel/Done
///------------------
/**
Helper function to add Cancel and Done button on keyboard.
@param target Target object for selector.
@param cancelAction Cancel button action name. Usually 'cancelAction:(IQBarButtonItem*)item'.
@param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
*/
public func addCancelDoneOnKeyboardWithTarget (target : AnyObject?, cancelAction : Selector, doneAction : Selector) {
addCancelDoneOnKeyboardWithTarget(target, cancelAction: cancelAction, doneAction: doneAction, titleText: nil)
}
/**
Helper function to add Cancel and Done button on keyboard.
@param target Target object for selector.
@param cancelAction Cancel button action name. Usually 'cancelAction:(IQBarButtonItem*)item'.
@param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addCancelDoneOnKeyboardWithTarget (target : AnyObject?, cancelAction : Selector, doneAction : Selector, titleText: String?) {
//If can't set InputAccessoryView. Then return
if self.respondsToSelector(Selector("setInputAccessoryView:")) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = IQToolbar()
var items : [UIBarButtonItem] = []
//Cancel button
let cancelButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: target, action: cancelAction)
items.append(cancelButton)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Title
let title = IQTitleBarButtonItem(title: shouldHidePlaceholderText == true ? nil : titleText)
items.append(title)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Done button
let doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: doneAction)
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
toolbar.toolbarTitleInvocation = self.titleInvocation
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
}
}
}
/**
Helper function to add Cancel and Done button on keyboard.
@param target Target object for selector.
@param cancelAction Cancel button action name. Usually 'cancelAction:(IQBarButtonItem*)item'.
@param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
*/
public func addCancelDoneOnKeyboardWithTarget (target : AnyObject?, cancelAction : Selector, doneAction : Selector, shouldShowPlaceholder: Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingPlaceholderText
}
addCancelDoneOnKeyboardWithTarget(target, cancelAction: cancelAction, doneAction: doneAction, titleText: title)
}
///-----------------
/// MARK: Right/Left
///-----------------
/**
Helper function to add Left and Right button on keyboard.
@param target Target object for selector.
@param leftButtonTitle Title for leftBarButtonItem, usually 'Cancel'.
@param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
@param leftButtonAction Left button action name. Usually 'cancelAction:(IQBarButtonItem*)item'.
@param rightButtonAction Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
*/
public func addRightLeftOnKeyboardWithTarget( target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector) {
addRightLeftOnKeyboardWithTarget(target, leftButtonTitle: leftButtonTitle, rightButtonTitle: rightButtonTitle, rightButtonAction: rightButtonAction, leftButtonAction: leftButtonAction, titleText: nil)
}
/**
Helper function to add Left and Right button on keyboard.
@param target Target object for selector.
@param leftButtonTitle Title for leftBarButtonItem, usually 'Cancel'.
@param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
@param leftButtonAction Left button action name. Usually 'cancelAction:(IQBarButtonItem*)item'.
@param rightButtonAction Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addRightLeftOnKeyboardWithTarget( target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector, titleText: String?) {
//If can't set InputAccessoryView. Then return
if self.respondsToSelector(Selector("setInputAccessoryView:")) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = IQToolbar()
toolbar.doneTitle = rightButtonTitle
var items : [UIBarButtonItem] = []
//Left button
let cancelButton = IQBarButtonItem(title: leftButtonTitle, style: UIBarButtonItemStyle.Plain, target: target, action: leftButtonAction)
items.append(cancelButton)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Title button
let title = IQTitleBarButtonItem(title: shouldHidePlaceholderText == true ? nil : titleText)
items.append(title)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Right button
let doneButton = IQBarButtonItem(title: rightButtonTitle, style: UIBarButtonItemStyle.Done, target: target, action: rightButtonAction)
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
toolbar.toolbarTitleInvocation = self.titleInvocation
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
}
}
}
/**
Helper function to add Left and Right button on keyboard.
@param target Target object for selector.
@param leftButtonTitle Title for leftBarButtonItem, usually 'Cancel'.
@param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
@param leftButtonAction Left button action name. Usually 'cancelAction:(IQBarButtonItem*)item'.
@param rightButtonAction Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
*/
public func addRightLeftOnKeyboardWithTarget( target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector, shouldShowPlaceholder: Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingPlaceholderText
}
addRightLeftOnKeyboardWithTarget(target, leftButtonTitle: leftButtonTitle, rightButtonTitle: rightButtonTitle, rightButtonAction: rightButtonAction, leftButtonAction: leftButtonAction, titleText: title)
}
///-------------------------
/// MARK: Previous/Next/Done
///-------------------------
/**
Helper function to add ArrowNextPrevious and Done button on keyboard.
@param target Target object for selector.
@param previousAction Previous button action name. Usually 'previousAction:(id)item'.
@param nextAction Next button action name. Usually 'nextAction:(id)item'.
@param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
*/
public func addPreviousNextDoneOnKeyboardWithTarget ( target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector) {
addPreviousNextDoneOnKeyboardWithTarget(target, previousAction: previousAction, nextAction: nextAction, doneAction: doneAction, titleText: nil)
}
/**
Helper function to add ArrowNextPrevious and Done button on keyboard.
@param target Target object for selector.
@param previousAction Previous button action name. Usually 'previousAction:(id)item'.
@param nextAction Next button action name. Usually 'nextAction:(id)item'.
@param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addPreviousNextDoneOnKeyboardWithTarget ( target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector, titleText: String?) {
//If can't set InputAccessoryView. Then return
if self.respondsToSelector(Selector("setInputAccessoryView:")) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = IQToolbar()
var items : [UIBarButtonItem] = []
let prev : IQBarButtonItem
let next : IQBarButtonItem
// Get the top level "bundle" which may actually be the framework
var bundle = NSBundle(forClass: IQKeyboardManager.self)
if let resourcePath = bundle.pathForResource("IQKeyboardManager", ofType: "bundle") {
if let resourcesBundle = NSBundle(path: resourcePath) {
bundle = resourcesBundle
}
}
var imageLeftArrow = UIImage(named: "IQButtonBarArrowLeft", inBundle: bundle, compatibleWithTraitCollection: nil)
var imageRightArrow = UIImage(named: "IQButtonBarArrowRight", inBundle: bundle, compatibleWithTraitCollection: nil)
//Support for RTL languages like Arabic, Persia etc... (Bug ID: #448)
if #available(iOS 9.0, *) {
imageLeftArrow = imageLeftArrow?.imageFlippedForRightToLeftLayoutDirection()
imageRightArrow = imageRightArrow?.imageFlippedForRightToLeftLayoutDirection()
}
prev = IQBarButtonItem(image: imageLeftArrow, style: UIBarButtonItemStyle.Plain, target: target, action: previousAction)
prev.accessibilityLabel = "Toolbar Previous Button"
next = IQBarButtonItem(image: imageRightArrow, style: UIBarButtonItemStyle.Plain, target: target, action: nextAction)
next.accessibilityLabel = "Toolbar Next Button"
//Previous button
items.append(prev)
//Fixed space
let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
fixed.width = 23
items.append(fixed)
//Next button
items.append(next)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Title button
let title = IQTitleBarButtonItem(title: shouldHidePlaceholderText == true ? nil : titleText)
items.append(title)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Done button
let doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: doneAction)
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
toolbar.toolbarTitleInvocation = self.titleInvocation
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
}
}
}
/**
Helper function to add ArrowNextPrevious and Done button on keyboard.
@param target Target object for selector.
@param previousAction Previous button action name. Usually 'previousAction:(id)item'.
@param nextAction Next button action name. Usually 'nextAction:(id)item'.
@param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
*/
public func addPreviousNextDoneOnKeyboardWithTarget ( target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector, shouldShowPlaceholder: Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingPlaceholderText
}
addPreviousNextDoneOnKeyboardWithTarget(target, previousAction: previousAction, nextAction: nextAction, doneAction: doneAction, titleText: title)
}
///--------------------------
/// MARK: Previous/Next/Right
///--------------------------
/**
Helper function to add ArrowNextPrevious and Right button on keyboard.
@param target Target object for selector.
@param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
@param previousAction Previous button action name. Usually 'previousAction:(id)item'.
@param nextAction Next button action name. Usually 'nextAction:(id)item'.
@param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addPreviousNextRightOnKeyboardWithTarget( target : AnyObject?, rightButtonImage : UIImage, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, titleText : String?) {
//If can't set InputAccessoryView. Then return
if self.respondsToSelector(Selector("setInputAccessoryView:")) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = IQToolbar()
toolbar.doneImage = rightButtonImage
var items : [UIBarButtonItem] = []
let prev : IQBarButtonItem
let next : IQBarButtonItem
// Get the top level "bundle" which may actually be the framework
var bundle = NSBundle(forClass: IQKeyboardManager.self)
if let resourcePath = bundle.pathForResource("IQKeyboardManager", ofType: "bundle") {
if let resourcesBundle = NSBundle(path: resourcePath) {
bundle = resourcesBundle
}
}
var imageLeftArrow = UIImage(named: "IQButtonBarArrowLeft", inBundle: bundle, compatibleWithTraitCollection: nil)
var imageRightArrow = UIImage(named: "IQButtonBarArrowRight", inBundle: bundle, compatibleWithTraitCollection: nil)
//Support for RTL languages like Arabic, Persia etc... (Bug ID: #448)
if #available(iOS 9.0, *) {
imageLeftArrow = imageLeftArrow?.imageFlippedForRightToLeftLayoutDirection()
imageRightArrow = imageRightArrow?.imageFlippedForRightToLeftLayoutDirection()
}
prev = IQBarButtonItem(image: imageLeftArrow, style: UIBarButtonItemStyle.Plain, target: target, action: previousAction)
prev.accessibilityLabel = "Toolbar Previous Button"
next = IQBarButtonItem(image: imageRightArrow, style: UIBarButtonItemStyle.Plain, target: target, action: nextAction)
next.accessibilityLabel = "Toolbar Next Button"
//Previous button
items.append(prev)
//Fixed space
let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
fixed.width = 23
items.append(fixed)
//Next button
items.append(next)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Title button
let title = IQTitleBarButtonItem(title: shouldHidePlaceholderText == true ? nil : titleText)
items.append(title)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Right button
let doneButton = IQBarButtonItem(image: rightButtonImage, style: UIBarButtonItemStyle.Done, target: target, action: rightButtonAction)
doneButton.accessibilityLabel = "Toolbar Done Button"
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
toolbar.toolbarTitleInvocation = self.titleInvocation
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
}
}
}
// /**
// Helper function to add ArrowNextPrevious and Right button on keyboard.
//
// @param target Target object for selector.
// @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
// @param previousAction Previous button action name. Usually 'previousAction:(id)item'.
// @param nextAction Next button action name. Usually 'nextAction:(id)item'.
// @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'.
// @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
// */
public func addPreviousNextRightOnKeyboardWithTarget( target : AnyObject?, rightButtonImage : UIImage, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, shouldShowPlaceholder : Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingPlaceholderText
}
addPreviousNextRightOnKeyboardWithTarget(target, rightButtonImage: rightButtonImage, previousAction: previousAction, nextAction: nextAction, rightButtonAction: rightButtonAction, titleText: title)
}
/**
Helper function to add ArrowNextPrevious and Right button on keyboard.
@param target Target object for selector.
@param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
@param previousAction Previous button action name. Usually 'previousAction:(id)item'.
@param nextAction Next button action name. Usually 'nextAction:(id)item'.
@param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'.
*/
public func addPreviousNextRightOnKeyboardWithTarget( target : AnyObject?, rightButtonTitle : String, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector) {
addPreviousNextRightOnKeyboardWithTarget(target, rightButtonTitle: rightButtonTitle, previousAction: previousAction, nextAction: nextAction, rightButtonAction: rightButtonAction, titleText: nil)
}
/**
Helper function to add ArrowNextPrevious and Right button on keyboard.
@param target Target object for selector.
@param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
@param previousAction Previous button action name. Usually 'previousAction:(id)item'.
@param nextAction Next button action name. Usually 'nextAction:(id)item'.
@param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addPreviousNextRightOnKeyboardWithTarget( target : AnyObject?, rightButtonTitle : String, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, titleText : String?) {
//If can't set InputAccessoryView. Then return
if self.respondsToSelector(Selector("setInputAccessoryView:")) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = IQToolbar()
toolbar.doneTitle = rightButtonTitle
var items : [UIBarButtonItem] = []
let prev : IQBarButtonItem
let next : IQBarButtonItem
// Get the top level "bundle" which may actually be the framework
var bundle = NSBundle(forClass: IQKeyboardManager.self)
if let resourcePath = bundle.pathForResource("IQKeyboardManager", ofType: "bundle") {
if let resourcesBundle = NSBundle(path: resourcePath) {
bundle = resourcesBundle
}
}
var imageLeftArrow = UIImage(named: "IQButtonBarArrowLeft", inBundle: bundle, compatibleWithTraitCollection: nil)
var imageRightArrow = UIImage(named: "IQButtonBarArrowRight", inBundle: bundle, compatibleWithTraitCollection: nil)
//Support for RTL languages like Arabic, Persia etc... (Bug ID: #448)
if #available(iOS 9.0, *) {
imageLeftArrow = imageLeftArrow?.imageFlippedForRightToLeftLayoutDirection()
imageRightArrow = imageRightArrow?.imageFlippedForRightToLeftLayoutDirection()
}
prev = IQBarButtonItem(image: imageLeftArrow, style: UIBarButtonItemStyle.Plain, target: target, action: previousAction)
prev.accessibilityLabel = "Toolbar Previous Button"
next = IQBarButtonItem(image: imageRightArrow, style: UIBarButtonItemStyle.Plain, target: target, action: nextAction)
next.accessibilityLabel = "Toolbar Next Button"
//Previous button
items.append(prev)
//Fixed space
let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
fixed.width = 23
items.append(fixed)
//Next button
items.append(next)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Title button
let title = IQTitleBarButtonItem(title: shouldHidePlaceholderText == true ? nil : titleText)
items.append(title)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Right button
let doneButton = IQBarButtonItem(title: rightButtonTitle, style: UIBarButtonItemStyle.Done, target: target, action: rightButtonAction)
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
toolbar.toolbarTitleInvocation = self.titleInvocation
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
default:
toolbar.barStyle = UIBarStyle.Default
}
}
}
}
// /**
// Helper function to add ArrowNextPrevious and Right button on keyboard.
//
// @param target Target object for selector.
// @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
// @param previousAction Previous button action name. Usually 'previousAction:(id)item'.
// @param nextAction Next button action name. Usually 'nextAction:(id)item'.
// @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'.
// @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
// */
public func addPreviousNextRightOnKeyboardWithTarget( target : AnyObject?, rightButtonTitle : String, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, shouldShowPlaceholder : Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingPlaceholderText
}
addPreviousNextRightOnKeyboardWithTarget(target, rightButtonTitle: rightButtonTitle, previousAction: previousAction, nextAction: nextAction, rightButtonAction: rightButtonAction, titleText: title)
}
///-----------------------------------
/// MARK: Enable/Disable Previous/Next
///-----------------------------------
/**
Helper function to enable and disable previous next buttons.
@param isPreviousEnabled BOOL to enable/disable previous button on keyboard.
@param isNextEnabled BOOL to enable/disable next button on keyboard..
*/
public func setEnablePrevious ( isPreviousEnabled : Bool, isNextEnabled : Bool) {
// Getting inputAccessoryView.
if let inputAccessoryView = self.inputAccessoryView as? IQToolbar {
// If it is IQToolbar and it's items are greater than zero.
if inputAccessoryView.items?.count > 3 {
if let items = inputAccessoryView.items {
if let prevButton = items[0] as? IQBarButtonItem {
if let nextButton = items[2] as? IQBarButtonItem {
if prevButton.enabled != isPreviousEnabled {
prevButton.enabled = isPreviousEnabled
}
if nextButton.enabled != isNextEnabled {
nextButton.enabled = isNextEnabled
}
}
}
}
}
}
}
}
| mit | d336deca4fae675a5bd9c4c4634a6a7e | 42.846878 | 225 | 0.625124 | 5.983773 | false | false | false | false |
xiaomudegithub/viossvc | viossvc/Model/UserModel.swift | 1 | 3588 | //
// UserModel.swift
// viossvc
//
// Created by yaowang on 2016/11/21.
// Copyright © 2016年 ywwlcom.yundian. All rights reserved.
//
import UIKit
import XCGLogger
enum UserType: Int {
case Tourist = 1
case Leader = 2
}
class LoginModel: BaseModel {
var phone_num: String?
var passwd: String?
var user_type: Int = UserType.Leader.rawValue
}
class UserModel : BaseModel {
var uid: Int = 0
var head_url: String?
}
class UserInfoModel: UserModel {
var address: String?
var cash_lv: Int = 0
var credit_lv: Int = 0
var gender: Int = 0
var has_recharged: Int = 0
var latitude: Double = 0.0
var longitude: Double = 0.0
var nickname: String?
var phone_num: String?
var praise_lv: Int = 0
var register_status: Int = 0
var user_cash_: Int = 0
var auth_status_: Int = -1 //-1:未认证, 0:认证中, 1:认证通过, 2:认证失败
var currentBankCardNumber:String?
var currentBanckCardName:String?
var has_passwd_: Int = -1 //-1:未设置提现密码 1:已设置提现密码
var skills:String?
}
class SMSVerifyModel: BaseModel {
enum SMSType: Int {
case Register = 0
case Login = 1
}
var verify_type: Int = 0;
var phone_num: String?
init(phone: String, type: SMSVerifyModel.SMSType = .Login) {
self.verify_type = type.rawValue
self.phone_num = phone
}
}
class SMSVerifyRetModel: BaseModel {
var timestamp: Int64 = 0
var token: String!
}
class RegisterModel: SMSVerifyRetModel {
var verify_code: Int = 0
var phone_num: String!
var passwd: String!
var user_type: Int = UserType.Leader.rawValue;
var smsType:SMSVerifyModel.SMSType = .Register
}
class NotifyUserInfoModel: UserInfoModel {
}
class UserBankCardsModel: BaseModel {
}
class DrawCashRecordModel: BaseModel {
var cash: Int = 0
var account: String?
var request_time: String?
var status: Int = 0 //0:等待提现 1:已提现 2:失败
var withdraw_time: String?
var fail_reason: String?
var bank_username: String?
var bank_name: String?
}
class DrawCashModel: BaseModel {
var uid: Int = 0
var account: String?
var cash: Int = 0
var size: Int = 20
var num: Int = 0
var result: Int = 0
var withdraw_record: [DrawCashRecordModel] = []
class func withdraw_recordModleClass() -> AnyClass {
return DrawCashRecordModel.classForCoder()
}
}
class BankCardModel: BaseModel {
var account:String?
var bank_id = 0
var bank_username:String?
var is_default = 0
}
class DrawCashPasswordModel: BaseModel {
var uid: Int = 0
var new_passwd: String?
var old_passwd: String?
var passwd_type: Int = 0
var change_type: Int = 0
}
class PhotoModel: BaseModel {
var photo_url: String?
var thumbnail_url: String?
var upload_time: String?
}
class PhotoWallModel: BaseModel {
var photo_list:[PhotoModel] = []
class func photo_listModleClass() -> AnyClass {
return PhotoModel.classForCoder()
}
}
class PhotoWallRequestModel: BaseModel {
var uid: Int = 0
var size: Int = 0
var num: Int = 0
}
class UserServerModel: BaseModel {
var service_id: Int = 0
var service_name: String?
var service_start: Int = 0
var service_end: Int = 0
var service_price: Int = 0
var change_type: Int = 0 //0:删除,1:修改,2:新增
var service_type: Int = 0
}
class UpdateServerModel: BaseModel{
var uid: Int = 0
var service_list: [UserServerModel] = []
}
| apache-2.0 | fd44e24877153132d8c17c3fb0fbb8b5 | 20.537037 | 64 | 0.641445 | 3.457879 | false | false | false | false |
HongliYu/DPSlideMenuKit-Swift | DPSlideMenuKitDemo/SideContent/DPSettingsViewModel.swift | 1 | 1325 | //
// DPSettingsViewModel.swift
// DPSlideMenuKitDemo
//
// Created by Hongli Yu on 11/07/2017.
// Copyright © 2017 Hongli Yu. All rights reserved.
//
import UIKit
class DPSettingsSectionViewModel {
private(set) var title: String?
private(set) var height: CGFloat?
private(set) var actionBlock:(()->Void)?
init(title: String?,
height: CGFloat?,
actionBlock: (()->Void)?) {
self.title = title
self.height = height
self.actionBlock = actionBlock
}
}
class DPSettingsCellViewModel {
private(set) var color: UIColor?
private(set) var title: String?
private(set) var cellHeight: CGFloat?
private(set) var actionBlock:(()->Void)?
init(color: UIColor?,
title: String?,
cellHeight: CGFloat?,
actionBlock: (()->Void)?) {
self.color = color
self.title = title
self.cellHeight = cellHeight
self.actionBlock = actionBlock
}
}
class DPSettingsViewModel {
var settingsCellViewModels: [DPSettingsCellViewModel]?
var settingsSectionViewModel: DPSettingsSectionViewModel?
init(settingsCellViewModels: [DPSettingsCellViewModel]?,
settingsSectionViewModel: DPSettingsSectionViewModel?) {
self.settingsCellViewModels = settingsCellViewModels
self.settingsSectionViewModel = settingsSectionViewModel
}
}
| mit | a8e90923ebb13aeca2493731fc93aadb | 22.22807 | 63 | 0.696375 | 4.369637 | false | false | false | false |
tomaskraina/Kingfisher | Sources/Indicator.swift | 10 | 6710 | //
// Indicator.swift
// Kingfisher
//
// Created by João D. Moreira on 30/08/16.
//
// Copyright (c) 2018 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
#if os(macOS)
public typealias IndicatorView = NSView
#else
public typealias IndicatorView = UIView
#endif
public enum IndicatorType {
/// No indicator.
case none
/// Use system activity indicator.
case activity
/// Use an image as indicator. GIF is supported.
case image(imageData: Data)
/// Use a custom indicator, which conforms to the `Indicator` protocol.
case custom(indicator: Indicator)
}
// MARK: - Indicator Protocol
public protocol Indicator {
func startAnimatingView()
func stopAnimatingView()
var viewCenter: CGPoint { get set }
var view: IndicatorView { get }
}
extension Indicator {
#if os(macOS)
public var viewCenter: CGPoint {
get {
let frame = view.frame
return CGPoint(x: frame.origin.x + frame.size.width / 2.0, y: frame.origin.y + frame.size.height / 2.0 )
}
set {
let frame = view.frame
let newFrame = CGRect(x: newValue.x - frame.size.width / 2.0,
y: newValue.y - frame.size.height / 2.0,
width: frame.size.width,
height: frame.size.height)
view.frame = newFrame
}
}
#else
public var viewCenter: CGPoint {
get {
return view.center
}
set {
view.center = newValue
}
}
#endif
}
// MARK: - ActivityIndicator
// Displays a NSProgressIndicator / UIActivityIndicatorView
final class ActivityIndicator: Indicator {
#if os(macOS)
private let activityIndicatorView: NSProgressIndicator
#else
private let activityIndicatorView: UIActivityIndicatorView
#endif
private var animatingCount = 0
var view: IndicatorView {
return activityIndicatorView
}
func startAnimatingView() {
animatingCount += 1
// Already animating
if animatingCount == 1 {
#if os(macOS)
activityIndicatorView.startAnimation(nil)
#else
activityIndicatorView.startAnimating()
#endif
activityIndicatorView.isHidden = false
}
}
func stopAnimatingView() {
animatingCount = max(animatingCount - 1, 0)
if animatingCount == 0 {
#if os(macOS)
activityIndicatorView.stopAnimation(nil)
#else
activityIndicatorView.stopAnimating()
#endif
activityIndicatorView.isHidden = true
}
}
init() {
#if os(macOS)
activityIndicatorView = NSProgressIndicator(frame: CGRect(x: 0, y: 0, width: 16, height: 16))
activityIndicatorView.controlSize = .small
activityIndicatorView.style = .spinning
#else
#if os(tvOS)
let indicatorStyle = UIActivityIndicatorViewStyle.white
#else
let indicatorStyle = UIActivityIndicatorViewStyle.gray
#endif
activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:indicatorStyle)
activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleTopMargin]
#endif
}
}
// MARK: - ImageIndicator
// Displays an ImageView. Supports gif
final class ImageIndicator: Indicator {
private let animatedImageIndicatorView: ImageView
var view: IndicatorView {
return animatedImageIndicatorView
}
init?(imageData data: Data, processor: ImageProcessor = DefaultImageProcessor.default, options: KingfisherOptionsInfo = KingfisherEmptyOptionsInfo) {
var options = options
// Use normal image view to show animations, so we need to preload all animation data.
if !options.preloadAllAnimationData {
options.append(.preloadAllAnimationData)
}
guard let image = processor.process(item: .data(data), options: options) else {
return nil
}
animatedImageIndicatorView = ImageView()
animatedImageIndicatorView.image = image
animatedImageIndicatorView.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
#if os(macOS)
// Need for gif to animate on macOS
self.animatedImageIndicatorView.imageScaling = .scaleNone
self.animatedImageIndicatorView.canDrawSubviewsIntoLayer = true
#else
animatedImageIndicatorView.contentMode = .center
animatedImageIndicatorView.autoresizingMask = [.flexibleLeftMargin,
.flexibleRightMargin,
.flexibleBottomMargin,
.flexibleTopMargin]
#endif
}
func startAnimatingView() {
#if os(macOS)
animatedImageIndicatorView.animates = true
#else
animatedImageIndicatorView.startAnimating()
#endif
animatedImageIndicatorView.isHidden = false
}
func stopAnimatingView() {
#if os(macOS)
animatedImageIndicatorView.animates = false
#else
animatedImageIndicatorView.stopAnimating()
#endif
animatedImageIndicatorView.isHidden = true
}
}
| mit | 8ea080c801d03ec0b6473edd9265de8b | 32.713568 | 153 | 0.629602 | 5.249609 | false | false | false | false |
jamgzj/resourceObject | Swift/SwiftStudy/SwiftStudy/AppDelegate.swift | 1 | 2628 | //
// AppDelegate.swift
// SwiftStudy
//
// Created by zhengxingxia on 2017/1/10.
// Copyright © 2017年 zhengxingxia. All rights reserved.
//
import UIKit
import IQKeyboardManager
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame:UIScreen.main.bounds)
window?.rootViewController = TestViewController()
window?.makeKeyAndVisible()
let manager = IQKeyboardManager.shared()
manager.toolbarDoneBarButtonItemText = "完成"
manager.isEnabled = true
manager.shouldResignOnTouchOutside = true
manager.shouldToolbarUsesTextFieldTintColor = true
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 | 84cd3e01ee6187f097fa82e6de2802e2 | 44.189655 | 285 | 0.740176 | 5.837416 | false | false | false | false |
loudnate/Loop | Common/Models/StatusExtensionContext.swift | 1 | 6869 | //
// StatusExtensionContext.swift
// Loop Status Extension
//
// Created by Bharat Mediratta on 11/25/16.
// Copyright © 2016 LoopKit Authors. All rights reserved.
//
// This class allows Loop to pass context data to the Loop Status Extension.
import Foundation
import HealthKit
import LoopKit
import LoopKitUI
struct NetBasalContext {
let rate: Double
let percentage: Double
let start: Date
let end: Date?
}
struct SensorDisplayableContext: SensorDisplayable {
let isStateValid: Bool
let stateDescription: String
let trendType: GlucoseTrend?
let isLocal: Bool
}
struct GlucoseContext: GlucoseValue {
let value: Double
let unit: HKUnit
let startDate: Date
var quantity: HKQuantity {
return HKQuantity(unit: unit, doubleValue: value)
}
}
struct PredictedGlucoseContext {
let values: [Double]
let unit: HKUnit
let startDate: Date
let interval: TimeInterval
var samples: [GlucoseContext] {
var result: [GlucoseContext] = []
for (i, v) in values.enumerated() {
result.append(GlucoseContext(value: v, unit: unit, startDate: startDate.addingTimeInterval(Double(i) * interval)))
}
return result
}
}
extension NetBasalContext: RawRepresentable {
typealias RawValue = [String: Any]
var rawValue: RawValue {
var value: RawValue = [
"rate": rate,
"percentage": percentage,
"start": start
]
value["end"] = end
return value
}
init?(rawValue: RawValue) {
guard
let rate = rawValue["rate"] as? Double,
let percentage = rawValue["percentage"] as? Double,
let start = rawValue["start"] as? Date
else {
return nil
}
self.rate = rate
self.percentage = percentage
self.start = start
self.end = rawValue["end"] as? Date
}
}
extension SensorDisplayableContext: RawRepresentable {
typealias RawValue = [String: Any]
var rawValue: RawValue {
var raw: RawValue = [
"isStateValid": isStateValid,
"stateDescription": stateDescription,
"isLocal": isLocal
]
raw["trendType"] = trendType?.rawValue
return raw
}
init(_ other: SensorDisplayable) {
isStateValid = other.isStateValid
stateDescription = other.stateDescription
isLocal = other.isLocal
trendType = other.trendType
}
init?(rawValue: RawValue) {
guard
let isStateValid = rawValue["isStateValid"] as? Bool,
let stateDescription = rawValue["stateDescription"] as? String,
let isLocal = rawValue["isLocal"] as? Bool
else {
return nil
}
self.isStateValid = isStateValid
self.stateDescription = stateDescription
self.isLocal = isLocal
if let rawValue = rawValue["trendType"] as? GlucoseTrend.RawValue {
trendType = GlucoseTrend(rawValue: rawValue)
} else {
trendType = nil
}
}
}
extension PredictedGlucoseContext: RawRepresentable {
typealias RawValue = [String: Any]
var rawValue: RawValue {
return [
"values": values,
"unit": unit.unitString,
"startDate": startDate,
"interval": interval
]
}
init?(rawValue: RawValue) {
guard
let values = rawValue["values"] as? [Double],
let unitString = rawValue["unit"] as? String,
let startDate = rawValue["startDate"] as? Date,
let interval = rawValue["interval"] as? TimeInterval
else {
return nil
}
self.values = values
self.unit = HKUnit(from: unitString)
self.startDate = startDate
self.interval = interval
}
}
struct PumpManagerHUDViewsContext: RawRepresentable {
typealias RawValue = [String: Any]
let pumpManagerHUDViewsRawValue: PumpManagerHUDViewsRawValue
init(pumpManagerHUDViewsRawValue: PumpManagerHUDViewsRawValue) {
self.pumpManagerHUDViewsRawValue = pumpManagerHUDViewsRawValue
}
init?(rawValue: RawValue) {
if let pumpManagerHUDViewsRawValue = rawValue["pumpManagerHUDViewsRawValue"] as? PumpManagerHUDViewsRawValue {
self.pumpManagerHUDViewsRawValue = pumpManagerHUDViewsRawValue
} else {
return nil
}
}
var rawValue: RawValue {
return ["pumpManagerHUDViewsRawValue": pumpManagerHUDViewsRawValue]
}
}
struct StatusExtensionContext: RawRepresentable {
typealias RawValue = [String: Any]
private let version = 5
var predictedGlucose: PredictedGlucoseContext?
var lastLoopCompleted: Date?
var netBasal: NetBasalContext?
var batteryPercentage: Double?
var reservoirCapacity: Double?
var sensor: SensorDisplayableContext?
var pumpManagerHUDViewsContext: PumpManagerHUDViewsContext?
init() { }
init?(rawValue: RawValue) {
guard let version = rawValue["version"] as? Int, version == self.version else {
return nil
}
if let rawValue = rawValue["predictedGlucose"] as? PredictedGlucoseContext.RawValue {
predictedGlucose = PredictedGlucoseContext(rawValue: rawValue)
}
if let rawValue = rawValue["netBasal"] as? NetBasalContext.RawValue {
netBasal = NetBasalContext(rawValue: rawValue)
}
lastLoopCompleted = rawValue["lastLoopCompleted"] as? Date
batteryPercentage = rawValue["batteryPercentage"] as? Double
reservoirCapacity = rawValue["reservoirCapacity"] as? Double
if let rawValue = rawValue["sensor"] as? SensorDisplayableContext.RawValue {
sensor = SensorDisplayableContext(rawValue: rawValue)
}
if let rawPumpManagerHUDViewsContext = rawValue["pumpManagerHUDViewsContext"] as? PumpManagerHUDViewsContext.RawValue {
pumpManagerHUDViewsContext = PumpManagerHUDViewsContext(rawValue: rawPumpManagerHUDViewsContext)
}
}
var rawValue: RawValue {
var raw: RawValue = [
"version": version
]
raw["predictedGlucose"] = predictedGlucose?.rawValue
raw["lastLoopCompleted"] = lastLoopCompleted
raw["netBasal"] = netBasal?.rawValue
raw["batteryPercentage"] = batteryPercentage
raw["reservoirCapacity"] = reservoirCapacity
raw["sensor"] = sensor?.rawValue
raw["pumpManagerHUDViewsContext"] = pumpManagerHUDViewsContext?.rawValue
return raw
}
}
extension StatusExtensionContext: CustomDebugStringConvertible {
var debugDescription: String {
return String(reflecting: rawValue)
}
}
| apache-2.0 | 8f5aa15d027a1f31e0edb74339657a67 | 27.736402 | 127 | 0.635847 | 5.016801 | false | false | false | false |
DSanzh/GuideMe-iOS | GuideMe/Controller/ProductDetailVC.swift | 1 | 534 | //
// ProductDetailVC.swift
// GuideMe
//
// Created by Sanzhar on 9/29/17.
// Copyright © 2017 Sanzhar Dauylov. All rights reserved.
//
import UIKit
class ProductDetailVC: UIViewController {
lazy var mainImage: UIImageView = {
let _image = UIImageView()
_image.contentMode = .scaleAspectFill
return _image
}()
lazy var priceLabel: UILabel = {
let _label = UILabel()
return _label
}()
override func viewDidLoad() {
super.viewDidLoad()
}
}
| mit | f616b005ba3a52ebf0d57c3ebd8b73c5 | 18.035714 | 58 | 0.596623 | 4.230159 | false | false | false | false |
michaelborgmann/handshake | Handshake/ItemsTableViewController.swift | 1 | 4389 | //
// ItemsTableViewController.swift
// Handshake
//
// Created by Michael Borgmann on 16/08/15.
// Copyright (c) 2015 Michael Borgmann. All rights reserved.
//
import UIKit
class ItemsTableViewController: UITableViewController, UITableViewDelegate {
var email: String?
override init(style: UITableViewStyle) {
super.init(style: UITableViewStyle.Plain)
self.navigationItem.title = "Items"
let addItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "add:")
navigationItem.rightBarButtonItem = addItem
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nil, bundle: nil)
}
required init!(coder aDecoder: NSCoder!) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "ItemCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "ItemCell")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ItemStore.sharedStore.allItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath) as! ItemCell
let item = ItemStore.sharedStore.allItems[indexPath.row]
//cell.textLabel?.text = tabName.description
if email != item.email {
cell.hidden = true
}
cell.amountLabel.text = "\(item.amount)"
cell.nameLabel.text = item.name
cell.priceLabel.text = "\(item.price)"
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var rowHeight: CGFloat = 44
let item = ItemStore.sharedStore.allItems[indexPath.row]
if email != item.email {
rowHeight = 0.0
}
return rowHeight
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
var item = ItemStore.sharedStore.allItems[indexPath.row]
ItemStore.sharedStore.removeItem(item)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
ItemStore.sharedStore.moveItemAtIndex(sourceIndexPath.row, toIndex: destinationIndexPath.row)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = ItemStore.sharedStore.allItems[indexPath.row]
let detailView = DetailView()
detailView.item = item
detailView.email = email
self.navigationController?.modalPresentationStyle = UIModalPresentationStyle.FormSheet
self.navigationController?.pushViewController(detailView, animated: true)
}
@IBAction func logout(sender: UIButton) {
print("button pressed")
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "isLoggedIn")
NSUserDefaults.standardUserDefaults().synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
}
func add(sender: AnyObject) {
//@IBAction func doneButtonPressed(sender: AnyObject) {
let item = ItemStore.sharedStore.createItem()
let detailView = DetailView()
detailView.item = item
detailView.email = email
self.navigationController?.modalPresentationStyle = UIModalPresentationStyle.FormSheet
self.navigationController?.pushViewController(detailView, animated: true)
}
}
| gpl-2.0 | 9bb66ea85774ece95e0302a88617d58f | 34.97541 | 157 | 0.677603 | 5.576874 | false | false | false | false |
ianchengtw/ios_30_apps_in_30_days | Day_01_TodoApp/TodoApp/TodoApp/controllers/EditItemViewController.swift | 1 | 1954 | //
// EditItemViewController.swift
// TodoApp
//
// Created by Ian on 5/7/16.
// Copyright © 2016 ianchengtw_ios_30_apps_in_30_days. All rights reserved.
//
import UIKit
class EditItemViewController: UIViewController {
@IBOutlet weak var titleInput: UITextField!
@IBOutlet weak var descriptionInput: UITextView!
@IBOutlet weak var btnSave: UIButton!
var todoItem: TodoItem = TodoItem(id: 0, title: "", description: "")
override func viewDidLoad() {
super.viewDidLoad()
self.titleInput.text = todoItem.title
self.titleInput.becomeFirstResponder()
self.descriptionInput.text = todoItem.description
self.btnSave.layer.cornerRadius = 5
self.btnSave.layer.borderWidth = 1
self.btnSave.layer.borderColor = UIColor.blueColor().CGColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func deleteItem(sender: UIBarButtonItem) {
todoItemModel.removeTodoItem(self.todoItem)
self.navigationController?.popToRootViewControllerAnimated(true)
}
@IBAction func saveItem(sender: UIButton) {
self.todoItem.title = titleInput.text ?? ""
self.todoItem.description = descriptionInput.text ?? ""
todoItemModel.updateTodoItem(self.todoItem)
self.navigationController?.popToRootViewControllerAnimated(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 468612a1e8ddb1926ca89520ed1f73ed | 28.149254 | 106 | 0.655914 | 4.982143 | false | false | false | false |
wupingzj/YangRepoApple | QiuTuiJian/QiuTuiJian/BusinessEntityLayoutFactory.swift | 1 | 17027 | //
// BusinessEntityLayoutFactory.swift
// QiuTuiJian
//
// Created by Ping on 8/09/2014.
// Copyright (c) 2014 Yang Ltd. All rights reserved.
//
import Foundation
import UIKit
class BusinessEntityLayoutFactory {
private var businessEntityDetailVC: UIViewController
private var selectedBusinessEntity: BusinessEntity?
private var contentView: UIView
private var contentViewsDictionary: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
private var metricsDictionary: Dictionary<String, CGFloat> = ["labelWidth":80.0, "textWidth":100.0]
private let standardLineGap = CGFloat(8.0)
private var adjustableViews: [UIView] = []
init(businessEntityDetailVC: UIViewController, businessEntity: BusinessEntity?, contentView: UIView) {
self.businessEntityDetailVC = businessEntityDetailVC
self.selectedBusinessEntity = businessEntity
self.contentView = contentView
self.contentViewsDictionary["contentView"] = contentView
// TODO - find out the totoal height of UI components on different devices
if Utils.sharedInstance.isIOS703() || Utils.sharedInstance.isIOS71() {
// For iOS7, increase the gap
standardLineGap = CGFloat(12.0)
}
metricsDictionary["labelHeight"] = CGFloat(20.0)
}
func showBusinessEntityMissingMessage() {
let errorMsg: UITextView = UITextView()
self.contentViewsDictionary["errorMsg"] = errorMsg
errorMsg.font = UIFont.systemFontOfSize(20.0)
errorMsg.text = "Please go back and select a business entity."
self.contentView.addSubview(errorMsg)
// errorMsg location
errorMsg.setTranslatesAutoresizingMaskIntoConstraints(false)
var constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[errorMsg(>=50)]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: contentViewsDictionary)
var constraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[errorMsg(100)]", options: NSLayoutFormatOptions(0), metrics: nil, views: contentViewsDictionary)
self.contentView.addConstraints(constraintsH)
self.contentView.addConstraints(constraintsV)
}
func showBusinessEntityDetails() {
// This view is very dynamic. Mixed-layout mechanisms are used to generate dyanmic views and orientation
// The contentView relies on auto resizeing to constraints
// The subviews are purely programatically aligned using layout format constraints
if let businessEntity = self.selectedBusinessEntity {
println("*** configuring the business entity \(businessEntity) ***")
var startY = CGFloat(0)
// basics
let basicsView: UIView = createBasicsView(x: 0, y: startY)
adjustableViews.append(basicsView)
// address
startY += basicsView.bounds.height
let addressView: UIView = createAddressView(x: 0, y: startY)
adjustableViews.append(addressView)
// optional description
startY += addressView.bounds.height
let descView: UIView? = createDescriptionView(x: 0, y: startY)
if (descView != nil) {
adjustableViews.append(descView!)
}
}
//self.contentView.backgroundColor = UIColor.greenColor()
}
func adjustViewBounds() {
for view: UIView in adjustableViews {
adjustViewBounds(view)
}
}
private func adjustViewBounds(view: UIView) {
// adjust width only
let bounds = UIScreen.mainScreen().bounds
let currentX = view.frame.origin.x
let currentY = view.frame.origin.y
let currentHeight = view.frame.height
view.frame = CGRect(x: currentX, y: currentY, width: bounds.width, height: currentHeight)
}
private func showDictionary(dictionary: Dictionary<String, AnyObject>) {
for (key, value) in dictionary {
println("key=\(key), value=\(value)")
}
}
private func appendToFormatV(inout format:String, label: String) {
format = format + "-[" + label + "(labelHeight)]"
}
// create basic details view of the business entity
private func createBasicsView(#x: CGFloat, y: CGFloat) -> UIView {
let businessEntity: BusinessEntity = selectedBusinessEntity!
let basicsView: UIView = UIView()
self.contentView.addSubview(basicsView)
//basicsView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.contentViewsDictionary["basicsView"] = basicsView
basicsView.backgroundColor = UIColor.greenColor()
var basicsViewDictionary: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
//*****
// Better be integer but CGFloat saves the hassle of data type conversion
var lineCount = CGFloat(0)
var formatH: [String] = []
var labelFormatV = "V:|"
var textFormatV = "V:|"
// category
let categoryLabel: UILabel = createLabel(basicsView, viewDictionary: &basicsViewDictionary, labelName: "categoryLabel", labelText: "Category:")
let category: UILabel = createLabel(basicsView, viewDictionary: &basicsViewDictionary, labelName: "category", labelText: businessEntity.category)
formatH.append("H:|-[categoryLabel(labelWidth)]-[category(>=textWidth)]-|")
appendToFormatV(&labelFormatV, label: "categoryLabel")
appendToFormatV(&textFormatV, label: "category")
++lineCount
// name
let nameLabel: UILabel = createLabel(basicsView, viewDictionary: &basicsViewDictionary, labelName: "nameLabel", labelText: "Name:")
let name: UILabel = createLabel(basicsView, viewDictionary: &basicsViewDictionary, labelName: "name", labelText: businessEntity.getContactName())
formatH.append("H:|-[nameLabel(labelWidth)]-[name(>=textWidth)]-|")
appendToFormatV(&labelFormatV, label: "nameLabel")
appendToFormatV(&textFormatV, label: "name")
++lineCount
// phone
if (businessEntity.phone != nil) {
let phoneLabel: UILabel = createLabel(basicsView, viewDictionary: &basicsViewDictionary, labelName: "phoneLabel", labelText: "Phone:")
let phone: UILabel = createLabel(basicsView, viewDictionary: &basicsViewDictionary, labelName: "phone", labelText: businessEntity.phone!)
formatH.append("H:|-[phoneLabel(labelWidth)]-[phone(>=textWidth)]-|")
appendToFormatV(&labelFormatV, label: "phoneLabel")
appendToFormatV(&textFormatV, label: "phone")
++lineCount
registerAction(phone, action:"callPhone")
}
// mobile
if let mobileNumber = businessEntity.getMobile() {
let mobileLabel: UILabel = createLabel(basicsView, viewDictionary: &basicsViewDictionary, labelName: "mobileLabel", labelText: "Mobile:")
let mobile: UILabel = createLabel(basicsView, viewDictionary: &basicsViewDictionary, labelName: "mobile", labelText: mobileNumber)
formatH.append("H:|-[mobileLabel(labelWidth)]-[mobile(>=textWidth)]-|")
appendToFormatV(&labelFormatV, label: "mobileLabel")
appendToFormatV(&textFormatV, label: "mobile")
++lineCount
registerAction(mobile, action:"callMobile")
}
// email
if businessEntity.email != nil {
let emailLabel: UILabel = createLabel(basicsView, viewDictionary: &basicsViewDictionary, labelName: "emailLabel", labelText: "Email:")
let email: UILabel = createLabel(basicsView, viewDictionary: &basicsViewDictionary, labelName: "email", labelText: businessEntity.email!)
formatH.append("H:|-[emailLabel(labelWidth)]-[email(>=textWidth)]-|")
appendToFormatV(&labelFormatV, label: "emailLabel")
appendToFormatV(&textFormatV, label: "email")
++lineCount
registerAction(email, action:"sendEmail")
}
// uuid - enable for debugging
if false {
let uuidLabel: UILabel = createLabel(basicsView, viewDictionary: &basicsViewDictionary, labelName: "uuidLabel", labelText: "uuid:")
let uuid: UILabel = createLabel(basicsView, viewDictionary: &basicsViewDictionary, labelName: "uuid", labelText: businessEntity.uuid)
formatH.append("H:|-[uuidLabel(labelWidth)]-[uuid(>=textWidth)]-|")
appendToFormatV(&labelFormatV, label: "uuidLabel")
appendToFormatV(&textFormatV, label: "uuid")
++lineCount
}
println("labelFormatV=\(labelFormatV)")
println("textFormatV=\(textFormatV)")
let constraintCreator: ConstraintCreator = ConstraintCreator(view: basicsView, metrics: metricsDictionary, views: basicsViewDictionary)
constraintCreator.addConstraints(formatH, options: NSLayoutFormatOptions(0))
constraintCreator.addConstraint(labelFormatV, options: NSLayoutFormatOptions(0))
constraintCreator.addConstraint(textFormatV, options: NSLayoutFormatOptions(0))
// calculate total view height
let viewHeight: CGFloat = lineCount * (metricsDictionary["labelHeight"]! + standardLineGap)
println("lineCount=\(lineCount), viewHeight=\(viewHeight)")
let bounds = UIScreen.mainScreen().bounds
// set view bounds
basicsView.frame = CGRect(x: x, y: y, width: bounds.width, height: viewHeight)
return basicsView
}
private func createAddressView(#x: CGFloat, y:CGFloat) -> UIView {
let businessEntity: BusinessEntity = selectedBusinessEntity!
let addressView: UIView = UIView()
let bounds = UIScreen.mainScreen().bounds
addressView.frame = CGRect(x: x, y: y, width: bounds.width, height: 180)
self.contentView.addSubview(addressView)
//addressView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.contentViewsDictionary["addressView"] = addressView
addressView.backgroundColor = UIColor.blueColor()
var addressViewDictionary: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
// address label
let addressLabel: UILabel = createLabel(addressView, viewDictionary: &addressViewDictionary, labelName: "addressLabel", labelText: "Address:")
// address detail
let addressLine1: UILabel = createLabel(addressView, viewDictionary: &addressViewDictionary, labelName: "addressLine1", labelText: businessEntity.address.getLine1())
let addressLine2: UILabel = createLabel(addressView, viewDictionary: &addressViewDictionary, labelName: "addressLine2", labelText: businessEntity.address.getLine2())
let city: UILabel = createLabel(addressView, viewDictionary: &addressViewDictionary, labelName: "city", labelText: businessEntity.address.city)
let state: UILabel = createLabel(addressView, viewDictionary: &addressViewDictionary, labelName: "state", labelText: businessEntity.address.state)
let country: UILabel = createLabel(addressView, viewDictionary: &addressViewDictionary, labelName: "country", labelText: businessEntity.address.country)
let postCode: UILabel = createLabel(addressView, viewDictionary: &addressViewDictionary, labelName: "postCode", labelText: businessEntity.address.postCode)
// setup address label constraints
let constraintCreator: ConstraintCreator = ConstraintCreator(view: addressView, metrics: metricsDictionary, views: addressViewDictionary)
constraintCreator.addConstraint("H:|-[addressLabel(labelWidth)]-[addressLine1(>=textWidth)]-|", options: NSLayoutFormatOptions(0))
constraintCreator.addConstraint("H:|-95-[addressLine2(>=textWidth)]-|", options: NSLayoutFormatOptions(0))
constraintCreator.addConstraint("H:|-95-[city(>=textWidth)]-|", options: NSLayoutFormatOptions(0))
constraintCreator.addConstraint("H:|-95-[state(>=textWidth)]-|", options: NSLayoutFormatOptions(0))
constraintCreator.addConstraint("H:|-95-[country(>=textWidth)]-|", options: NSLayoutFormatOptions(0))
constraintCreator.addConstraint("H:|-95-[postCode(>=textWidth)]-|", options: NSLayoutFormatOptions(0))
constraintCreator.addConstraint("V:|-[addressLabel(labelHeight)]", options: NSLayoutFormatOptions(0))
var formatV: String = "V:|-[addressLine1(labelHeight)]-[addressLine2(labelHeight)]-[city(labelHeight)]-[state(labelHeight)]-[country(labelHeight)]-[postCode(labelHeight)]"
constraintCreator.addConstraint(formatV, options: NSLayoutFormatOptions(0))
return addressView
}
// create basic details view of the business entity
private func createDescriptionView(#x: CGFloat, y: CGFloat) -> UIView? {
let businessEntity: BusinessEntity = selectedBusinessEntity!
if businessEntity.desc == nil {
return nil
}
let descView: UIView = UIView()
self.contentView.addSubview(descView)
self.contentViewsDictionary["descView"] = descView
descView.backgroundColor = UIColor.grayColor()
var descViewDictionary: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
// Better be integer but CGFloat saves the hassle of data type conversion
var lineCount = CGFloat(0)
var formatH: [String] = []
var labelFormatV = "V:|"
var textFormatV = "V:|"
if let description = businessEntity.desc {
let descLabel: UILabel = createLabel(descView, viewDictionary: &descViewDictionary, labelName: "descLabel", labelText: "Description:")
let desc: UILabel = createLabel(descView, viewDictionary: &descViewDictionary, labelName: "desc", labelText: description)
formatH.append("H:|-[descLabel(labelWidth)]-[desc(>=textWidth)]-|")
appendToFormatV(&labelFormatV, label: "descLabel")
appendToFormatV(&textFormatV, label: "desc")
++lineCount
}
println("labelFormatV=\(labelFormatV)")
println("textFormatV=\(textFormatV)")
let constraintCreator: ConstraintCreator = ConstraintCreator(view: descView, metrics: metricsDictionary, views: descViewDictionary)
constraintCreator.addConstraints(formatH, options: NSLayoutFormatOptions(0))
constraintCreator.addConstraint(labelFormatV, options: NSLayoutFormatOptions(0))
constraintCreator.addConstraint(textFormatV, options: NSLayoutFormatOptions(0))
// calculate total view height
let viewHeight: CGFloat = lineCount * (metricsDictionary["labelHeight"]! + standardLineGap)
println("lineCount=\(lineCount), viewHeight=\(viewHeight)")
let bounds = UIScreen.mainScreen().bounds
// set view bounds
descView.frame = CGRect(x: x, y: y, width: bounds.width, height: viewHeight)
// println("UIScreen.mainScreen().bounds.height=\(bounds.height)")
// println("UIScreen.mainScreen().bounds.width=\(bounds.width)")
// println("descView.frame.height=\(descView.frame.height)")
// println("descView.frame.width=\(descView.frame.width)")
// println("descView.frame.size=\(descView.frame.size)")
// println("descView.bounds.width=\(descView.bounds.width)")
// println("descView.bounds.height=\(descView.bounds.height)")
// println("descView.bounds.size=\(descView.bounds.size)")
return descView
}
// the viewDictionary is added with the newly created label
// Parameter: labelName is the label name in the viewDictionary
// labelText is the label text that is displayed on view
private func createLabel(view: UIView, inout viewDictionary: Dictionary<String, AnyObject>, labelName:String, labelText:String) -> UILabel {
var label: UILabel = UILabel()
label.text = labelText
view.addSubview(label)
viewDictionary[labelName] = label
label.setTranslatesAutoresizingMaskIntoConstraints(false)
return label
}
private func registerAction(view: UIView, action: String) {
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self.businessEntityDetailVC, action: Selector(action))
view.userInteractionEnabled = true
view.addGestureRecognizer(tapGestureRecognizer)
println("registering action for view \(view). action=\(action)")
}
}
| gpl-2.0 | 9bb5cab957499d86296432c7fe817545 | 47.509972 | 179 | 0.664885 | 5.096378 | false | false | false | false |
FandyLiu/FDDemoCollection | Swift/Apply/Apply/ButtonTableViewCell.swift | 1 | 2668 | //
// ButtonTableViewCell.swift
// Apply
//
// Created by QianTuFD on 2017/4/1.
// Copyright © 2017年 fandy. All rights reserved.
//
import UIKit
enum ButtonTableViewCellType {
case button(title: String, top: CGFloat, bottom: CGFloat)
}
class ButtonTableViewCell: ApplyTableViewCell, ApplyTableViewCellProtocol {
static var indentifier: String = "ButtonTableViewCell"
fileprivate var buttonTopConstract: NSLayoutConstraint?
var myType: ButtonTableViewCellType = .button(title: "", top: 0.0, bottom: 0.0) {
didSet {
cellType = ApplyTableViewCellType.button(myType)
switch myType {
case let .button(title: title, top: top, bottom: _):
button.setTitle(title, for: UIControlState.normal)
buttonTopConstract?.constant = top
}
}
}
let button: UIButton = {
let button = UIButton(type: .custom)
button.backgroundColor = COLOR_1478b8
button.layer.cornerRadius = 10.f
button.layer.masksToBounds = true
return button
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
mycontentView.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(ButtonTableViewCell.nextButtonClick(btn:)), for: UIControlEvents.touchUpInside)
let topConstract = NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: mycontentView, attribute: .top, multiplier: 1.0, constant: 20.0)
let centerXConstract = NSLayoutConstraint(item: button, attribute: .centerX, relatedBy: .equal, toItem: mycontentView, attribute: .centerX, multiplier: 1.0, constant: 0.0)
mycontentView.addConstraints([topConstract, centerXConstract])
let widthConstract = NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 320)
let heightConstract = NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 45.0)
buttonTopConstract = topConstract
button.addConstraints([widthConstract, heightConstract])
mycontentView.addConstraints([topConstract, centerXConstract])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func nextButtonClick(btn: UIButton) {
delegate?.buttonCell?(self, nextButtonClick: btn)
}
}
| mit | e084283e688353aee0b642522d1f56a7 | 41.983871 | 179 | 0.68818 | 4.547782 | false | false | false | false |
Totopolis/monik.ios | sources/monik/Monik.swift | 1 | 3433 | //
// Monik.swift
// MonikiOS
//
// Created by Сергей Пестов on 29/12/2016.
// Copyright © 2016 SmartDriving. All rights reserved.
//
import Foundation
open class Monik: Closable {
public enum Source {
case system
case application
case logic
case security
var description: String {
return String(describing: self)
}
}
public enum Level {
case trace, info, warning, error, fatal
var description: String {
return String(describing: self)
}
init?(from: String) {
let all: [Level] = [.trace, .info, .warning, .error, .fatal]
guard let found = all.filter({ $0.description == from }).first else {
return nil
}
self = found
}
}
open func securityFatal(_ message: String) {
log(.security, .fatal, message)
}
open func systemTrace(_ message: String) {
log(.system, .trace, message)
}
open func logicWarning(_ message: String) {
log(.logic, .warning, message)
}
open func log(_ source: Source, _ level: Level, _ message: String) {
queue.async {
self.loggers.forEach {
if level >= $0.level {
// format message with formatter or leave unchanged if nil formatter.
let msg = $0.formatter?.format(message) ?? message
// log message to queue.
$0.log(source, level, msg)
}
}
}
}
open func close() {
loggers.forEach { ($0 as? Closable)?.close() }
}
open var loggers: [Logger] = []
fileprivate let queue = DispatchQueue(label: "monik.log")
open static var `default`: Monik = {
let m = Monik()
m.loggers = [ ConsoleLogger() ]
return m
}()
}
extension Monik {
open func configure(with data: [AnyHashable : Any], factory: Factory.Type) throws {
guard let loggers = data["loggers"] as? [[AnyHashable: Any]] else {
throw MonikError.configureError
}
self.loggers = loggers.flatMap {
guard let channel = $0["channel"] as? String,
let logger = factory.instantiate(channel) else
{
return nil
}
if let enabled = $0["enabled"] as? Bool,
enabled == false
{
return nil
}
try? (logger as? Configurable)?.configure(with: $0)
return logger
}
}
open func configure(with url: URL) {
queue.async {
guard let data = try? Data(contentsOf: url),
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [AnyHashable: Any],
let configuration = json else
{
return
}
try? self.configure(with: configuration, factory: Factory.self)
}
}
}
extension Monik.Level: Comparable {}
public func ==(lhs: Monik.Level, rhs: Monik.Level) -> Bool {
return lhs.hashValue == rhs.hashValue
}
public func <(lhs: Monik.Level, rhs: Monik.Level) -> Bool {
return lhs.hashValue < rhs.hashValue
}
| mit | b6963e85178a9179633f4cda1ed82ae6 | 25.10687 | 109 | 0.50614 | 4.640434 | false | true | false | false |
awkward/Tatsi | Tatsi/Views/Albums/AlbumsViewController.swift | 1 | 11552 | //
// AlbumsViewController.swift
// AWKImagePickerController
//
// Created by Rens Verhoeven on 27-03-16.
// Copyright © 2017 Awkward BV. All rights reserved.
//
import UIKit
import Photos
internal protocol AlbumsViewControllerDelegate: class {
/// Called when an album is selected in the album list.
///
/// - Parameters:
/// - albumsViewController: The AlbumsViewController in which the album was selected.
/// - album: The selected album.
func albumsViewController(_ albumsViewController: AlbumsViewController, didSelectAlbum album: PHAssetCollection)
}
final internal class AlbumsViewController: UITableViewController, PickerViewController {
/// A category in which a album lives. These categories are displayed as sections in the table view.
internal struct AlbumCategory {
/// The title that should be displayed in the header above the albums.
var headerTitle: String?
/// The albums that should be displayed for the category.
let albums: [PHAssetCollection]
}
// MARK: - Public Properties
/// Set the delegate in order to recieve a callback when the user selects an album.
weak var delegate: AlbumsViewControllerDelegate?
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.config?.preferredStatusBarStyle ?? .default
}
// MARK: - Private Properties
/// The categories of albums to display in the album list. These translate to the sections in the table view.
fileprivate var categories: [AlbumCategory] = []
lazy fileprivate var smartAlbumSortingOrder: [PHAssetCollectionSubtype] = {
var smartAlbumSortingOrder = [
PHAssetCollectionSubtype.smartAlbumUserLibrary,
PHAssetCollectionSubtype.smartAlbumFavorites,
PHAssetCollectionSubtype.smartAlbumRecentlyAdded,
PHAssetCollectionSubtype.smartAlbumVideos,
PHAssetCollectionSubtype.smartAlbumSelfPortraits,
PHAssetCollectionSubtype.smartAlbumPanoramas,
PHAssetCollectionSubtype.smartAlbumTimelapses,
PHAssetCollectionSubtype.smartAlbumSlomoVideos,
PHAssetCollectionSubtype.smartAlbumBursts,
PHAssetCollectionSubtype.smartAlbumScreenshots,
PHAssetCollectionSubtype.smartAlbumAllHidden
]
if #available(iOS 10.3, *), let index = smartAlbumSortingOrder.firstIndex(of: .smartAlbumPanoramas) {
smartAlbumSortingOrder.insert(.smartAlbumLivePhotos, at: index)
}
if #available(iOS 10.2, *), let index = smartAlbumSortingOrder.firstIndex(of: .smartAlbumBursts) {
smartAlbumSortingOrder.insert(.smartAlbumDepthEffect, at: index)
}
if #available(iOS 11, *), let index = smartAlbumSortingOrder.firstIndex(of: .smartAlbumAllHidden) {
smartAlbumSortingOrder.insert(.smartAlbumAnimated, at: index)
}
return smartAlbumSortingOrder
}()
// MARK: - Initializer
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let cancelButtonItem = self.pickerViewController?.customCancelButtonItem() ?? UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: #selector(AlbumsViewController.cancel(_:)))
cancelButtonItem.target = self
cancelButtonItem.action = #selector(cancel(_:))
cancelButtonItem.accessibilityIdentifier = "tatsi.button.cancel"
cancelButtonItem.tintColor = self.config?.colors.link ?? TatsiConfig.default.colors.link
self.navigationItem.rightBarButtonItem = cancelButtonItem
self.navigationItem.backBarButtonItem?.accessibilityIdentifier = "tatsi.button.albums"
self.title = LocalizableStrings.albumsViewTitle
self.tableView.register(AlbumTableViewCell.self, forCellReuseIdentifier: AlbumTableViewCell.reuseIdentifier)
self.tableView.register(AlbumsTableHeaderView.self, forHeaderFooterViewReuseIdentifier: AlbumsTableHeaderView.reuseIdentifier)
self.tableView.rowHeight = 90
self.tableView.separatorInset = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0)
self.tableView.separatorStyle = .none
self.tableView.backgroundColor = self.config?.colors.background ?? TatsiConfig.default.colors.background
self.tableView.accessibilityIdentifier = "tatsi.tableView.albums"
self.startLoadingAlbums()
}
// MARK: - Accessibility
public override func accessibilityPerformEscape() -> Bool {
if self.config?.singleViewMode == true {
return false
} else {
self.cancelPicking()
if self.pickerViewController?.pickerDelegate == nil {
self.dismiss(animated: true, completion: nil)
}
return true
}
}
// MARK: - Fetching
fileprivate func startLoadingAlbums() {
var newCategories = [AlbumCategory]()
let smartAlbums = self.fetchSmartAlbums()
if !smartAlbums.isEmpty {
newCategories.append(AlbumCategory(headerTitle: nil, albums: smartAlbums))
}
let userAlbums = self.fetchUserAlbums()
if !userAlbums.isEmpty {
newCategories.append(AlbumCategory(headerTitle: LocalizableStrings.albumsViewMyAlbumsHeader, albums: userAlbums))
}
if self.config?.showSharedAlbums == true {
let sharedAlbums = self.fetchSharedAlbums()
if !sharedAlbums.isEmpty {
newCategories.append(AlbumCategory(headerTitle: LocalizableStrings.albumsViewSharedAlbumsHeader, albums: sharedAlbums))
}
}
self.categories = newCategories
}
fileprivate func fetchSmartAlbums() -> [PHAssetCollection] {
let collectionResults = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.albumRegular, options: nil)
var collections = [PHAssetCollection]()
collectionResults.enumerateObjects({ (collection, _, _) in
guard self.config?.isCollectionAllowed(collection) == true else {
return
}
collections.append(collection)
})
collections.sort { (collection1, collection2) -> Bool in
guard let index1 = self.smartAlbumSortingOrder.firstIndex(of: collection1.assetCollectionSubtype), let index2 = self.smartAlbumSortingOrder.firstIndex(of: collection2.assetCollectionSubtype) else {
return true
}
return index1 < index2
}
return collections
}
fileprivate func fetchUserAlbums() -> [PHAssetCollection] {
let collectionResults = PHCollectionList.fetchTopLevelUserCollections(with: nil)
var collections = [PHAssetCollection]()
collectionResults.enumerateObjects({ (collection, _, _) in
guard let assetCollection = collection as? PHAssetCollection, self.config?.isCollectionAllowed(collection) == true else {
return
}
collections.append(assetCollection)
})
collections.sort { (collection1, collection2) -> Bool in
guard let title1 = collection1.localizedTitle, let title2 = collection2.localizedTitle else {
return false
}
return title1.compare(title2) == .orderedDescending
}
return collections
}
fileprivate func fetchSharedAlbums() -> [PHAssetCollection] {
let collectionResults = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumCloudShared, options: nil)
var collections = [PHAssetCollection]()
collectionResults.enumerateObjects({ (collection, _, _) in
collections.append(collection)
})
collections.sort { (collection1, collection2) -> Bool in
guard let title1 = collection1.localizedTitle, let title2 = collection2.localizedTitle else {
return false
}
return title1.compare(title2) == .orderedDescending
}
return collections
}
// MARK: - Actions
@objc fileprivate func cancel(_ sender: AnyObject) {
self.cancelPicking()
}
// MARK: - Helpers
fileprivate func category(for section: Int) -> AlbumCategory? {
guard section < self.categories.count else {
return nil
}
return self.categories[section]
}
fileprivate func album(for indexPath: IndexPath) -> PHAssetCollection? {
guard let category = self.category(for: indexPath.section), indexPath.row < category.albums.count else {
return nil
}
return category.albums[indexPath.row]
}
}
// MARK: - UITableViewDataSource
extension AlbumsViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return self.categories.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.category(for: section)?.albums.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: AlbumTableViewCell.reuseIdentifier, for: indexPath) as? AlbumTableViewCell else {
fatalError("AlbumTableViewCell probably not registered")
}
cell.album = self.album(for: indexPath)
cell.reloadContents(with: self.config?.assetFetchOptions())
cell.accessoryType = (self.config?.singleViewMode ?? false) ? .none : .disclosureIndicator
cell.colors = self.config?.colors
return cell
}
}
// MARK: - UITableViewDelegate
extension AlbumsViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let album = self.album(for: indexPath) else {
return
}
if let delegate = self.delegate {
delegate.albumsViewController(self, didSelectAlbum: album)
} else {
let gridViewController = AssetsGridViewController(album: album)
self.navigationController?.pushViewController(gridViewController, animated: true)
}
self.didSelectCollection(album)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let category = self.category(for: section) else {
return nil
}
guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: AlbumsTableHeaderView.reuseIdentifier) as? AlbumsTableHeaderView else {
fatalError("AlbumsTableHeaderView probably not registered")
}
headerView.title = category.headerTitle
headerView.colors = self.config?.colors
return headerView
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard self.category(for: section)?.headerTitle != nil else {
return 0
}
return AlbumsTableHeaderView.height
}
}
| mit | 516195369ab792d6d46c19de75c033cf | 39.388112 | 223 | 0.66886 | 5.451156 | false | false | false | false |
suragch/aePronunciation-iOS | aePronunciation/KeyboardTextKey.swift | 1 | 5574 | import UIKit
@IBDesignable
class KeyboardTextKey: KeyboardKey {
private let primaryLayer = CATextLayer()
private let secondaryLayer = CATextLayer()
let secondaryLayerMargin: CGFloat = 5.0
private var oldFrame = CGRect.zero
private static let selectedTextColor = UIColor.white
private static let disabledTextColor = UIColor.lightGray
private static var normalTextColor = UIColor.systemDefaultTextColor
// MARK: Primary input value
@IBInspectable var primaryString: String = "" {
didSet {
updatePrimaryLayerFrame()
}
}
@IBInspectable var primaryStringFontSize: CGFloat = 17 {
didSet {
updatePrimaryLayerFrame()
}
}
var primaryStringFontColor: UIColor = normalTextColor {
didSet {
updatePrimaryLayerFrame()
}
}
override var isSelected: Bool {
didSet {
if isSelected {
primaryStringFontColor = KeyboardTextKey.selectedTextColor
} else {
primaryStringFontColor = KeyboardTextKey.normalTextColor
}
}
}
override var isEnabled: Bool {
didSet {
if isEnabled {
primaryStringFontColor = KeyboardTextKey.normalTextColor
} else {
primaryStringFontColor = KeyboardTextKey.disabledTextColor
}
}
}
// MARK: Secondary (long press) input value
@IBInspectable var secondaryString: String = "" {
didSet {
updateSecondaryLayerFrame()
}
}
@IBInspectable var secondaryStringFontSize: CGFloat = 12 {
didSet {
updateSecondaryLayerFrame()
}
}
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override var frame: CGRect {
didSet {
// only update frames if non-zero and changed
if frame != CGRect.zero && frame != oldFrame {
updatePrimaryLayerFrame()
updateSecondaryLayerFrame()
oldFrame = frame
}
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 13.0, *) {
if self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
primaryStringFontColor = UIColor.systemDefaultTextColor
}
}
}
func setup() {
// Primary text layer
primaryLayer.contentsScale = UIScreen.main.scale
layer.addSublayer(primaryLayer)
// Secondary text layer
secondaryLayer.contentsScale = UIScreen.main.scale
layer.addSublayer(secondaryLayer)
}
func updatePrimaryLayerFrame() {
let myAttribute: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: primaryStringFontSize),
NSAttributedString.Key.foregroundColor: primaryStringFontColor ]
let attrString = NSMutableAttributedString(string: primaryString, attributes: myAttribute )
let size = dimensionsForAttributedString(attrString)
let x = (layer.bounds.width - size.width) / 2
let y = (layer.bounds.height - size.height) / 2
primaryLayer.frame = CGRect(x: x, y: y, width: size.width, height: size.height)
primaryLayer.string = attrString
}
func updateSecondaryLayerFrame() {
let myAttribute = [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: secondaryStringFontSize) ]
let attrString = NSMutableAttributedString(string: secondaryString, attributes: myAttribute )
let size = dimensionsForAttributedString(attrString)
let x = layer.bounds.width - size.width - secondaryLayerMargin
let y = layer.bounds.height - size.height - secondaryLayerMargin
secondaryLayer.frame = CGRect(x: x, y: y, width: size.width, height: size.height)
secondaryLayer.string = attrString
}
override func longPressBegun(_ guesture: UILongPressGestureRecognizer) {
if self.secondaryString != "" {
delegate?.keyTextEntered(sender: self, keyText: self.secondaryString)
} else {
// enter primary string if this key has no seconary string
delegate?.keyTextEntered(sender: self, keyText: self.primaryString)
}
}
// tap event (do when finger lifted)
override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
delegate?.keyTextEntered(sender: self, keyText: self.primaryString)
}
func dimensionsForAttributedString(_ attrString: NSAttributedString) -> CGSize {
var ascent: CGFloat = 0
var descent: CGFloat = 0
var width: CGFloat = 0
let line: CTLine = CTLineCreateWithAttributedString(attrString)
width = CGFloat(CTLineGetTypographicBounds(line, &ascent, &descent, nil))
// make width an even integer for better graphics rendering
width = ceil(width)
if Int(width)%2 == 1 {
width += 1.0
}
return CGSize(width: width, height: ceil(ascent+descent))
}
}
| unlicense | bd6b4384bceae526a6881041075f7676 | 31.982249 | 109 | 0.617689 | 5.263456 | false | false | false | false |
knutnyg/ios-iou | iou/ProfileViewController.swift | 1 | 1801 |
import Foundation
import UIKit
import SnapKit
class ProfileViewController : UIViewController {
var profileImage:UIImage!
var profileImageView:UIImageView!
var nameLabel:UILabel!
override func viewDidLoad() {
view.backgroundColor = UIColor.whiteColor()
profileImageView = createProfileImageView()
nameLabel = createLabel("")
view.addSubview(profileImageView)
view.addSubview(nameLabel)
let components = [profileImageView, nameLabel]
let rules = [
ConstraintRules()
.snapTop(view.snp_top)
.marginTop(30)
.height(100)
.centerX()
.width(100),
ConstraintRules()
.snapTop(profileImageView.snp_bottom)
.centerX()
]
SnapKitHelpers.setConstraints(view, components: components, rules: rules)
}
override func viewDidAppear(animated: Bool) {
if API.currentUser != nil {
refreshProfile()
}
}
func refreshProfile(){
nameLabel.text = "Welcome \(API.currentUser!.name)"
API.getImageForUser(API.currentUser!).onSuccess{image in
self.profileImageView.image = image
}
}
func createProfileImageView() -> UIImageView {
let profileImage = UIImage(named: "profile.png")
let profileImageView = UIImageView(image: profileImage)
profileImageView.layer.borderWidth = 1.0
profileImageView.layer.masksToBounds = false
profileImageView.layer.borderColor = UIColor.whiteColor().CGColor
profileImageView.layer.cornerRadius = 100/2
profileImageView.clipsToBounds = true
return profileImageView
}
} | bsd-2-clause | 6b791d3a33f4fa9b236501c3f98654b9 | 26.30303 | 81 | 0.609661 | 5.628125 | false | false | false | false |
SASAbus/SASAbus-ios | SASAbus/Data/Networking/Model/CloudTrip.swift | 1 | 1465 | //
// Created by Alex Lardschneider on 05/04/2017.
// Copyright (c) 2017 SASA AG. All rights reserved.
//
import Foundation
import ObjectMapper
class CloudTrip: Mappable, Hashable {
var hash: String!
var lines: [Int]!
var variants: [Int]!
var trips: [Int]!
var vehicle: Int!
var origin: Int!
var destination: Int!
var departure: Int64!
var arrival: Int64!
var path: [Int]!
init(trip: Trip) {
hash = trip.tripHash
lines = trip.getLinesAsList()
variants = trip.getVariantsAsList()
trips = trip.getTripsAsList()
vehicle = trip.vehicle
origin = trip.origin
destination = trip.destination
departure = trip.departure
arrival = trip.arrival
path = trip.path!.components(separatedBy: Config.DELIMITER).map {
Int($0)!
}
}
required init?(map: Map) {
}
func mapping(map: Map) {
hash <- map["hash"]
lines <- map["lines"]
variants <- map["variants"]
trips <- map["trips"]
vehicle <- map["vehicle"]
origin <- map["origin"]
destination <- map["destination"]
departure <- map["departure"]
arrival <- map["arrival"]
path <- map["path"]
}
var hashValue: Int {
return hash.hashValue
}
public static func ==(lhs: CloudTrip, rhs: CloudTrip) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
| gpl-3.0 | 0bfeb6ec18e34ac6c501bdf4fb790ea6 | 20.231884 | 73 | 0.568601 | 4.092179 | false | false | false | false |
jokechat/swift3-novel | swift_novels/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationAudioEqualizer.swift | 8 | 1981 | //
// NVActivityIndicatorAnimationAudioEqualizer.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 6/14/16.
// Copyright © 2016 Nguyen Vinh. All rights reserved.
//
import UIKit
class NVActivityIndicatorAnimationAudioEqualizer: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let lineSize = size.width / 9
let x = (layer.bounds.size.width - lineSize * 7) / 2
let y = (layer.bounds.size.height - size.height) / 2
let duration: [CFTimeInterval] = [4.3, 2.5, 1.7, 3.1]
let values = [0, 0.7, 0.4, 0.05, 0.95, 0.3, 0.9, 0.4, 0.15, 0.18, 0.75, 0.01]
// Draw lines
for i in 0 ..< 4 {
let animation = CAKeyframeAnimation()
animation.keyPath = "path"
animation.isAdditive = true
animation.values = []
for j in 0 ..< values.count {
let heightFactor = values[j]
let height = size.height * CGFloat(heightFactor)
let point = CGPoint(x: 0, y: size.height - height)
let path = UIBezierPath(rect: CGRect(origin: point, size: CGSize(width: lineSize, height: height)))
animation.values?.append(path.cgPath)
}
animation.duration = duration[i]
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
let line = NVActivityIndicatorShape.line.layerWith(size: CGSize(width: lineSize, height: size.height), color: color)
let frame = CGRect(x: x + lineSize * 2 * CGFloat(i),
y: y,
width: lineSize,
height: size.height)
line.frame = frame
line.add(animation, forKey: "animation")
layer.addSublayer(line)
}
}
}
| apache-2.0 | 823fb66aec21ae23dd22530c5e2e4ed9 | 37.823529 | 128 | 0.54596 | 4.5 | false | false | false | false |
grandiere/box | box/View/GridVisorDownload/VGridVisorDownload.swift | 1 | 1920 | import UIKit
class VGridVisorDownload:VView
{
private weak var controller:CGridVisorDownload!
private weak var viewBase:VGridVisorDownloadBase!
private weak var layoutBaseTop:NSLayoutConstraint!
private weak var layoutBaseLeft:NSLayoutConstraint!
private let kBaseSize:CGFloat = 160
private let kAnimationDuration:TimeInterval = 1
override init(controller:CController)
{
super.init(controller:controller)
backgroundColor = UIColor.clear
self.controller = controller as? CGridVisorDownload
let viewBase:VGridVisorDownloadBase = VGridVisorDownloadBase()
viewBase.layer.cornerRadius = kBaseSize / 2.0
self.viewBase = viewBase
addSubview(viewBase)
layoutBaseTop = NSLayoutConstraint.topToTop(
view:viewBase,
toView:self)
layoutBaseLeft = NSLayoutConstraint.leftToLeft(
view:viewBase,
toView:self)
NSLayoutConstraint.size(
view:viewBase,
constant:kBaseSize)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
let width:CGFloat = bounds.maxX
let height:CGFloat = bounds.maxY
let remainWidth:CGFloat = width - kBaseSize
let remainHeight:CGFloat = height - kBaseSize
let marginLeft:CGFloat = remainWidth / 2.0
let marginTop:CGFloat = remainHeight / 2.0
layoutBaseTop.constant = marginTop
layoutBaseLeft.constant = marginLeft
super.layoutSubviews()
}
//MARK: public
func downloaded(model:MGridVisorDownloadProtocol)
{
viewBase.downloadedReady(model:model)
UIView.animate(withDuration:kAnimationDuration)
{ [weak self] in
self?.viewBase.downloadedAnimation()
}
}
}
| mit | a58c59c3f0d41841bb821cf2b05dadd8 | 28.090909 | 70 | 0.638021 | 5.106383 | false | false | false | false |
lllyyy/LY | U17-master/U17/U17/Procedure/Home/View/UUpdateTCell.swift | 1 | 1577 | //
// UUpdateTCell.swift
// U17
//
// Created by charles on 2017/11/10.
// Copyright © 2017年 None. All rights reserved.
//
import UIKit
class UUpdateTCell: UBaseTableViewCell {
private lazy var coverView: UIImageView = {
let cw = UIImageView()
cw.contentMode = .scaleAspectFill
cw.layer.cornerRadius = 5
cw.layer.masksToBounds = true
return cw
}()
private lazy var tipLabel: UILabel = {
let tl = UILabel()
tl.backgroundColor = UIColor.black.withAlphaComponent(0.4)
tl.textColor = UIColor.white
tl.font = UIFont.systemFont(ofSize: 9)
return tl
}()
override func configUI() {
contentView.addSubview(coverView)
coverView.snp.makeConstraints {
$0.edges.equalToSuperview().inset(UIEdgeInsetsMake(10, 10, 20, 10))
}
coverView.addSubview(tipLabel)
tipLabel.snp.makeConstraints {
$0.left.bottom.right.equalToSuperview()
$0.height.equalTo(20)
}
let line = UIView().then{
$0.backgroundColor = UIColor.background
}
contentView.addSubview(line)
line.snp.makeConstraints {
$0.left.right.bottom.equalToSuperview()
$0.height.equalTo(10)
}
}
var model: ComicModel? {
didSet {
guard let model = model else { return }
coverView.kf.setImage(urlString: model.cover)
tipLabel.text = " \(model.description ?? "")"
}
}
}
| mit | 1766ccd50537941cfbb6f5edf1456adf | 25.677966 | 79 | 0.571156 | 4.458924 | false | false | false | false |
BenEmdon/swift-algorithm-club | Boyer-Moore/BoyerMoore.playground/Contents.swift | 1 | 1207 | //: Playground - noun: a place where people can play
extension String {
func indexOf(pattern: String) -> String.Index? {
let patternLength = pattern.characters.count
assert(patternLength > 0)
assert(patternLength <= self.characters.count)
var skipTable = [Character: Int]()
for (i, c) in pattern.characters.enumerated() {
skipTable[c] = patternLength - i - 1
}
let p = pattern.index(before: pattern.endIndex)
let lastChar = pattern[p]
var i = self.index(startIndex, offsetBy: patternLength - 1)
func backwards() -> String.Index? {
var q = p
var j = i
while q > pattern.startIndex {
j = index(before: j)
q = index(before: q)
if self[j] != pattern[q] { return nil }
}
return j
}
while i < self.endIndex {
let c = self[i]
if c == lastChar {
if let k = backwards() { return k }
i = index(after: i)
} else {
i = index(i, offsetBy: skipTable[c] ?? patternLength)
}
}
return nil
}
}
// A few simple tests
let s = "Hello, World"
s.indexOf(pattern: "World") // 7
let animals = "🐶🐔🐷🐮🐱"
animals.indexOf(pattern: "🐮") // 6
| mit | 35c30d6d048e7300f023829e52df5b5c | 23.770833 | 63 | 0.577796 | 3.52819 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/Settings/Menu/ChangeNumber/ChangePhoneNumberController.swift | 1 | 1592 | //
// ChangePhoneNumberController.swift
// Pigeon-project
//
// Created by Roman Mizin on 3/30/18.
// Copyright © 2018 Roman Mizin. All rights reserved.
//
import UIKit
import ARSLineProgress
class ChangePhoneNumberController: PhoneNumberController, VerificationDelegate {
func verificationFinished(with success: Bool, error: String?) {
ARSLineProgress.hide()
guard success, error == nil else {
basicErrorAlertWith(title: "Error", message: error ?? "", controller: self)
return
}
let destination = ChangeNumberVerificationController()
destination.enterVerificationContainerView.titleNumber.text = phoneNumberContainerView.countryCode.text! + phoneNumberContainerView.phoneNumber.text!
navigationController?.pushViewController(destination, animated: true)
}
override func configurePhoneNumberContainerView() {
super.configurePhoneNumberContainerView()
if !DeviceType.isIPad {
let leftBarButton = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(leftBarButtonDidTap))
navigationItem.leftBarButtonItem = leftBarButton
}
phoneNumberContainerView.termsAndPrivacy.isHidden = true
phoneNumberContainerView.instructions.text = "Please confirm your country code\nand enter your NEW phone number."
let attributes = [NSAttributedString.Key.foregroundColor: ThemeManager.currentTheme().generalSubtitleColor]
phoneNumberContainerView.phoneNumber.attributedPlaceholder = NSAttributedString(string: "New phone number", attributes: attributes)
verificationDelegate = self
}
}
| gpl-3.0 | 9fd50377ee9078e25b4b2e984e4bfdd7 | 40.868421 | 153 | 0.77247 | 5.083067 | false | true | false | false |
sandynegi/HeaderImportCountFinder | FileImportCountFinder/main.swift | 1 | 5587 | //
// main.swift
// FileImportCountFinder
//
// Created by Sandeep Negi on 29/05/17.
// Copyright © 2017 Sandeep Negi. All rights reserved.
//
import Foundation
import AppKit
extension Dictionary {
func sortedKeys(isOrderedBefore:(Key,Key) -> Bool) -> [Key] {
return Array(self.keys).sorted(by: isOrderedBefore)
}
// Slower because of a lot of lookups, but probably takes less memory (this is equivalent to Pascals answer in an generic extension)
func sortedKeysByValue(isOrderedBefore:(Value, Value) -> Bool) -> [Key] {
return sortedKeys {
isOrderedBefore(self[$0]!, self[$1]!)
}
}
// Faster because of no lookups, may take more memory because of duplicating contents
func keysSortedByValue(isOrderedBefore:(Value, Value) -> Bool) -> [Key] {
return Array(self)
.sorted() {
let (_, lv) = $0
let (_, rv) = $1
return isOrderedBefore(lv, rv)
}
.map {
let (k, _) = $0
return k
}
}
}
extension FileManager {
func listFiles(path: String) -> [URL] {
let baseurl: URL = URL(fileURLWithPath: path)
var urls = [URL]()
enumerator(atPath: path)?.forEach({ (e) in
guard let s = e as? String else { return }
if includeFile(filename:s) /*&& !childOfIgnoreDir(dirName:s)*/ {
let relativeURL = URL(fileURLWithPath: s, relativeTo: baseurl)
let url = relativeURL.absoluteURL
urls.append(url)
}
})
return urls
}
func childOfIgnoreDir(dirName:String) -> Bool {
let ignoreFolderList = ["Libs"]
for item in ignoreFolderList {
if dirName.range(of: item, options: .caseInsensitive) != nil {
return true
}
}
return false
}
func includeFile(filename:String) -> Bool {
return filename.hasSuffix(".h") || filename.hasSuffix(".m")
}
}
extension Data {
var attributedString: NSAttributedString? {
do {
return try NSAttributedString(data: self, options: [ NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.plain, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
}
return nil
}
}
class HeaderImportFinder {
var dirPath:String = ""
func search() {
let mypath = dirPath
let fm = FileManager()
let arr = fm.listFiles(path: mypath)
var currentProcessingItemIndex = 0
var countDict = Dictionary<String, Int>()
for item in arr {
autoreleasepool {
do {
// Read file content
var dataObj:Data? = try Data(contentsOf:item)
var attibutedString = dataObj!.attributedString
var contentFromFile = attibutedString?.string
let count = arr.count - 1
for i in 0...count {
autoreleasepool {
if arr[i].absoluteString.hasSuffix(".h") {
let searchQuery = "#import \u{22}" + arr[i].lastPathComponent + "\u{22}"
let isContain = contentFromFile?.contains(searchQuery)
if isContain! {
let previousCount = countDict[searchQuery] ?? 0
countDict[searchQuery] = 1 + previousCount
}
}
}
}
dataObj = nil
attibutedString = nil
contentFromFile = nil
}
catch let error as NSError {
print("An error took place: \(error)")
}
let donePercentage = CGFloat((currentProcessingItemIndex+1)*100)/CGFloat(arr.count)
print(String(format: "Work done ... %.2f%%", donePercentage))
currentProcessingItemIndex += 1
}
}
let sortedKeys = countDict.keysSortedByValue(isOrderedBefore: <) //sorting dictionary
print("Import count + sorted result")
for item in sortedKeys {
print(item + " ====> " + String(countDict[item]!))
}
}
func cleanFilePath(path: String) -> String {
let trimmedPath = path.trimmingCharacters(in: .whitespacesAndNewlines)
let pathWithoutEscapedWhitespaces = trimmedPath.replacingOccurrences(of:"\\ ", with: " ")
return pathWithoutEscapedWhitespaces
}
func getDirPath(){
let response:String? = CommandLine.arguments[1];
if nil != response && 0 < (response?.count)! {
dirPath = cleanFilePath(path: response!)
}else{
print("Invlaid path input")
}
}
}
let finderObj = HeaderImportFinder()
finderObj.getDirPath()
let sema = DispatchSemaphore( value: 0)
DispatchQueue.global(qos: .background).async {
finderObj.search()
sema.signal();
}
sema.wait();
| gpl-3.0 | b87061fa44f2e2e4228910038f3343e9 | 32.25 | 282 | 0.524884 | 5.106033 | false | false | false | false |
idapgroup/IDPDesign | Tests/iOS/Pods/Nimble/Sources/Nimble/Adapters/NMBObjCMatcher.swift | 18 | 3558 | import Foundation
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
// swiftlint:disable line_length
public typealias MatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage) throws -> Bool
public typealias FullMatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage, _ shouldNotMatch: Bool) throws -> Bool
// swiftlint:enable line_length
public class NMBObjCMatcher: NSObject, NMBMatcher {
let _match: MatcherBlock
let _doesNotMatch: MatcherBlock
let canMatchNil: Bool
public init(canMatchNil: Bool, matcher: @escaping MatcherBlock, notMatcher: @escaping MatcherBlock) {
self.canMatchNil = canMatchNil
self._match = matcher
self._doesNotMatch = notMatcher
}
public convenience init(matcher: @escaping MatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
public convenience init(canMatchNil: Bool, matcher: @escaping MatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: matcher, notMatcher: ({ actualExpression, failureMessage in
return try !matcher(actualExpression, failureMessage)
}))
}
public convenience init(matcher: @escaping FullMatcherBlock) {
self.init(canMatchNil: true, matcher: matcher)
}
public convenience init(canMatchNil: Bool, matcher: @escaping FullMatcherBlock) {
self.init(canMatchNil: canMatchNil, matcher: ({ actualExpression, failureMessage in
return try matcher(actualExpression, failureMessage, false)
}), notMatcher: ({ actualExpression, failureMessage in
return try matcher(actualExpression, failureMessage, true)
}))
}
private func canMatch(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
do {
if !canMatchNil {
if try actualExpression.evaluate() == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
return false
}
}
} catch let error {
failureMessage.actualValue = "an unexpected error thrown: \(error)"
return false
}
return true
}
public func matches(_ actualBlock: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: location)
let result: Bool
do {
result = try _match(expr, failureMessage)
} catch let error {
failureMessage.stringValue = "unexpected error thrown: <\(error)>"
return false
}
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
public func doesNotMatch(_ actualBlock: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let expr = Expression(expression: actualBlock, location: location)
let result: Bool
do {
result = try _doesNotMatch(expr, failureMessage)
} catch let error {
failureMessage.stringValue = "unexpected error thrown: <\(error)>"
return false
}
if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) {
return result
} else {
return false
}
}
}
#endif
| bsd-3-clause | 47da98b276de288937b425aede0c5599 | 37.258065 | 151 | 0.645025 | 5.42378 | false | false | false | false |
WildDogTeam/lib-ios-streambase | StreamBaseExample/Message.swift | 1 | 591 | //
// Message.swift
// StreamBaseExample
//
// Created by IMacLi on 15/11/2.
// Copyright © 2015年 liwuyang. All rights reserved.
//
import Foundation
import Wilddog
class Message : BaseItem {
var text: String?
var username: String?
override func update(dict: [String : AnyObject]?) {
super.update(dict)
text = dict?["text"] as? String
username = dict?["username"] as? String
}
override var dict: [String: AnyObject] {
var d = super.dict
d["text"] = text
d["username"] = username
return d
}
} | mit | a4ab9d17378f2eddb54f51f0e56a2db9 | 19.310345 | 55 | 0.586735 | 3.745223 | false | false | false | false |
honishi/Hakumai | Hakumai/OAuthCredential.sample.swift | 1 | 573 | //
// OAuthCredential.sample.swift
// Hakumai
//
// Created by Hiroyuki Onishi on 2021/07/16.
// Copyright © 2021 Hiroyuki Onishi. All rights reserved.
//
import Foundation
let hakumaiClientId = "XXXXX"
let hakumaiServerApiBaseUrl = "https://api.host"
let hakumaiServerApiPathRefreshToken = "/path/to/refresh-token"
let devAuthCallbackUrl = "https://dev.api.host/oauth-callback"
let devHakumaiServerApiBaseUrl = "https://dev.api.host"
let useDevServer = false
// swift/lint:disable line_length
let debugExpiredAccessToken = "XXXXX"
// swift/lint:enable line_length
| mit | 7077f3b4aec6096ad7fd03a846438b0c | 27.6 | 63 | 0.76049 | 3.231638 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Editor/Controller/Photo/PhotoEditorViewController+BrushColorView.swift | 1 | 3001 | //
// PhotoEditorViewController+BrushColorView.swift
// HXPHPicker
//
// Created by Slience on 2021/11/15.
//
import UIKit
extension PhotoEditorViewController: PhotoEditorBrushColorViewDelegate {
func brushColorView(didUndoButton colorView: PhotoEditorBrushColorView) {
imageView.undoDraw()
brushColorView.canUndo = imageView.canUndoDraw
}
func brushColorView(_ colorView: PhotoEditorBrushColorView, changedColor colorHex: String) {
imageView.drawColorHex = colorHex
}
func brushColorView(_ colorView: PhotoEditorBrushColorView, changedColor color: UIColor) {
imageView.drawColor = color
}
func brushColorView(touchDown colorView: PhotoEditorBrushColorView) {
let lineWidth = imageView.brushLineWidth + 4
brushSizeView.size = CGSize(width: lineWidth, height: lineWidth)
brushSizeView.center = CGPoint(x: view.width * 0.5, y: view.height * 0.5)
brushSizeView.alpha = 0
view.addSubview(brushSizeView)
UIView.animate(withDuration: 0.2) {
self.brushSizeView.alpha = 1
}
}
func brushColorView(touchUpOutside colorView: PhotoEditorBrushColorView) {
UIView.animate(withDuration: 0.2) {
self.brushSizeView.alpha = 0
} completion: { _ in
self.brushSizeView.removeFromSuperview()
}
}
func brushColorView(
_ colorView: PhotoEditorBrushColorView,
didChangedBrushLine lineWidth: CGFloat
) {
imageView.brushLineWidth = lineWidth
brushSizeView.size = CGSize(width: lineWidth + 4, height: lineWidth + 4)
brushSizeView.center = CGPoint(x: view.width * 0.5, y: view.height * 0.5)
}
class BrushSizeView: UIView {
lazy var borderLayer: CAShapeLayer = {
let borderLayer = CAShapeLayer()
borderLayer.strokeColor = UIColor.white.cgColor
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.lineWidth = 2
borderLayer.shadowColor = UIColor.black.withAlphaComponent(0.4).cgColor
borderLayer.shadowRadius = 2
borderLayer.shadowOpacity = 0.5
borderLayer.shadowOffset = CGSize(width: 0, height: 0)
return borderLayer
}()
override init(frame: CGRect) {
super.init(frame: frame)
layer.addSublayer(borderLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
borderLayer.frame = bounds
let path = UIBezierPath(
arcCenter: CGPoint(x: width * 0.5, y: height * 0.5),
radius: width * 0.5 - 1,
startAngle: 0,
endAngle: CGFloat.pi * 2,
clockwise: true
)
borderLayer.path = path.cgPath
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
| mit | ae15c65e7ee64f795ed29f9a9495d20d | 35.156627 | 96 | 0.618127 | 4.863857 | false | false | false | false |
Rehsco/StyledOverlay | StyledOverlay/StyledLabelsOverlay.swift | 1 | 2140 | //
// StyledLabelsOverlay.swift
// StyledOverlay
//
// Created by Martin Rehder on 22.10.2016.
/*
* Copyright 2016-present Martin Jacob Rehder.
* http://www.rehsco.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
import StyledLabel
open class StyledLabelsOverlay: StyledBase3Overlay {
open var upperLabel = StyledLabel()
open var centerLabel = StyledLabel()
open var lowerLabel = StyledLabel()
override func initView() {
super.initView()
self.initLabels()
}
func initLabels() {
self.upperView.addSubview(self.upperLabel)
self.centerView.addSubview(self.centerLabel)
self.lowerView.addSubview(self.lowerLabel)
self.upperLabel.textAlignment = .center
self.centerLabel.textAlignment = .center
self.lowerLabel.textAlignment = .center
}
open override func layoutViews() {
super.layoutViews()
self.upperLabel.frame = self.upperView.bounds
self.centerLabel.frame = self.centerView.bounds
self.lowerLabel.frame = self.lowerView.bounds
}
}
| mit | 572a60bd3e6d49df231fd5a726da5fd4 | 35.271186 | 80 | 0.719159 | 4.403292 | false | false | false | false |
briandw/SwiftFighter | SwiftFighter/WebSocket.swift | 2 | 68044 | /*
* SwiftWebSocket (websocket.swift)
*
* Copyright (C) Josh Baker. All Rights Reserved.
* Contact: @tidwall, [email protected]
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
*/
import Foundation
private let windowBufferSize = 0x2000
private class Payload {
var ptr : UnsafeMutablePointer<UInt8>
var cap : Int
var len : Int
init(){
len = 0
cap = windowBufferSize
ptr = UnsafeMutablePointer<UInt8>(malloc(cap))
}
deinit{
free(ptr)
}
var count : Int {
get {
return len
}
set {
if newValue > cap {
while cap < newValue {
cap *= 2
}
ptr = UnsafeMutablePointer<UInt8>(realloc(ptr, cap))
}
len = newValue
}
}
func append(bytes: UnsafePointer<UInt8>, length: Int){
let prevLen = len
count = len+length
memcpy(ptr+prevLen, bytes, length)
}
var array : [UInt8] {
get {
var array = [UInt8](count: count, repeatedValue: 0)
memcpy(&array, ptr, count)
return array
}
set {
count = 0
append(newValue, length: newValue.count)
}
}
var nsdata : NSData {
get {
return NSData(bytes: ptr, length: count)
}
set {
count = 0
append(UnsafePointer<UInt8>(newValue.bytes), length: newValue.length)
}
}
var buffer : UnsafeBufferPointer<UInt8> {
get {
return UnsafeBufferPointer<UInt8>(start: ptr, count: count)
}
set {
count = 0
append(newValue.baseAddress, length: newValue.count)
}
}
}
private enum OpCode : UInt8, CustomStringConvertible {
case Continue = 0x0, Text = 0x1, Binary = 0x2, Close = 0x8, Ping = 0x9, Pong = 0xA
var isControl : Bool {
switch self {
case .Close, .Ping, .Pong:
return true
default:
return false
}
}
var description : String {
switch self {
case Continue: return "Continue"
case Text: return "Text"
case Binary: return "Binary"
case Close: return "Close"
case Ping: return "Ping"
case Pong: return "Pong"
}
}
}
/// The WebSocketEvents struct is used by the events property and manages the events for the WebSocket connection.
public struct WebSocketEvents {
/// An event to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data.
public var open : ()->() = {}
/// An event to be called when the WebSocket connection's readyState changes to .Closed.
public var close : (code : Int, reason : String, wasClean : Bool)->() = {(code, reason, wasClean) in}
/// An event to be called when an error occurs.
public var error : (error : ErrorType)->() = {(error) in}
/// An event to be called when a message is received from the server.
public var message : (data : Any)->() = {(data) in}
/// An event to be called when a pong is received from the server.
public var pong : (data : Any)->() = {(data) in}
/// An event to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events.
public var end : (code : Int, reason : String, wasClean : Bool, error : ErrorType?)->() = {(code, reason, wasClean, error) in}
}
/// The WebSocketBinaryType enum is used by the binaryType property and indicates the type of binary data being transmitted by the WebSocket connection.
public enum WebSocketBinaryType : CustomStringConvertible {
/// The WebSocket should transmit [UInt8] objects.
case UInt8Array
/// The WebSocket should transmit NSData objects.
case NSData
/// The WebSocket should transmit UnsafeBufferPointer<UInt8> objects. This buffer is only valid during the scope of the message event. Use at your own risk.
case UInt8UnsafeBufferPointer
public var description : String {
switch self {
case UInt8Array: return "UInt8Array"
case NSData: return "NSData"
case UInt8UnsafeBufferPointer: return "UInt8UnsafeBufferPointer"
}
}
}
/// The WebSocketReadyState enum is used by the readyState property to describe the status of the WebSocket connection.
@objc public enum WebSocketReadyState : Int, CustomStringConvertible {
/// The connection is not yet open.
case Connecting = 0
/// The connection is open and ready to communicate.
case Open = 1
/// The connection is in the process of closing.
case Closing = 2
/// The connection is closed or couldn't be opened.
case Closed = 3
private var isClosed : Bool {
switch self {
case .Closing, .Closed:
return true
default:
return false
}
}
/// Returns a string that represents the ReadyState value.
public var description : String {
switch self {
case Connecting: return "Connecting"
case Open: return "Open"
case Closing: return "Closing"
case Closed: return "Closed"
}
}
}
private let defaultMaxWindowBits = 15
/// The WebSocketCompression struct is used by the compression property and manages the compression options for the WebSocket connection.
public struct WebSocketCompression {
/// Used to accept compressed messages from the server. Default is true.
public var on = false
/// request no context takeover.
public var noContextTakeover = false
/// request max window bits.
public var maxWindowBits = defaultMaxWindowBits
}
/// The WebSocketService options are used by the services property and manages the underlying socket services.
public struct WebSocketService : OptionSetType {
public typealias RawValue = UInt
var value: UInt = 0
init(_ value: UInt) { self.value = value }
public init(rawValue value: UInt) { self.value = value }
public init(nilLiteral: ()) { self.value = 0 }
public static var allZeros: WebSocketService { return self.init(0) }
static func fromMask(raw: UInt) -> WebSocketService { return self.init(raw) }
public var rawValue: UInt { return self.value }
/// No services.
public static var None: WebSocketService { return self.init(0) }
/// Allow socket to handle VoIP.
public static var VoIP: WebSocketService { return self.init(1 << 0) }
/// Allow socket to handle video.
public static var Video: WebSocketService { return self.init(1 << 1) }
/// Allow socket to run in background.
public static var Background: WebSocketService { return self.init(1 << 2) }
/// Allow socket to handle voice.
public static var Voice: WebSocketService { return self.init(1 << 3) }
}
private let atEndDetails = "streamStatus.atEnd"
private let timeoutDetails = "The operation couldn’t be completed. Operation timed out"
private let timeoutDuration : CFTimeInterval = 30
public enum WebSocketError : ErrorType, CustomStringConvertible {
case Memory
case NeedMoreInput
case InvalidHeader
case InvalidAddress
case Network(String)
case LibraryError(String)
case PayloadError(String)
case ProtocolError(String)
case InvalidResponse(String)
case InvalidCompressionOptions(String)
public var description : String {
switch self {
case .Memory: return "Memory"
case .NeedMoreInput: return "NeedMoreInput"
case .InvalidAddress: return "InvalidAddress"
case .InvalidHeader: return "InvalidHeader"
case let .InvalidResponse(details): return "InvalidResponse(\(details))"
case let .InvalidCompressionOptions(details): return "InvalidCompressionOptions(\(details))"
case let .LibraryError(details): return "LibraryError(\(details))"
case let .ProtocolError(details): return "ProtocolError(\(details))"
case let .PayloadError(details): return "PayloadError(\(details))"
case let .Network(details): return "Network(\(details))"
}
}
public var details : String {
switch self {
case .InvalidResponse(let details): return details
case .InvalidCompressionOptions(let details): return details
case .LibraryError(let details): return details
case .ProtocolError(let details): return details
case .PayloadError(let details): return details
case .Network(let details): return details
default: return ""
}
}
}
private class UTF8 {
var text : String = ""
var count : UInt32 = 0 // number of bytes
var procd : UInt32 = 0 // number of bytes processed
var codepoint : UInt32 = 0 // the actual codepoint
var bcount = 0
init() { text = "" }
func append(byte : UInt8) throws {
if count == 0 {
if byte <= 0x7F {
text.append(UnicodeScalar(byte))
return
}
if byte == 0xC0 || byte == 0xC1 {
throw WebSocketError.PayloadError("invalid codepoint: invalid byte")
}
if byte >> 5 & 0x7 == 0x6 {
count = 2
} else if byte >> 4 & 0xF == 0xE {
count = 3
} else if byte >> 3 & 0x1F == 0x1E {
count = 4
} else {
throw WebSocketError.PayloadError("invalid codepoint: frames")
}
procd = 1
codepoint = (UInt32(byte) & (0xFF >> count)) << ((count-1) * 6)
return
}
if byte >> 6 & 0x3 != 0x2 {
throw WebSocketError.PayloadError("invalid codepoint: signature")
}
codepoint += UInt32(byte & 0x3F) << ((count-procd-1) * 6)
if codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF) {
throw WebSocketError.PayloadError("invalid codepoint: out of bounds")
}
procd += 1
if procd == count {
if codepoint <= 0x7FF && count > 2 {
throw WebSocketError.PayloadError("invalid codepoint: overlong")
}
if codepoint <= 0xFFFF && count > 3 {
throw WebSocketError.PayloadError("invalid codepoint: overlong")
}
procd = 0
count = 0
text.append(UnicodeScalar(codepoint))
}
return
}
func append(bytes : UnsafePointer<UInt8>, length : Int) throws {
if length == 0 {
return
}
if count == 0 {
var ascii = true
for i in 0 ..< length {
if bytes[i] > 0x7F {
ascii = false
break
}
}
if ascii {
text += NSString(bytes: bytes, length: length, encoding: NSASCIIStringEncoding) as! String
bcount += length
return
}
}
for i in 0 ..< length {
try append(bytes[i])
}
bcount += length
}
var completed : Bool {
return count == 0
}
static func bytes(string : String) -> [UInt8]{
let data = string.dataUsingEncoding(NSUTF8StringEncoding)!
return [UInt8](UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(data.bytes), count: data.length))
}
static func string(bytes : [UInt8]) -> String{
if let str = NSString(bytes: bytes, length: bytes.count, encoding: NSUTF8StringEncoding) {
return str as String
}
return ""
}
}
private class Frame {
var inflate = false
var code = OpCode.Continue
var utf8 = UTF8()
var payload = Payload()
var statusCode = UInt16(0)
var finished = true
static func makeClose(statusCode: UInt16, reason: String) -> Frame {
let f = Frame()
f.code = .Close
f.statusCode = statusCode
f.utf8.text = reason
return f
}
func copy() -> Frame {
let f = Frame()
f.code = code
f.utf8.text = utf8.text
f.payload.buffer = payload.buffer
f.statusCode = statusCode
f.finished = finished
f.inflate = inflate
return f
}
}
private class Delegate : NSObject, NSStreamDelegate {
@objc func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent){
manager.signal()
}
}
@_silgen_name("zlibVersion") private func zlibVersion() -> COpaquePointer
@_silgen_name("deflateInit2_") private func deflateInit2(strm : UnsafeMutablePointer<Void>, level : CInt, method : CInt, windowBits : CInt, memLevel : CInt, strategy : CInt, version : COpaquePointer, stream_size : CInt) -> CInt
@_silgen_name("deflateInit_") private func deflateInit(strm : UnsafeMutablePointer<Void>, level : CInt, version : COpaquePointer, stream_size : CInt) -> CInt
@_silgen_name("deflateEnd") private func deflateEnd(strm : UnsafeMutablePointer<Void>) -> CInt
@_silgen_name("deflate") private func deflate(strm : UnsafeMutablePointer<Void>, flush : CInt) -> CInt
@_silgen_name("inflateInit2_") private func inflateInit2(strm : UnsafeMutablePointer<Void>, windowBits : CInt, version : COpaquePointer, stream_size : CInt) -> CInt
@_silgen_name("inflateInit_") private func inflateInit(strm : UnsafeMutablePointer<Void>, version : COpaquePointer, stream_size : CInt) -> CInt
@_silgen_name("inflate") private func inflateG(strm : UnsafeMutablePointer<Void>, flush : CInt) -> CInt
@_silgen_name("inflateEnd") private func inflateEndG(strm : UnsafeMutablePointer<Void>) -> CInt
private func zerror(res : CInt) -> ErrorType? {
var err = ""
switch res {
case 0: return nil
case 1: err = "stream end"
case 2: err = "need dict"
case -1: err = "errno"
case -2: err = "stream error"
case -3: err = "data error"
case -4: err = "mem error"
case -5: err = "buf error"
case -6: err = "version error"
default: err = "undefined error"
}
return WebSocketError.PayloadError("zlib: \(err): \(res)")
}
private struct z_stream {
var next_in : UnsafePointer<UInt8> = nil
var avail_in : CUnsignedInt = 0
var total_in : CUnsignedLong = 0
var next_out : UnsafeMutablePointer<UInt8> = nil
var avail_out : CUnsignedInt = 0
var total_out : CUnsignedLong = 0
var msg : UnsafePointer<CChar> = nil
var state : COpaquePointer = nil
var zalloc : COpaquePointer = nil
var zfree : COpaquePointer = nil
var opaque : COpaquePointer = nil
var data_type : CInt = 0
var adler : CUnsignedLong = 0
var reserved : CUnsignedLong = 0
}
private class Inflater {
var windowBits = 0
var strm = z_stream()
var tInput = [[UInt8]]()
var inflateEnd : [UInt8] = [0x00, 0x00, 0xFF, 0xFF]
var bufferSize = windowBufferSize
var buffer = UnsafeMutablePointer<UInt8>(malloc(windowBufferSize))
init?(windowBits : Int){
if buffer == nil {
return nil
}
self.windowBits = windowBits
let ret = inflateInit2(&strm, windowBits: -CInt(windowBits), version: zlibVersion(), stream_size: CInt(sizeof(z_stream)))
if ret != 0 {
return nil
}
}
deinit{
inflateEndG(&strm)
free(buffer)
}
func inflate(bufin : UnsafePointer<UInt8>, length : Int, final : Bool) throws -> (p : UnsafeMutablePointer<UInt8>, n : Int){
var buf = buffer
var bufsiz = bufferSize
var buflen = 0
for i in 0 ..< 2{
if i == 0 {
strm.avail_in = CUnsignedInt(length)
strm.next_in = UnsafePointer<UInt8>(bufin)
} else {
if !final {
break
}
strm.avail_in = CUnsignedInt(inflateEnd.count)
strm.next_in = UnsafePointer<UInt8>(inflateEnd)
}
while true {
strm.avail_out = CUnsignedInt(bufsiz)
strm.next_out = buf
inflateG(&strm, flush: 0)
let have = bufsiz - Int(strm.avail_out)
bufsiz -= have
buflen += have
if strm.avail_out != 0{
break
}
if bufsiz == 0 {
bufferSize *= 2
let nbuf = UnsafeMutablePointer<UInt8>(realloc(buffer, bufferSize))
if nbuf == nil {
throw WebSocketError.PayloadError("memory")
}
buffer = nbuf
buf = buffer+Int(buflen)
bufsiz = bufferSize - buflen
}
}
}
return (buffer, buflen)
}
}
private class Deflater {
var windowBits = 0
var memLevel = 0
var strm = z_stream()
var bufferSize = windowBufferSize
var buffer = UnsafeMutablePointer<UInt8>(malloc(windowBufferSize))
init?(windowBits : Int, memLevel : Int){
if buffer == nil {
return nil
}
self.windowBits = windowBits
self.memLevel = memLevel
let ret = deflateInit2(&strm, level: 6, method: 8, windowBits: -CInt(windowBits), memLevel: CInt(memLevel), strategy: 0, version: zlibVersion(), stream_size: CInt(sizeof(z_stream)))
if ret != 0 {
return nil
}
}
deinit{
deflateEnd(&strm)
free(buffer)
}
func deflate(bufin : UnsafePointer<UInt8>, length : Int, final : Bool) -> (p : UnsafeMutablePointer<UInt8>, n : Int, err : NSError?){
return (nil, 0, nil)
}
}
/// WebSocketDelegate is an Objective-C alternative to WebSocketEvents and is used to delegate the events for the WebSocket connection.
@objc public protocol WebSocketDelegate {
/// A function to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data.
func webSocketOpen()
/// A function to be called when the WebSocket connection's readyState changes to .Closed.
func webSocketClose(code: Int, reason: String, wasClean: Bool)
/// A function to be called when an error occurs.
func webSocketError(error: NSError)
/// A function to be called when a message (string) is received from the server.
optional func webSocketMessageText(text: String)
/// A function to be called when a message (binary) is received from the server.
optional func webSocketMessageData(data: NSData)
/// A function to be called when a pong is received from the server.
optional func webSocketPong()
/// A function to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events.
optional func webSocketEnd(code: Int, reason: String, wasClean: Bool, error: NSError?)
}
/// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455.
private class InnerWebSocket: Hashable {
var id : Int
var mutex = pthread_mutex_t()
let request : NSURLRequest!
let subProtocols : [String]!
var frames : [Frame] = []
var delegate : Delegate
var inflater : Inflater!
var deflater : Deflater!
var outputBytes : UnsafeMutablePointer<UInt8>
var outputBytesSize : Int = 0
var outputBytesStart : Int = 0
var outputBytesLength : Int = 0
var inputBytes : UnsafeMutablePointer<UInt8>
var inputBytesSize : Int = 0
var inputBytesStart : Int = 0
var inputBytesLength : Int = 0
var createdAt = CFAbsoluteTimeGetCurrent()
var connectionTimeout = false
var eclose : ()->() = {}
var _eventQueue : dispatch_queue_t? = dispatch_get_main_queue()
var _subProtocol = ""
var _compression = WebSocketCompression()
var _allowSelfSignedSSL = false
var _services = WebSocketService.None
var _event = WebSocketEvents()
var _eventDelegate: WebSocketDelegate?
var _binaryType = WebSocketBinaryType.UInt8Array
var _readyState = WebSocketReadyState.Connecting
var _networkTimeout = NSTimeInterval(-1)
var url : String {
return request.URL!.description
}
var subProtocol : String {
get { return privateSubProtocol }
}
var privateSubProtocol : String {
get { lock(); defer { unlock() }; return _subProtocol }
set { lock(); defer { unlock() }; _subProtocol = newValue }
}
var compression : WebSocketCompression {
get { lock(); defer { unlock() }; return _compression }
set { lock(); defer { unlock() }; _compression = newValue }
}
var allowSelfSignedSSL : Bool {
get { lock(); defer { unlock() }; return _allowSelfSignedSSL }
set { lock(); defer { unlock() }; _allowSelfSignedSSL = newValue }
}
var services : WebSocketService {
get { lock(); defer { unlock() }; return _services }
set { lock(); defer { unlock() }; _services = newValue }
}
var event : WebSocketEvents {
get { lock(); defer { unlock() }; return _event }
set { lock(); defer { unlock() }; _event = newValue }
}
var eventDelegate : WebSocketDelegate? {
get { lock(); defer { unlock() }; return _eventDelegate }
set { lock(); defer { unlock() }; _eventDelegate = newValue }
}
var eventQueue : dispatch_queue_t? {
get { lock(); defer { unlock() }; return _eventQueue; }
set { lock(); defer { unlock() }; _eventQueue = newValue }
}
var binaryType : WebSocketBinaryType {
get { lock(); defer { unlock() }; return _binaryType }
set { lock(); defer { unlock() }; _binaryType = newValue }
}
var readyState : WebSocketReadyState {
get { return privateReadyState }
}
var privateReadyState : WebSocketReadyState {
get { lock(); defer { unlock() }; return _readyState }
set { lock(); defer { unlock() }; _readyState = newValue }
}
func copyOpen(request: NSURLRequest, subProtocols : [String] = []) -> InnerWebSocket{
let ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: false)
ws.eclose = eclose
ws.compression = compression
ws.allowSelfSignedSSL = allowSelfSignedSSL
ws.services = services
ws.event = event
ws.eventQueue = eventQueue
ws.binaryType = binaryType
return ws
}
var hashValue: Int { return id }
init(request: NSURLRequest, subProtocols : [String] = [], stub : Bool = false){
pthread_mutex_init(&mutex, nil)
self.id = manager.nextId()
self.request = request
self.subProtocols = subProtocols
self.outputBytes = UnsafeMutablePointer<UInt8>.alloc(windowBufferSize)
self.outputBytesSize = windowBufferSize
self.inputBytes = UnsafeMutablePointer<UInt8>.alloc(windowBufferSize)
self.inputBytesSize = windowBufferSize
self.delegate = Delegate()
if stub{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), manager.queue){
self
}
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), manager.queue){
manager.add(self)
}
}
}
deinit{
if outputBytes != nil {
free(outputBytes)
}
if inputBytes != nil {
free(inputBytes)
}
pthread_mutex_init(&mutex, nil)
}
@inline(__always) private func lock(){
pthread_mutex_lock(&mutex)
}
@inline(__always) private func unlock(){
pthread_mutex_unlock(&mutex)
}
private var dirty : Bool {
lock()
defer { unlock() }
if exit {
return false
}
if connectionTimeout {
return true
}
if stage != .ReadResponse && stage != .HandleFrames {
return true
}
if rd.streamStatus == .Opening && wr.streamStatus == .Opening {
return false;
}
if rd.streamStatus != .Open || wr.streamStatus != .Open {
return true
}
if rd.streamError != nil || wr.streamError != nil {
return true
}
if rd.hasBytesAvailable || frames.count > 0 || inputBytesLength > 0 {
return true
}
if outputBytesLength > 0 && wr.hasSpaceAvailable{
return true
}
return false
}
enum Stage : Int {
case OpenConn
case ReadResponse
case HandleFrames
case CloseConn
case End
}
var stage = Stage.OpenConn
var rd : NSInputStream!
var wr : NSOutputStream!
var atEnd = false
var closeCode = UInt16(0)
var closeReason = ""
var closeClean = false
var closeFinal = false
var finalError : ErrorType?
var exit = false
var more = true
func step(){
if exit {
return
}
do {
try stepBuffers(more)
try stepStreamErrors()
more = false
switch stage {
case .OpenConn:
try openConn()
stage = .ReadResponse
case .ReadResponse:
try readResponse()
privateReadyState = .Open
fire {
self.event.open()
self.eventDelegate?.webSocketOpen()
}
stage = .HandleFrames
case .HandleFrames:
try stepOutputFrames()
if closeFinal {
privateReadyState = .Closing
stage = .CloseConn
return
}
let frame = try readFrame()
switch frame.code {
case .Text:
fire {
self.event.message(data: frame.utf8.text)
self.eventDelegate?.webSocketMessageText?(frame.utf8.text)
}
case .Binary:
fire {
switch self.binaryType {
case .UInt8Array:
self.event.message(data: frame.payload.array)
case .NSData:
self.event.message(data: frame.payload.nsdata)
// The WebSocketDelegate is necessary to add Objective-C compability and it is only possible to send binary data with NSData.
self.eventDelegate?.webSocketMessageData?(frame.payload.nsdata)
case .UInt8UnsafeBufferPointer:
self.event.message(data: frame.payload.buffer)
}
}
case .Ping:
let nframe = frame.copy()
nframe.code = .Pong
lock()
frames += [nframe]
unlock()
case .Pong:
fire {
switch self.binaryType {
case .UInt8Array:
self.event.pong(data: frame.payload.array)
case .NSData:
self.event.pong(data: frame.payload.nsdata)
case .UInt8UnsafeBufferPointer:
self.event.pong(data: frame.payload.buffer)
}
self.eventDelegate?.webSocketPong?()
}
case .Close:
lock()
frames += [frame]
unlock()
default:
break
}
case .CloseConn:
if let error = finalError {
self.event.error(error: error)
self.eventDelegate?.webSocketError(error as NSError)
}
privateReadyState = .Closed
if rd != nil {
closeConn()
fire {
self.eclose()
self.event.close(code: Int(self.closeCode), reason: self.closeReason, wasClean: self.closeFinal)
self.eventDelegate?.webSocketClose(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeFinal)
}
}
stage = .End
case .End:
fire {
self.event.end(code: Int(self.closeCode), reason: self.closeReason, wasClean: self.closeClean, error: self.finalError)
self.eventDelegate?.webSocketEnd?(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeClean, error: self.finalError as? NSError)
}
exit = true
manager.remove(self)
}
} catch WebSocketError.NeedMoreInput {
more = true
} catch {
if finalError != nil {
return
}
finalError = error
if stage == .OpenConn || stage == .ReadResponse {
stage = .CloseConn
} else {
var frame : Frame?
if let error = error as? WebSocketError{
switch error {
case .Network(let details):
if details == atEndDetails{
stage = .CloseConn
frame = Frame.makeClose(1006, reason: "Abnormal Closure")
atEnd = true
finalError = nil
}
case .ProtocolError:
frame = Frame.makeClose(1002, reason: "Protocol error")
case .PayloadError:
frame = Frame.makeClose(1007, reason: "Payload error")
default:
break
}
}
if frame == nil {
frame = Frame.makeClose(1006, reason: "Abnormal Closure")
}
if let frame = frame {
if frame.statusCode == 1007 {
self.lock()
self.frames = [frame]
self.unlock()
manager.signal()
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), manager.queue){
self.lock()
self.frames += [frame]
self.unlock()
manager.signal()
}
}
}
}
}
}
func stepBuffers(more: Bool) throws {
if rd != nil {
if stage != .CloseConn && rd.streamStatus == NSStreamStatus.AtEnd {
if atEnd {
return;
}
throw WebSocketError.Network(atEndDetails)
}
if more {
while rd.hasBytesAvailable {
var size = inputBytesSize
while size-(inputBytesStart+inputBytesLength) < windowBufferSize {
size *= 2
}
if size > inputBytesSize {
let ptr = UnsafeMutablePointer<UInt8>(realloc(inputBytes, size))
if ptr == nil {
throw WebSocketError.Memory
}
inputBytes = ptr
inputBytesSize = size
}
let n = rd.read(inputBytes+inputBytesStart+inputBytesLength, maxLength: inputBytesSize-inputBytesStart-inputBytesLength)
if n > 0 {
inputBytesLength += n
}
}
}
}
if wr != nil && wr.hasSpaceAvailable && outputBytesLength > 0 {
let n = wr.write(outputBytes+outputBytesStart, maxLength: outputBytesLength)
if n > 0 {
outputBytesLength -= n
if outputBytesLength == 0 {
outputBytesStart = 0
} else {
outputBytesStart += n
}
}
}
}
func stepStreamErrors() throws {
if finalError == nil {
if connectionTimeout {
throw WebSocketError.Network(timeoutDetails)
}
if let error = rd?.streamError {
throw WebSocketError.Network(error.localizedDescription)
}
if let error = wr?.streamError {
throw WebSocketError.Network(error.localizedDescription)
}
}
}
func stepOutputFrames() throws {
lock()
defer {
frames = []
unlock()
}
if !closeFinal {
for frame in frames {
try writeFrame(frame)
if frame.code == .Close {
closeCode = frame.statusCode
closeReason = frame.utf8.text
closeFinal = true
return
}
}
}
}
@inline(__always) func fire(block: ()->()){
if let queue = eventQueue {
dispatch_sync(queue) {
block()
}
} else {
block()
}
}
var readStateSaved = false
var readStateFrame : Frame?
var readStateFinished = false
var leaderFrame : Frame?
func readFrame() throws -> Frame {
var frame : Frame
var finished : Bool
if !readStateSaved {
if leaderFrame != nil {
frame = leaderFrame!
finished = false
leaderFrame = nil
} else {
frame = try readFrameFragment(nil)
finished = frame.finished
}
if frame.code == .Continue{
throw WebSocketError.ProtocolError("leader frame cannot be a continue frame")
}
if !finished {
readStateSaved = true
readStateFrame = frame
readStateFinished = finished
throw WebSocketError.NeedMoreInput
}
} else {
frame = readStateFrame!
finished = readStateFinished
if !finished {
let cf = try readFrameFragment(frame)
finished = cf.finished
if cf.code != .Continue {
if !cf.code.isControl {
throw WebSocketError.ProtocolError("only ping frames can be interlaced with fragments")
}
leaderFrame = frame
return cf
}
if !finished {
readStateSaved = true
readStateFrame = frame
readStateFinished = finished
throw WebSocketError.NeedMoreInput
}
}
}
if !frame.utf8.completed {
throw WebSocketError.PayloadError("incomplete utf8")
}
readStateSaved = false
readStateFrame = nil
readStateFinished = false
return frame
}
func closeConn() {
rd.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
wr.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
rd.delegate = nil
wr.delegate = nil
rd.close()
wr.close()
}
func openConn() throws {
let req = request.mutableCopy() as! NSMutableURLRequest
req.setValue("websocket", forHTTPHeaderField: "Upgrade")
req.setValue("Upgrade", forHTTPHeaderField: "Connection")
if req.valueForHTTPHeaderField("User-Agent") == nil {
req.setValue("SwiftWebSocket", forHTTPHeaderField: "User-Agent")
}
req.setValue("13", forHTTPHeaderField: "Sec-WebSocket-Version")
if req.URL == nil || req.URL!.host == nil{
throw WebSocketError.InvalidAddress
}
if req.URL!.port == nil || req.URL!.port!.integerValue == 80 || req.URL!.port!.integerValue == 443 {
req.setValue(req.URL!.host!, forHTTPHeaderField: "Host")
} else {
req.setValue("\(req.URL!.host!):\(req.URL!.port!.integerValue)", forHTTPHeaderField: "Host")
}
req.setValue(req.URL!.absoluteString, forHTTPHeaderField: "Origin")
if subProtocols.count > 0 {
req.setValue(subProtocols.joinWithSeparator(";"), forHTTPHeaderField: "Sec-WebSocket-Protocol")
}
if req.URL!.scheme != "wss" && req.URL!.scheme != "ws" {
throw WebSocketError.InvalidAddress
}
if compression.on {
var val = "permessage-deflate"
if compression.noContextTakeover {
val += "; client_no_context_takeover; server_no_context_takeover"
}
val += "; client_max_window_bits"
if compression.maxWindowBits != 0 {
val += "; server_max_window_bits=\(compression.maxWindowBits)"
}
req.setValue(val, forHTTPHeaderField: "Sec-WebSocket-Extensions")
}
let security: TCPConnSecurity
let port : Int
if req.URL!.scheme == "wss" {
port = req.URL!.port?.integerValue ?? 443
security = .NegoticatedSSL
} else {
port = req.URL!.port?.integerValue ?? 80
security = .None
}
var path = CFURLCopyPath(req.URL!) as String
if path == "" {
path = "/"
}
if let q = req.URL!.query {
if q != "" {
path += "?" + q
}
}
var reqs = "GET \(path) HTTP/1.1\r\n"
for key in req.allHTTPHeaderFields!.keys {
if let val = req.valueForHTTPHeaderField(key) {
reqs += "\(key): \(val)\r\n"
}
}
var keyb = [UInt32](count: 4, repeatedValue: 0)
for i in 0 ..< 4 {
keyb[i] = arc4random()
}
let rkey = NSData(bytes: keyb, length: 16).base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
reqs += "Sec-WebSocket-Key: \(rkey)\r\n"
reqs += "\r\n"
var header = [UInt8]()
for b in reqs.utf8 {
header += [b]
}
let addr = ["\(req.URL!.host!)", "\(port)"]
if addr.count != 2 || Int(addr[1]) == nil {
throw WebSocketError.InvalidAddress
}
var (rdo, wro) : (NSInputStream?, NSOutputStream?)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(nil, addr[0], UInt32(Int(addr[1])!), &readStream, &writeStream);
rdo = readStream!.takeRetainedValue()
wro = writeStream!.takeRetainedValue()
(rd, wr) = (rdo!, wro!)
rd.setProperty(security.level, forKey: NSStreamSocketSecurityLevelKey)
wr.setProperty(security.level, forKey: NSStreamSocketSecurityLevelKey)
if services.contains(.VoIP) {
rd.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
wr.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
}
if services.contains(.Video) {
rd.setProperty(NSStreamNetworkServiceTypeVideo, forKey: NSStreamNetworkServiceType)
wr.setProperty(NSStreamNetworkServiceTypeVideo, forKey: NSStreamNetworkServiceType)
}
if services.contains(.Background) {
rd.setProperty(NSStreamNetworkServiceTypeBackground, forKey: NSStreamNetworkServiceType)
wr.setProperty(NSStreamNetworkServiceTypeBackground, forKey: NSStreamNetworkServiceType)
}
if services.contains(.Voice) {
rd.setProperty(NSStreamNetworkServiceTypeVoice, forKey: NSStreamNetworkServiceType)
wr.setProperty(NSStreamNetworkServiceTypeVoice, forKey: NSStreamNetworkServiceType)
}
if allowSelfSignedSSL {
let prop: Dictionary<NSObject,NSObject> = [kCFStreamSSLPeerName: kCFNull, kCFStreamSSLValidatesCertificateChain: NSNumber(bool: false)]
rd.setProperty(prop, forKey: kCFStreamPropertySSLSettings as String)
wr.setProperty(prop, forKey: kCFStreamPropertySSLSettings as String)
}
rd.delegate = delegate
wr.delegate = delegate
rd.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
wr.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
rd.open()
wr.open()
try write(header, length: header.count)
}
func write(bytes: UnsafePointer<UInt8>, length: Int) throws {
if outputBytesStart+outputBytesLength+length > outputBytesSize {
var size = outputBytesSize
while outputBytesStart+outputBytesLength+length > size {
size *= 2
}
let ptr = UnsafeMutablePointer<UInt8>(realloc(outputBytes, size))
if ptr == nil {
throw WebSocketError.Memory
}
outputBytes = ptr
outputBytesSize = size
}
memcpy(outputBytes+outputBytesStart+outputBytesLength, bytes, length)
outputBytesLength += length
}
func readResponse() throws {
let end : [UInt8] = [ 0x0D, 0x0A, 0x0D, 0x0A ]
let ptr = UnsafeMutablePointer<UInt8>(memmem(inputBytes+inputBytesStart, inputBytesLength, end, 4))
if ptr == nil {
throw WebSocketError.NeedMoreInput
}
let buffer = inputBytes+inputBytesStart
let bufferCount = ptr-(inputBytes+inputBytesStart)
let string = NSString(bytesNoCopy: buffer, length: bufferCount, encoding: NSUTF8StringEncoding, freeWhenDone: false) as? String
if string == nil {
throw WebSocketError.InvalidHeader
}
let header = string!
var needsCompression = false
var serverMaxWindowBits = 15
let clientMaxWindowBits = 15
var key = ""
let trim : (String)->(String) = { (text) in return text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())}
let eqval : (String,String)->(String) = { (line, del) in return trim(line.componentsSeparatedByString(del)[1]) }
let lines = header.componentsSeparatedByString("\r\n")
for i in 0 ..< lines.count {
let line = trim(lines[i])
if i == 0 {
if !line.hasPrefix("HTTP/1.1 101"){
throw WebSocketError.InvalidResponse(line)
}
} else if line != "" {
var value = ""
if line.hasPrefix("\t") || line.hasPrefix(" ") {
value = trim(line)
} else {
key = ""
if let r = line.rangeOfString(":") {
key = trim(line.substringToIndex(r.startIndex))
value = trim(line.substringFromIndex(r.endIndex))
}
}
switch key.lowercaseString {
case "sec-websocket-subprotocol":
privateSubProtocol = value
case "sec-websocket-extensions":
let parts = value.componentsSeparatedByString(";")
for p in parts {
let part = trim(p)
if part == "permessage-deflate" {
needsCompression = true
} else if part.hasPrefix("server_max_window_bits="){
if let i = Int(eqval(line, "=")) {
serverMaxWindowBits = i
}
}
}
default:
break
}
}
}
if needsCompression {
if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 {
throw WebSocketError.InvalidCompressionOptions("server_max_window_bits")
}
if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 {
throw WebSocketError.InvalidCompressionOptions("client_max_window_bits")
}
inflater = Inflater(windowBits: serverMaxWindowBits)
if inflater == nil {
throw WebSocketError.InvalidCompressionOptions("inflater init")
}
deflater = Deflater(windowBits: clientMaxWindowBits, memLevel: 8)
if deflater == nil {
throw WebSocketError.InvalidCompressionOptions("deflater init")
}
}
inputBytesLength -= bufferCount+4
if inputBytesLength == 0 {
inputBytesStart = 0
} else {
inputBytesStart += bufferCount+4
}
}
class ByteReader {
var start : UnsafePointer<UInt8>
var end : UnsafePointer<UInt8>
var bytes : UnsafePointer<UInt8>
init(bytes: UnsafePointer<UInt8>, length: Int){
self.bytes = bytes
start = bytes
end = bytes+length
}
func readByte() throws -> UInt8 {
if bytes >= end {
throw WebSocketError.NeedMoreInput
}
let b = bytes.memory
bytes += 1
return b
}
var length : Int {
return end - bytes
}
var position : Int {
get {
return bytes - start
}
set {
bytes = start + newValue
}
}
}
var fragStateSaved = false
var fragStatePosition = 0
var fragStateInflate = false
var fragStateLen = 0
var fragStateFin = false
var fragStateCode = OpCode.Continue
var fragStateLeaderCode = OpCode.Continue
var fragStateUTF8 = UTF8()
var fragStatePayload = Payload()
var fragStateStatusCode = UInt16(0)
var fragStateHeaderLen = 0
var buffer = [UInt8](count: windowBufferSize, repeatedValue: 0)
var reusedPayload = Payload()
func readFrameFragment(leader : Frame?) throws -> Frame {
var inflate : Bool
var len : Int
var fin = false
var code : OpCode
var leaderCode : OpCode
var utf8 : UTF8
var payload : Payload
var statusCode : UInt16
var headerLen : Int
var leader = leader
let reader = ByteReader(bytes: inputBytes+inputBytesStart, length: inputBytesLength)
if fragStateSaved {
// load state
reader.position += fragStatePosition
inflate = fragStateInflate
len = fragStateLen
fin = fragStateFin
code = fragStateCode
leaderCode = fragStateLeaderCode
utf8 = fragStateUTF8
payload = fragStatePayload
statusCode = fragStateStatusCode
headerLen = fragStateHeaderLen
fragStateSaved = false
} else {
var b = try reader.readByte()
fin = b >> 7 & 0x1 == 0x1
let rsv1 = b >> 6 & 0x1 == 0x1
let rsv2 = b >> 5 & 0x1 == 0x1
let rsv3 = b >> 4 & 0x1 == 0x1
if inflater != nil && (rsv1 || (leader != nil && leader!.inflate)) {
inflate = true
} else if rsv1 || rsv2 || rsv3 {
throw WebSocketError.ProtocolError("invalid extension")
} else {
inflate = false
}
code = OpCode.Binary
if let c = OpCode(rawValue: (b & 0xF)){
code = c
} else {
throw WebSocketError.ProtocolError("invalid opcode")
}
if !fin && code.isControl {
throw WebSocketError.ProtocolError("unfinished control frame")
}
b = try reader.readByte()
if b >> 7 & 0x1 == 0x1 {
throw WebSocketError.ProtocolError("server sent masked frame")
}
var len64 = Int64(b & 0x7F)
var bcount = 0
if b & 0x7F == 126 {
bcount = 2
} else if len64 == 127 {
bcount = 8
}
if bcount != 0 {
if code.isControl {
throw WebSocketError.ProtocolError("invalid payload size for control frame")
}
len64 = 0
var i = bcount-1
while i >= 0 {
b = try reader.readByte()
len64 += Int64(b) << Int64(i*8)
i -= 1
}
}
len = Int(len64)
if code == .Continue {
if code.isControl {
throw WebSocketError.ProtocolError("control frame cannot have the 'continue' opcode")
}
if leader == nil {
throw WebSocketError.ProtocolError("continue frame is missing it's leader")
}
}
if code.isControl {
if leader != nil {
leader = nil
}
if inflate {
throw WebSocketError.ProtocolError("control frame cannot be compressed")
}
}
statusCode = 0
if leader != nil {
leaderCode = leader!.code
utf8 = leader!.utf8
payload = leader!.payload
} else {
leaderCode = code
utf8 = UTF8()
payload = reusedPayload
payload.count = 0
}
if leaderCode == .Close {
if len == 1 {
throw WebSocketError.ProtocolError("invalid payload size for close frame")
}
if len >= 2 {
let b1 = try reader.readByte()
let b2 = try reader.readByte()
statusCode = (UInt16(b1) << 8) + UInt16(b2)
len -= 2
if statusCode < 1000 || statusCode > 4999 || (statusCode >= 1004 && statusCode <= 1006) || (statusCode >= 1012 && statusCode <= 2999) {
throw WebSocketError.ProtocolError("invalid status code for close frame")
}
}
}
headerLen = reader.position
}
let rlen : Int
let rfin : Bool
let chopped : Bool
if reader.length+reader.position-headerLen < len {
rlen = reader.length
rfin = false
chopped = true
} else {
rlen = len-reader.position+headerLen
rfin = fin
chopped = false
}
let bytes : UnsafeMutablePointer<UInt8>
let bytesLen : Int
if inflate {
(bytes, bytesLen) = try inflater!.inflate(reader.bytes, length: rlen, final: rfin)
} else {
(bytes, bytesLen) = (UnsafeMutablePointer<UInt8>(reader.bytes), rlen)
}
reader.bytes += rlen
if leaderCode == .Text || leaderCode == .Close {
try utf8.append(bytes, length: bytesLen)
} else {
payload.append(bytes, length: bytesLen)
}
if chopped {
// save state
fragStateHeaderLen = headerLen
fragStateStatusCode = statusCode
fragStatePayload = payload
fragStateUTF8 = utf8
fragStateLeaderCode = leaderCode
fragStateCode = code
fragStateFin = fin
fragStateLen = len
fragStateInflate = inflate
fragStatePosition = reader.position
fragStateSaved = true
throw WebSocketError.NeedMoreInput
}
inputBytesLength -= reader.position
if inputBytesLength == 0 {
inputBytesStart = 0
} else {
inputBytesStart += reader.position
}
let f = Frame()
(f.code, f.payload, f.utf8, f.statusCode, f.inflate, f.finished) = (code, payload, utf8, statusCode, inflate, fin)
return f
}
var head = [UInt8](count: 0xFF, repeatedValue: 0)
func writeFrame(f : Frame) throws {
if !f.finished{
throw WebSocketError.LibraryError("cannot send unfinished frames")
}
var hlen = 0
let b : UInt8 = 0x80
var deflate = false
if deflater != nil {
if f.code == .Binary || f.code == .Text {
deflate = true
// b |= 0x40
}
}
head[hlen] = b | f.code.rawValue
hlen += 1
var payloadBytes : [UInt8]
var payloadLen = 0
if f.utf8.text != "" {
payloadBytes = UTF8.bytes(f.utf8.text)
} else {
payloadBytes = f.payload.array
}
payloadLen += payloadBytes.count
if deflate {
}
var usingStatusCode = false
if f.statusCode != 0 && payloadLen != 0 {
payloadLen += 2
usingStatusCode = true
}
if payloadLen < 126 {
head[hlen] = 0x80 | UInt8(payloadLen)
hlen += 1
} else if payloadLen <= 0xFFFF {
head[hlen] = 0x80 | 126
hlen += 1
var i = 1
while i >= 0 {
head[hlen] = UInt8((UInt16(payloadLen) >> UInt16(i*8)) & 0xFF)
hlen += 1
i -= 1
}
} else {
head[hlen] = UInt8((0x1 << 7) + 127)
hlen += 1
var i = 7
while i >= 0 {
head[hlen] = UInt8((UInt64(payloadLen) >> UInt64(i*8)) & 0xFF)
hlen += 1
i -= 1
}
}
let r = arc4random()
var maskBytes : [UInt8] = [UInt8(r >> 0 & 0xFF), UInt8(r >> 8 & 0xFF), UInt8(r >> 16 & 0xFF), UInt8(r >> 24 & 0xFF)]
for i in 0 ..< 4 {
head[hlen] = maskBytes[i]
hlen += 1
}
if payloadLen > 0 {
if usingStatusCode {
var sc = [UInt8(f.statusCode >> 8 & 0xFF), UInt8(f.statusCode >> 0 & 0xFF)]
for i in 0 ..< 2 {
sc[i] ^= maskBytes[i % 4]
}
head[hlen] = sc[0]
hlen += 1
head[hlen] = sc[1]
hlen += 1
for i in 2 ..< payloadLen {
payloadBytes[i-2] ^= maskBytes[i % 4]
}
} else {
for i in 0 ..< payloadLen {
payloadBytes[i] ^= maskBytes[i % 4]
}
}
}
try write(head, length: hlen)
try write(payloadBytes, length: payloadBytes.count)
}
func close(code : Int = 1000, reason : String = "Normal Closure") {
let f = Frame()
f.code = .Close
f.statusCode = UInt16(truncatingBitPattern: code)
f.utf8.text = reason
sendFrame(f)
}
func sendFrame(f : Frame) {
lock()
frames += [f]
unlock()
manager.signal()
}
func send(message : Any) {
let f = Frame()
if let message = message as? String {
f.code = .Text
f.utf8.text = message
} else if let message = message as? [UInt8] {
f.code = .Binary
f.payload.array = message
} else if let message = message as? UnsafeBufferPointer<UInt8> {
f.code = .Binary
f.payload.append(message.baseAddress, length: message.count)
} else if let message = message as? NSData {
f.code = .Binary
f.payload.nsdata = message
} else {
f.code = .Text
f.utf8.text = "\(message)"
}
sendFrame(f)
}
func ping() {
let f = Frame()
f.code = .Ping
sendFrame(f)
}
func ping(message : Any){
let f = Frame()
f.code = .Ping
if let message = message as? String {
f.payload.array = UTF8.bytes(message)
} else if let message = message as? [UInt8] {
f.payload.array = message
} else if let message = message as? UnsafeBufferPointer<UInt8> {
f.payload.append(message.baseAddress, length: message.count)
} else if let message = message as? NSData {
f.payload.nsdata = message
} else {
f.utf8.text = "\(message)"
}
sendFrame(f)
}
}
private func ==(lhs: InnerWebSocket, rhs: InnerWebSocket) -> Bool {
return lhs.id == rhs.id
}
private enum TCPConnSecurity {
case None
case NegoticatedSSL
var level: String {
switch self {
case .None: return NSStreamSocketSecurityLevelNone
case .NegoticatedSSL: return NSStreamSocketSecurityLevelNegotiatedSSL
}
}
}
// Manager class is used to minimize the number of dispatches and cycle through network events
// using fewers threads. Helps tremendously with lowing system resources when many conncurrent
// sockets are opened.
private class Manager {
var queue = dispatch_queue_create("SwiftWebSocketInstance", nil)
var once = dispatch_once_t()
var mutex = pthread_mutex_t()
var cond = pthread_cond_t()
var websockets = Set<InnerWebSocket>()
var _nextId = 0
init(){
pthread_mutex_init(&mutex, nil)
pthread_cond_init(&cond, nil)
dispatch_async(dispatch_queue_create("SwiftWebSocket", nil)) {
var wss : [InnerWebSocket] = []
while true {
var wait = true
wss.removeAll()
pthread_mutex_lock(&self.mutex)
for ws in self.websockets {
wss.append(ws)
}
for ws in wss {
self.checkForConnectionTimeout(ws)
if ws.dirty {
pthread_mutex_unlock(&self.mutex)
ws.step()
pthread_mutex_lock(&self.mutex)
wait = false
}
}
if wait {
self.wait(250)
}
pthread_mutex_unlock(&self.mutex)
}
}
}
func checkForConnectionTimeout(ws : InnerWebSocket) {
if ws.rd != nil && ws.wr != nil && (ws.rd.streamStatus == .Opening || ws.wr.streamStatus == .Opening) {
let age = CFAbsoluteTimeGetCurrent() - ws.createdAt
if age >= timeoutDuration {
ws.connectionTimeout = true
}
}
}
func wait(timeInMs : Int) -> Int32 {
var ts = timespec()
var tv = timeval()
gettimeofday(&tv, nil)
ts.tv_sec = time(nil) + timeInMs / 1000;
let v1 = Int(tv.tv_usec * 1000)
let v2 = Int(1000 * 1000 * Int(timeInMs % 1000))
ts.tv_nsec = v1 + v2;
ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000);
ts.tv_nsec %= (1000 * 1000 * 1000);
return pthread_cond_timedwait(&self.cond, &self.mutex, &ts)
}
func signal(){
pthread_mutex_lock(&mutex)
pthread_cond_signal(&cond)
pthread_mutex_unlock(&mutex)
}
func add(websocket: InnerWebSocket) {
pthread_mutex_lock(&mutex)
websockets.insert(websocket)
pthread_cond_signal(&cond)
pthread_mutex_unlock(&mutex)
}
func remove(websocket: InnerWebSocket) {
pthread_mutex_lock(&mutex)
websockets.remove(websocket)
pthread_cond_signal(&cond)
pthread_mutex_unlock(&mutex)
}
func nextId() -> Int {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
_nextId += 1
return _nextId
}
}
private let manager = Manager()
/// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455.
public class WebSocket: NSObject {
private var ws: InnerWebSocket
private var id = manager.nextId()
private var opened: Bool
public override var hashValue: Int { return id }
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
public convenience init(_ url: String){
self.init(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: [])
}
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
public convenience init(url: NSURL){
self.init(request: NSURLRequest(URL: url), subProtocols: [])
}
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols.
public convenience init(_ url: String, subProtocols : [String]){
self.init(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: subProtocols)
}
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol.
public convenience init(_ url: String, subProtocol : String){
self.init(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: [subProtocol])
}
/// Create a WebSocket connection from an NSURLRequest; Also include a list of protocols.
public init(request: NSURLRequest, subProtocols : [String] = []){
opened = true
ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: false)
}
/// Create a WebSocket object with a deferred connection; the connection is not opened until the .open() method is called.
public override init(){
opened = false
ws = InnerWebSocket(request: NSURLRequest(), subProtocols: [], stub: true)
super.init()
ws.eclose = {
self.opened = false
}
}
/// The URL as resolved by the constructor. This is always an absolute URL. Read only.
public var url : String{ return ws.url }
/// A string indicating the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object.
public var subProtocol : String{ return ws.subProtocol }
/// The compression options of the WebSocket.
public var compression : WebSocketCompression{
get { return ws.compression }
set { ws.compression = newValue }
}
/// Allow for Self-Signed SSL Certificates. Default is false.
public var allowSelfSignedSSL : Bool{
get { return ws.allowSelfSignedSSL }
set { ws.allowSelfSignedSSL = newValue }
}
/// The services of the WebSocket.
public var services : WebSocketService{
get { return ws.services }
set { ws.services = newValue }
}
/// The events of the WebSocket.
public var event : WebSocketEvents{
get { return ws.event }
set { ws.event = newValue }
}
/// The queue for firing off events. default is main_queue
public var eventQueue : dispatch_queue_t?{
get { return ws.eventQueue }
set { ws.eventQueue = newValue }
}
/// A WebSocketBinaryType value indicating the type of binary data being transmitted by the connection. Default is .UInt8Array.
public var binaryType : WebSocketBinaryType{
get { return ws.binaryType }
set { ws.binaryType = newValue }
}
/// The current state of the connection; this is one of the WebSocketReadyState constants. Read only.
public var readyState : WebSocketReadyState{
return ws.readyState
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
public func open(url: String){
open(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: [])
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
public func open(nsurl url: NSURL){
open(request: NSURLRequest(URL: url), subProtocols: [])
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols.
public func open(url: String, subProtocols : [String]){
open(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: subProtocols)
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol.
public func open(url: String, subProtocol : String){
open(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: [subProtocol])
}
/// Opens a deferred or closed WebSocket connection from an NSURLRequest; Also include a list of protocols.
public func open(request request: NSURLRequest, subProtocols : [String] = []){
if opened{
return
}
opened = true
ws = ws.copyOpen(request, subProtocols: subProtocols)
}
/// Opens a closed WebSocket connection from an NSURLRequest; Uses the same request and protocols as previously closed WebSocket
public func open(){
open(request: ws.request, subProtocols: ws.subProtocols)
}
/**
Closes the WebSocket connection or connection attempt, if any. If the connection is already closed or in the state of closing, this method does nothing.
:param: code An integer indicating the status code explaining why the connection is being closed. If this parameter is not specified, a default value of 1000 (indicating a normal closure) is assumed.
:param: reason A human-readable string explaining why the connection is closing. This string must be no longer than 123 bytes of UTF-8 text (not characters).
*/
public func close(code : Int = 1000, reason : String = "Normal Closure"){
if !opened{
return
}
opened = false
ws.close(code, reason: reason)
}
/**
Transmits message to the server over the WebSocket connection.
:param: message The message to be sent to the server.
*/
public func send(message : Any){
if !opened{
return
}
ws.send(message)
}
/**
Transmits a ping to the server over the WebSocket connection.
:param: optional message The data to be sent to the server.
*/
public func ping(message : Any){
if !opened{
return
}
ws.ping(message)
}
/**
Transmits a ping to the server over the WebSocket connection.
*/
public func ping(){
if !opened{
return
}
ws.ping()
}
}
public func ==(lhs: WebSocket, rhs: WebSocket) -> Bool {
return lhs.id == rhs.id
}
extension WebSocket {
/// The events of the WebSocket using a delegate.
public var delegate : WebSocketDelegate? {
get { return ws.eventDelegate }
set { ws.eventDelegate = newValue }
}
/**
Transmits message to the server over the WebSocket connection.
:param: text The message (string) to be sent to the server.
*/
@objc
public func send(text text: String){
send(text)
}
/**
Transmits message to the server over the WebSocket connection.
:param: data The message (binary) to be sent to the server.
*/
@objc
public func send(data data: NSData){
send(data)
}
}
| bsd-2-clause | 4a7698299868c7f13264179248eeb365 | 36.365184 | 227 | 0.55501 | 4.996108 | false | false | false | false |
iankunneke/TIY-Assignmnts | Make Something Beautiful/Make Something Beautiful/GameScene.swift | 1 | 6123 | //
// GameScene.swift
// Make Something Beautiful
//
// Created by ian kunneke on 8/7/15.
// Copyright (c) 2015 The Iron Yard. All rights reserved.
//
import UIKit
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate
{
var gameEnding: Bool = false
var catchCaught = 0
var contactQueue: Array<SKPhysicsContact> = []
let skewer = SKSpriteNode(imageNamed: "Skewer")
var touchLocationX = CGFloat()
var isFingerOnSkewer = false
let kSkewerCategory: UInt32 = 0x1 << 0
let kCatchCategory: UInt32 = 0x1 << 1
let kSceneEdgeCategory: UInt32 = 0x1 << 2
var scoreKeeper = Score()
let catches = ["BadCatch", "OrangeCatch", "StarCatch", "OceanCatch"]
let gameScore = Score()
var scoreLabel = UILabel(frame: CGRectMake(0, 0, 100, 60))
override func didMoveToView(view: SKView)
{
// view setup
backgroundColor = SKColor.whiteColor()
// configure score label
scoreKeeper.clearScore()
self.view?.addSubview(scoreLabel)
scoreLabel.text = "0000"
// create and place the skewer on screen
makeAndPlaceSkewer()
// Physics setup for scene
self.physicsBody?.collisionBitMask = 0
self.physicsWorld.contactDelegate = self
// Start the falling catch pieces
runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.runBlock(addCatch),SKAction.waitForDuration(1.0)])))
}
func makeAndPlaceSkewer()
{
skewer.name = "Skewer"
skewer.physicsBody = SKPhysicsBody(rectangleOfSize: skewer.size)
skewer.physicsBody?.affectedByGravity = false
skewer.position = CGPoint(x: size.width * 0.5, y: size.height * 0.0)
skewer.physicsBody?.categoryBitMask = kSkewerCategory
skewer.physicsBody?.contactTestBitMask = kCatchCategory
skewer.physicsBody?.collisionBitMask = kSceneEdgeCategory
addChild(skewer)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
{
var touch = touches.first as! UITouch
var touchLocation = touch.locationInNode(self)
touchLocationX = touchLocation.x
//let touchLocationX = touch.locationInNode(self).x
// println(touchLocation)
isFingerOnSkewer = true
//
// if let body = physicsWorld.bodyAtPoint(touchLocation)
// {
// if body.node!.name == "Skewer"
// {
// println("Began touch on skewer")
// isFingerOnSkewer = true
// }
// }
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent)
{
var touch = touches.first as! UITouch
touchLocationX = touch.locationInNode(self).x
// reposition the x coordinate for the skewer
skewer.position.x = touchLocationX
//touchLocationX = touchLocation.x
// println(touchLocationX)
if isFingerOnSkewer
{
//SKAction.moveToX(scewer: touchLocationX, 0)
//SKAction.movetoX(touchLocationX, 0)
var touch = touches.first as! UITouch
var touchLocation = touch.locationInNode(self)
var previousLocation = touch.previousLocationInNode(self)
//var aScewer = childNodeWithName("skewer") as! SKSpriteNode
// skewer = aSkewer.position.x + (touchLocation.x - previousLocation.x)
//
// scewerX = max(scewerX, aScewer.size.width/2)
// scewerX = min(scewerX, size.width - aScewer.size.width/2)
// aScewer.position = CGPointMake(scewerX, aScewer.position.y)
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent)
{
//intentional no-op
}
func didBeginContact(contact: SKPhysicsContact)
{
scoreKeeper.addToScore(1)
scoreLabel.text = String(scoreKeeper.gameScore)
// println("collision detected")
if contact.bodyA.node!.name == "Skewer"
{
contact.bodyB.node!.removeFromParent()
}
else
{
contact.bodyA!.node!.removeFromParent()
}
}
func random() ->CGFloat
{
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(#min: CGFloat,max: CGFloat) -> CGFloat
{
return random() * (max - min) + min
}
func addCatch()
{
let randomCatchIndex = Int(arc4random_uniform(UInt32(catches.count)))
let catch = SKSpriteNode(imageNamed: catches[randomCatchIndex])
let actualX = random(min: catch.size.width/2, max: size.width - catch.size.width/2)
// println("random x for shape: \(actualX)")
catch.physicsBody = SKPhysicsBody(rectangleOfSize: catch.size)
catch.position = CGPoint(x: actualX, y: size.height + catch.size.height/2)
addChild(catch)
let actualDuration = random(min: CGFloat(2.0), max: CGFloat(6.0))
let actionMove = SKAction.moveTo(CGPoint(x: actualX, y: -catch.size.width/2), duration: NSTimeInterval(actualDuration))
let actionMoveDone = SKAction.removeFromParent()
//catch.physicsBody = SKPhysicsBody(rectangleOfSize: catch.size)
catch.physicsBody?.categoryBitMask = kCatchCategory
catch.physicsBody?.contactTestBitMask = kSkewerCategory
catch.physicsBody?.collisionBitMask = 0x0
//catch.physicsBody?.usesPreciseCollisionDetection = true
catch.physicsBody?.dynamic = true
catch.runAction(SKAction.sequence([actionMove, actionMoveDone]))
}
// func endGame()
// {
// if !gameEnding
// {
// gameEnding = true
//
// }
// }
// func catchDidCollideWithSkewer(skewer:SKSpriteNode, catch:SKSpriteNode)
// {
// println("Hit")
// catch.removeFromParent()
//
// catchCaught++
//
//
// }
}
| cc0-1.0 | 829e9c03bfe1015b42e03573e0cdb300 | 30.081218 | 127 | 0.606729 | 4.327208 | false | false | false | false |
YMXian/Deliria | Deliria/Deliria/Crypto/Collection+Extension.swift | 1 | 2641 | //
// Collection+Extension.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 02/08/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
extension Collection where Self.Iterator.Element == UInt8, Self.Index == Int {
func toUInt32Array() -> Array<UInt32> {
var result = Array<UInt32>()
result.reserveCapacity(16)
for idx in stride(from: self.startIndex, to: self.endIndex, by: MemoryLayout<UInt32>.size) {
var val: UInt32 = 0
val |= self.count > 3 ? UInt32(self[idx.advanced(by: 3)]) << 24 : 0
val |= self.count > 2 ? UInt32(self[idx.advanced(by: 2)]) << 16 : 0
val |= self.count > 1 ? UInt32(self[idx.advanced(by: 1)]) << 8 : 0
val |= self.count > 0 ? UInt32(self[idx]) : 0
result.append(val)
}
return result
}
func toUInt64Array() -> Array<UInt64> {
var result = Array<UInt64>()
result.reserveCapacity(32)
for idx in stride(from: self.startIndex, to: self.endIndex, by: MemoryLayout<UInt64>.size) {
var val: UInt64 = 0
val |= self.count > 7 ? UInt64(self[idx.advanced(by: 7)]) << 56 : 0
val |= self.count > 6 ? UInt64(self[idx.advanced(by: 6)]) << 48 : 0
val |= self.count > 5 ? UInt64(self[idx.advanced(by: 5)]) << 40 : 0
val |= self.count > 4 ? UInt64(self[idx.advanced(by: 4)]) << 32 : 0
val |= self.count > 3 ? UInt64(self[idx.advanced(by: 3)]) << 24 : 0
val |= self.count > 2 ? UInt64(self[idx.advanced(by: 2)]) << 16 : 0
val |= self.count > 1 ? UInt64(self[idx.advanced(by: 1)]) << 8 : 0
val |= self.count > 0 ? UInt64(self[idx.advanced(by: 0)]) << 0 : 0
result.append(val)
}
return result
}
/// Initialize integer from array of bytes. Caution: may be slow!
func toInteger<T: Integer>() -> T where T: ByteConvertible, T: BitshiftOperationsType {
if self.count == 0 {
return 0
}
var bytes = self.reversed() //FIXME: check it this is equivalent of Array(...)
if bytes.count < MemoryLayout<T>.size {
let paddingCount = MemoryLayout<T>.size - bytes.count
if (paddingCount > 0) {
bytes += Array<UInt8>(repeating: 0, count: paddingCount)
}
}
if MemoryLayout<T>.size == 1 {
return T(truncatingBitPattern: UInt64(bytes[0]))
}
var result: T = 0
for byte in bytes.reversed() {
result = result << 8 | T(byte)
}
return result
}
}
| mit | b32bb9a748d4cc5cc4a5d51d4d6a68e0 | 37.823529 | 100 | 0.546591 | 3.682008 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.HardwareFinish.swift | 1 | 2031 | import Foundation
public extension AnyCharacteristic {
static func hardwareFinish(
_ value: Data = Data(),
permissions: [CharacteristicPermission] = [.read],
description: String? = "Hardware Finish",
format: CharacteristicFormat? = .tlv8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.hardwareFinish(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func hardwareFinish(
_ value: Data = Data(),
permissions: [CharacteristicPermission] = [.read],
description: String? = "Hardware Finish",
format: CharacteristicFormat? = .tlv8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Data> {
GenericCharacteristic<Data>(
type: .hardwareFinish,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | 82538f919f66fe00b9567785672a5cc2 | 32.295082 | 66 | 0.576071 | 5.459677 | false | false | false | false |
inacioferrarini/OMDBSpy | OMDBSpyTests/Foundation/DataSyncRules/DataSyncDailyRulesTests.swift | 1 | 3596 | import XCTest
@testable import OMDBSpy
class DataSyncDailyRulesTests: XCTestCase {
func createRules() -> DataSyncRules {
let coreDataStack = TestUtil().appContext().coreDataStack
return DataSyncRules(coreDataStack: coreDataStack)
}
func test_nonExistingDailyRule_mustReturnFalse() {
let ruleName = TestUtil().randomRuleName()
let rules = self.createRules()
rules.addSyncRule(ruleName, rule: SyncRule.Daily(3))
let result = rules.shouldPerformSyncRule("NonExistingRule", atDate: NSDate())
XCTAssertEqual(result, false, "Execution of a non-existing daily rule is expected to fail.")
}
func test_nonExistingDailyRule_update_doesNotcrash() {
let ruleName = TestUtil().randomRuleName()
let rules = self.createRules()
rules.updateSyncRuleHistoryExecutionTime(ruleName, lastExecutionDate: NSDate())
}
func test_existingDailyRuleHistory_update_doesNotcrash() {
let ruleName = TestUtil().randomRuleName()
let rules = self.createRules()
let context = rules.coreDataStack.managedObjectContext
EntitySyncHistory.entityAutoSyncHistoryByName(ruleName, lastExecutionDate: NSDate(), inManagedObjectContext: context)
rules.updateSyncRuleHistoryExecutionTime(ruleName, lastExecutionDate: NSDate())
}
func test_updatingExistingDailyRule_doesNotCrash() {
let ruleName = TestUtil().randomRuleName()
let rules = self.createRules()
rules.addSyncRule(ruleName, rule: SyncRule.Daily(12))
rules.updateSyncRuleHistoryExecutionTime(ruleName, lastExecutionDate: NSDate())
}
func test_existingDailyRuleWithoutLastExecutionDate_mustReturnTrue() {
let ruleName = TestUtil().randomRuleName()
let rules = self.createRules()
rules.addSyncRule(ruleName, rule: SyncRule.Daily(3))
let result = rules.shouldPerformSyncRule(ruleName, atDate: NSDate())
XCTAssertEqual(result, true, "Execution of an existing daily rule without last execution date is exected to succeeded.")
}
func test_existingDailyRule_withDaysEquals3AndlastExecutionDateEquals3_mustReturnTrue() {
let ruleName = TestUtil().randomRuleName()
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let lastExecutionDate = formatter.dateFromString("2015-03-23T12:20:20")!
let executionDate = formatter.dateFromString("2015-03-26T12:20:20")!
let rules = self.createRules()
rules.addSyncRule(ruleName, rule: SyncRule.Daily(3))
rules.updateSyncRuleHistoryExecutionTime(ruleName, lastExecutionDate: lastExecutionDate)
let result = rules.shouldPerformSyncRule(ruleName, atDate: executionDate)
XCTAssertEqual(result, true)
}
func test_existingDailyRule_withDaysEqual32AndlastExecutionDateEquals2_mustReturnFalse() {
let ruleName = TestUtil().randomRuleName()
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let lastExecutionDate = formatter.dateFromString("2015-03-23T12:20:20")!
let executionDate = formatter.dateFromString("2015-03-25T12:20:20")!
let rules = self.createRules()
rules.addSyncRule(ruleName, rule: SyncRule.Daily(3))
rules.updateSyncRuleHistoryExecutionTime(ruleName, lastExecutionDate: lastExecutionDate)
let result = rules.shouldPerformSyncRule(ruleName, atDate: executionDate)
XCTAssertEqual(result, true)
}
}
| mit | ac9f0634bca4364fe0788d4a8d2f3d9c | 45.102564 | 128 | 0.704672 | 4.291169 | false | true | false | false |
alexhuang91/DownloadManager | DownloadManager/Download.swift | 1 | 2830 | //
// Download.swift
// ReactNativeDeploy
//
// Created by Alex Huang on 1/31/16.
// Copyright © 2016 Alex Huang. All rights reserved.
//
import Foundation
/// The Download class represents an active download. It is immutable and provides functionality to return new Download objects given state changes.
public class Download: NSObject {
let downloadURL: NSURL
let destinationURL: NSURL
let isDownloading: Bool
let downloadTask: NSURLSessionDownloadTask?
let resumeData: NSData?
let progressSize: Int64
let downloadSize: Int64
var progress: Float {
if downloadSize == 0 {
return 0.0
} else {
return Float(progressSize) / Float(downloadSize)
}
}
init(downloadURL: NSURL, destinationURL: NSURL, isDownloading: Bool, progressSize: Int64, downloadSize: Int64, downloadTask: NSURLSessionDownloadTask?, resumeData: NSData?) {
self.downloadURL = downloadURL
self.destinationURL = destinationURL
self.isDownloading = isDownloading
self.progressSize = progressSize
self.downloadSize = downloadSize
self.downloadTask = downloadTask
self.resumeData = resumeData
}
convenience init(downloadURL: NSURL, destinationURL: NSURL) {
self.init(downloadURL: downloadURL, destinationURL: destinationURL, isDownloading: false, progressSize: 0, downloadSize: 0, downloadTask: nil, resumeData: nil)
}
// MARK: Property Changes
public func downloadWithProgress(newProgressSize: Int64, newDownloadSize: Int64) -> Download {
return Download(downloadURL: downloadURL, destinationURL: destinationURL, isDownloading: isDownloading, progressSize: newProgressSize, downloadSize: newDownloadSize, downloadTask: downloadTask, resumeData: resumeData)
}
public func downloadWithPauseState(newResumeData: NSData? = nil) -> Download {
return Download(downloadURL: downloadURL, destinationURL: destinationURL, isDownloading: false, progressSize: progressSize, downloadSize: downloadSize, downloadTask: downloadTask, resumeData: newResumeData)
}
public func downloadWithResumeState(newDownloadTask: NSURLSessionDownloadTask) -> Download {
return Download(downloadURL: downloadURL, destinationURL: destinationURL, isDownloading: true, progressSize: progressSize, downloadSize: downloadSize, downloadTask: newDownloadTask, resumeData: resumeData)
}
// MARK: Helpers
public func getProgressSizeString() -> String {
return NSByteCountFormatter.stringFromByteCount(self.progressSize, countStyle: NSByteCountFormatterCountStyle.Binary)
}
public func getDownloadSizeString() -> String {
return NSByteCountFormatter.stringFromByteCount(self.downloadSize, countStyle: NSByteCountFormatterCountStyle.Binary)
}
} | mit | f017f9bdd9776bebd9177041fb70a96f | 42.538462 | 225 | 0.741605 | 5.069892 | false | false | false | false |
httpswift/swifter | Xcode/Sources/Socket+Server.swift | 1 | 4581 | //
// Socket+Server.swift
// Swifter
//
// Created by Damian Kolakowski on 13/07/16.
//
import Foundation
extension Socket {
// swiftlint:disable function_body_length
/// - Parameters:
/// - listenAddress: String representation of the address the socket should accept
/// connections from. It should be in IPv4 format if forceIPv4 == true,
/// otherwise - in IPv6.
public class func tcpSocketForListen(_ port: in_port_t, _ forceIPv4: Bool = false, _ maxPendingConnection: Int32 = SOMAXCONN, _ listenAddress: String? = nil) throws -> Socket {
#if os(Linux)
let socketFileDescriptor = socket(forceIPv4 ? AF_INET : AF_INET6, Int32(SOCK_STREAM.rawValue), 0)
#else
let socketFileDescriptor = socket(forceIPv4 ? AF_INET : AF_INET6, SOCK_STREAM, 0)
#endif
if socketFileDescriptor == -1 {
throw SocketError.socketCreationFailed(Errno.description())
}
var value: Int32 = 1
if setsockopt(socketFileDescriptor, SOL_SOCKET, SO_REUSEADDR, &value, socklen_t(MemoryLayout<Int32>.size)) == -1 {
let details = Errno.description()
Socket.close(socketFileDescriptor)
throw SocketError.socketSettingReUseAddrFailed(details)
}
Socket.setNoSigPipe(socketFileDescriptor)
var bindResult: Int32 = -1
if forceIPv4 {
#if os(Linux)
var addr = sockaddr_in(
sin_family: sa_family_t(AF_INET),
sin_port: port.bigEndian,
sin_addr: in_addr(s_addr: in_addr_t(0)),
sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
#else
var addr = sockaddr_in(
sin_len: UInt8(MemoryLayout<sockaddr_in>.stride),
sin_family: UInt8(AF_INET),
sin_port: port.bigEndian,
sin_addr: in_addr(s_addr: in_addr_t(0)),
sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
#endif
if let address = listenAddress {
if address.withCString({ cstring in inet_pton(AF_INET, cstring, &addr.sin_addr) }) == 1 {
// print("\(address) is converted to \(addr.sin_addr).")
} else {
// print("\(address) is not converted.")
}
}
bindResult = withUnsafePointer(to: &addr) {
bind(socketFileDescriptor, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in>.size))
}
} else {
#if os(Linux)
var addr = sockaddr_in6(
sin6_family: sa_family_t(AF_INET6),
sin6_port: port.bigEndian,
sin6_flowinfo: 0,
sin6_addr: in6addr_any,
sin6_scope_id: 0)
#else
var addr = sockaddr_in6(
sin6_len: UInt8(MemoryLayout<sockaddr_in6>.stride),
sin6_family: UInt8(AF_INET6),
sin6_port: port.bigEndian,
sin6_flowinfo: 0,
sin6_addr: in6addr_any,
sin6_scope_id: 0)
#endif
if let address = listenAddress {
if address.withCString({ cstring in inet_pton(AF_INET6, cstring, &addr.sin6_addr) }) == 1 {
//print("\(address) is converted to \(addr.sin6_addr).")
} else {
//print("\(address) is not converted.")
}
}
bindResult = withUnsafePointer(to: &addr) {
bind(socketFileDescriptor, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in6>.size))
}
}
if bindResult == -1 {
let details = Errno.description()
Socket.close(socketFileDescriptor)
throw SocketError.bindFailed(details)
}
if listen(socketFileDescriptor, maxPendingConnection) == -1 {
let details = Errno.description()
Socket.close(socketFileDescriptor)
throw SocketError.listenFailed(details)
}
return Socket(socketFileDescriptor: socketFileDescriptor)
}
public func acceptClientSocket() throws -> Socket {
var addr = sockaddr()
var len: socklen_t = 0
let clientSocket = accept(self.socketFileDescriptor, &addr, &len)
if clientSocket == -1 {
throw SocketError.acceptFailed(Errno.description())
}
Socket.setNoSigPipe(clientSocket)
return Socket(socketFileDescriptor: clientSocket)
}
}
| bsd-3-clause | cea941c35b767e6a0a26a2773c0b1c99 | 38.491379 | 180 | 0.555992 | 4.297373 | false | false | false | false |
niceagency/Base | Base/BaseLayoutConstraint.swift | 1 | 9078 | //
// BaseLayoutConstraint.swift
// Base
//
// Created by Wain on 01/05/2018.
// Copyright © 2018 Nice Agency. All rights reserved.
//
import UIKit
final class BaseLayoutConstraint: NSLayoutConstraint {
private lazy var guide: UILayoutGuide = { UILayoutGuide() }()
private lazy var altConstraints: [NSLayoutConstraint] = { [] }()
@IBOutlet private var equalWidthTo: BaseLayoutConstraint?
@IBOutlet private var equalHeightTo: BaseLayoutConstraint?
override func awakeFromNib() {
super.awakeFromNib()
guide.identifier = self.identifier ?? "?.?"
self.addLayoutGuide()
if let view1 = self.secondItem as? UIView {
self.convertToLeadingConstraint(linkedView: view1)
} else if let guide1 = self.secondItem as? UILayoutGuide {
self.convertToLeadingConstraint(linkedGuide: guide1)
} else {
assertionFailure("Not connected to a view or a layout guide")
return
}
if let view2 = self.firstItem as? UIView {
self.convertToTrailingConstraint(linkedView: view2)
} else if let guide2 = self.firstItem as? UILayoutGuide {
self.convertToTrailingConstraint(linkedGuide: guide2)
} else {
assertionFailure("Not connected to a view or a layout guide")
return
}
self.applySpacingConstraints()
self.isActive = false
}
// MARK: -
private func addLayoutGuide() {
var parent: UIView?
if let view1 = self.firstItem as? UIView,
let view2 = self.secondItem as? UIView {
guard view1.superview == view2.superview else {
assertionFailure("Connected 2 views don't have the same superview")
return
}
parent = view1.superview
} else if let view1 = self.firstItem as? UIView {
parent = view1.superview
} else if let view2 = self.secondItem as? UIView {
parent = view2.superview
}
guard let superview = parent else {
assertionFailure("Parent superview not located")
return
}
superview.addLayoutGuide(guide)
}
private func convertToLeadingConstraint(linkedView view: UIView) {
let attr = self.secondAttribute
switch attr {
case .left,
.right,
.leading,
.trailing:
guide.leadingAnchor.constraint(equalTo: view.xAxisAnchor(forAttribute: attr)).isActive = true
case .leftMargin,
.rightMargin,
.leadingMargin,
.trailingMargin:
guide.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.xAxisAnchor(forAttribute: attr)).isActive = true
case .top,
.bottom:
guide.topAnchor.constraint(equalTo: view.yAxisAnchor(forAttribute: attr)).isActive = true
case .topMargin,
.bottomMargin:
guide.topAnchor.constraint(equalTo: view.layoutMarginsGuide.yAxisAnchor(forAttribute: attr)).isActive = true
default:
assertionFailure("Invalid attribute supplied")
return
}
}
private func convertToLeadingConstraint(linkedGuide: UILayoutGuide) {
let attr = self.secondAttribute
switch attr {
case .left,
.right,
.leading,
.trailing:
guide.leadingAnchor.constraint(equalTo: linkedGuide.xAxisAnchor(forAttribute: attr)).isActive = true
case .top,
.bottom:
guide.topAnchor.constraint(equalTo: linkedGuide.yAxisAnchor(forAttribute: attr)).isActive = true
default:
assertionFailure("Invalid attribute supplied")
return
}
}
private func convertToTrailingConstraint(linkedView view: UIView) {
let attr = self.firstAttribute
switch attr {
case .left,
.right,
.leading,
.trailing:
guide.trailingAnchor.constraint(equalTo: view.xAxisAnchor(forAttribute: attr)).isActive = true
case .leftMargin,
.rightMargin,
.leadingMargin,
.trailingMargin:
guide.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.xAxisAnchor(forAttribute: attr)).isActive = true
case .top,
.bottom:
guide.bottomAnchor.constraint(equalTo: view.yAxisAnchor(forAttribute: attr)).isActive = true
case .topMargin,
.bottomMargin:
guide.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.yAxisAnchor(forAttribute: attr)).isActive = true
default:
assertionFailure("Invalid attribute supplied")
return
}
}
private func convertToTrailingConstraint(linkedGuide: UILayoutGuide) {
let attr = self.firstAttribute
switch attr {
case .left,
.right,
.leading,
.trailing:
guide.trailingAnchor.constraint(equalTo: linkedGuide.xAxisAnchor(forAttribute: attr)).isActive = true
case .top,
.bottom:
guide.bottomAnchor.constraint(equalTo: linkedGuide.yAxisAnchor(forAttribute: attr)).isActive = true
default:
assertionFailure("Invalid attribute supplied")
return
}
}
private func applySpacingConstraints() {
if let width = equalWidthTo {
let constraint = guide.widthAnchor.constraint(equalTo: width.guide.widthAnchor)
if width.guide.owningView != nil {
constraint.isActive = true
} else {
width.altConstraints.append(constraint)
}
}
if let height = equalHeightTo {
let constraint = guide.heightAnchor.constraint(equalTo: height.guide.heightAnchor)
if height.guide.owningView != nil {
constraint.isActive = true
} else {
height.altConstraints.append(constraint)
}
}
altConstraints.forEach({ $0.isActive = true })
altConstraints.removeAll()
}
}
// MARK: -
private extension UIView {
private static let xMapping: [NSLayoutAttribute: ((UIView) -> NSLayoutXAxisAnchor)] = [
.left: { $0.leftAnchor },
.right: { $0.rightAnchor },
.leading: { $0.leadingAnchor },
.trailing: { $0.trailingAnchor },
.leftMargin: { $0.leftAnchor },
.rightMargin: { $0.rightAnchor },
.leadingMargin: { $0.leadingAnchor },
.trailingMargin: { $0.trailingAnchor }
]
private static let yMapping: [NSLayoutAttribute: ((UIView) -> NSLayoutYAxisAnchor)] = [
.top: { $0.topAnchor },
.bottom: { $0.bottomAnchor },
.topMargin: { $0.topAnchor },
.bottomMargin: { $0.bottomAnchor }
]
func xAxisAnchor(forAttribute attr: NSLayoutAttribute) -> NSLayoutXAxisAnchor {
guard let anchorMapping = UIView.xMapping[attr] else {
assertionFailure("Invalid attribute supplied")
return leadingAnchor
}
return anchorMapping(self)
}
func yAxisAnchor(forAttribute attr: NSLayoutAttribute) -> NSLayoutYAxisAnchor {
guard let anchorMapping = UIView.yMapping[attr] else {
assertionFailure("Invalid attribute supplied")
return topAnchor
}
return anchorMapping(self)
}
}
private extension UILayoutGuide {
private static let xMapping: [NSLayoutAttribute: ((UILayoutGuide) -> NSLayoutXAxisAnchor)] = [
.left: { $0.leftAnchor },
.right: { $0.rightAnchor },
.leading: { $0.leadingAnchor },
.trailing: { $0.trailingAnchor },
.leftMargin: { $0.leftAnchor },
.rightMargin: { $0.rightAnchor },
.leadingMargin: { $0.leadingAnchor },
.trailingMargin: { $0.trailingAnchor }
]
private static let yMapping: [NSLayoutAttribute: ((UILayoutGuide) -> NSLayoutYAxisAnchor)] = [
.top: { $0.topAnchor },
.bottom: { $0.bottomAnchor },
.topMargin: { $0.topAnchor },
.bottomMargin: { $0.bottomAnchor }
]
func xAxisAnchor(forAttribute attr: NSLayoutAttribute) -> NSLayoutXAxisAnchor {
guard let anchorMapping = UILayoutGuide.xMapping[attr] else {
assertionFailure("Invalid attribute supplied")
return leadingAnchor
}
return anchorMapping(self)
}
func yAxisAnchor(forAttribute attr: NSLayoutAttribute) -> NSLayoutYAxisAnchor {
guard let anchorMapping = UILayoutGuide.yMapping[attr] else {
assertionFailure("Invalid attribute supplied")
return topAnchor
}
return anchorMapping(self)
}
}
| mit | 30622d8330625a15379a63c6abd3ed3d | 33.382576 | 125 | 0.590283 | 5.271196 | false | false | false | false |
pivotal/cedar | Spec/Swift/SwiftSpec.swift | 1 | 6286 | import Cedar
#if !EXCLUDE_SWIFT_SPECS
/// A very simple function for making assertions since Cedar provides no
/// matchers usable from Swift
private func expectThat(_ value: Bool, file: String = #file, line: UInt = #line) {
if !value {
(CDRSpecFailure.specFailure(withReason: "Expectation failed", fileName: file, lineNumber: Int32(line)) as AnyObject).raise()
}
}
private var globalValue__: String?
/// This mirrors `SpecSpec`
class SwiftSpecSpec: CDRSpec {
override func declareBehaviors() {
describe("SwiftSpec") {
beforeEach {
// NSLog("=====================> I should run before all specs.")
}
afterEach {
// NSLog("=====================> I should run after all specs.")
}
describe("a nested spec") {
beforeEach {
// NSLog("=====================> I should run only before the nested specs.")
}
afterEach {
// NSLog("=====================> I should run only after the nested specs.")
}
it("should also run") {
// NSLog("=====================> Nested spec")
}
it("should also also run") {
// NSLog("=====================> Another nested spec")
}
}
context("a nested spec (context)") {
beforeEach {
// NSLog("=====================> I should run only before the nested specs.")
}
afterEach {
// NSLog("=====================> I should run only after the nested specs.")
}
it("should also run") {
// NSLog("=====================> Nested spec")
}
it("should also also run") {
// NSLog("=====================> Another nested spec")
}
}
it("should run") {
// NSLog("=====================> Spec")
}
it("should be pending", PENDING)
it("should also be pending", nil)
xit("should also be pending (xit)") {}
describe("described specs should be pending", PENDING)
describe("described specs should also be pending", nil)
xdescribe("xdescribed specs should be pending") {}
context("contexted specs should be pending", PENDING)
context("contexted specs should also be pending", nil)
xcontext("xcontexted specs should be pending") {};
describe("empty describe blocks should be pending") {}
context("empty context blocks should be pending") {}
}
describe("subjectAction") {
var value: Int = 0
subjectAction { value = 5 }
beforeEach {
value = 100
}
it("should run after the beforeEach") {
expectThat(value == 5)
}
describe("in a nested describe block") {
beforeEach {
value = 200
}
it("should run after all the beforeEach blocks") {
expectThat(value == 5)
}
}
}
describe("a describe block") {
beforeEach {
globalValue__ = nil
}
describe("that contains a beforeEach in a shared example group") {
itShouldBehaveLike("a describe context that contains a beforeEach in a Swift shared example group")
it("should not run the shared beforeEach before specs outside the shared example group") {
expectThat(globalValue__ == nil)
}
}
describe("that passes a value to the shared example context") {
beforeEach {
globalValue__ = "something"
CDRSpecHelper.specHelper().sharedExampleContext["value"] = globalValue__
}
itShouldBehaveLike("a Swift shared example group that receives a value in the context")
}
describe("that passes a value in-line to the shared example context") {
beforeEach {
globalValue__ = "something"
}
expectThat(globalValue__ == nil)
itShouldBehaveLike("a Swift shared example group that receives a value in the context") {
$0["value"] = globalValue__
}
}
itShouldBehaveLike("a Swift shared example group that contains a failing spec")
}
describe("a describe block that tries to include a shared example group that doesn't exist") {
expectExceptionWithReason("Unknown shared example group with description: 'a unicorn'") {
itShouldBehaveLike("a unicorn")
}
}
}
}
class SharedExampleGroupPoolForSwiftSpecs: CDRSharedExampleGroupPool {
override func declareSharedExampleGroups() {
sharedExamplesFor("a describe context that contains a beforeEach in a Swift shared example group") { _ in
beforeEach {
expectThat(CDRSpecHelper.specHelper().sharedExampleContext.count == 0)
globalValue__ = ""
}
it("should run the shared beforeEach before specs inside the shared example group") {
expectThat(globalValue__ != nil)
}
}
sharedExamplesFor("a Swift shared example group that receives a value in the context") { context in
it("should receive the values set in the global shared example context") {
expectThat((context["value"] as? String) == globalValue__)
}
}
sharedExamplesFor("a Swift shared example group that contains a failing spec") { _ in
it("should fail in the expected fashion") {
expectFailureWithMessage("Expectation failed") {
expectThat("wibble" == "wobble")
}
}
}
}
}
#endif
| mit | 5953a84153f67ef918c91a47035ada2f | 33.922222 | 132 | 0.495546 | 5.451865 | false | false | false | false |
superk589/CGSSGuide | DereGuide/Toolbox/Colleague/Model/DMSupportCard.swift | 3 | 2700 | //
// DMSupportCard.swift
// DereGuide
//
// Created by zzk on 31/08/2017.
// Copyright © 2017 zzk. All rights reserved.
//
import Foundation
import SwiftyJSON
class DMSupportCard : NSObject, NSCoding{
var all : DMLeaderCard!
var cool : DMLeaderCard!
var cute : DMLeaderCard!
var passion : DMLeaderCard!
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init(fromJson json: JSON!){
if json.isEmpty{
return
}
let allJson = json["all"]
if !allJson.isEmpty{
all = DMLeaderCard(fromJson: allJson)
}
let coolJson = json["cool"]
if !coolJson.isEmpty{
cool = DMLeaderCard(fromJson: coolJson)
}
let cuteJson = json["cute"]
if !cuteJson.isEmpty{
cute = DMLeaderCard(fromJson: cuteJson)
}
let passionJson = json["passion"]
if !passionJson.isEmpty{
passion = DMLeaderCard(fromJson: passionJson)
}
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
var dictionary = [String:Any]()
if all != nil{
dictionary["all"] = all.toDictionary()
}
if cool != nil{
dictionary["cool"] = cool.toDictionary()
}
if cute != nil{
dictionary["cute"] = cute.toDictionary()
}
if passion != nil{
dictionary["passion"] = passion.toDictionary()
}
return dictionary
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
@objc required init(coder aDecoder: NSCoder)
{
all = aDecoder.decodeObject(forKey: "all") as? DMLeaderCard
cool = aDecoder.decodeObject(forKey: "cool") as? DMLeaderCard
cute = aDecoder.decodeObject(forKey: "cute") as? DMLeaderCard
passion = aDecoder.decodeObject(forKey: "passion") as? DMLeaderCard
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
func encode(with aCoder: NSCoder)
{
if all != nil{
aCoder.encode(all, forKey: "all")
}
if cool != nil{
aCoder.encode(cool, forKey: "cool")
}
if cute != nil{
aCoder.encode(cute, forKey: "cute")
}
if passion != nil{
aCoder.encode(passion, forKey: "passion")
}
}
}
| mit | 2e6eb4cac234b9a0ff3f006073630d05 | 25.99 | 183 | 0.558355 | 4.27057 | false | false | false | false |
OlenaPianykh/Garage48KAPU | KAPU/KapuViewController.swift | 1 | 2595 | //
// KapuViewController.swift
// KAPU
//
// Created by Oleksii Pelekh on 3/4/17.
// Copyright © 2017 Vasyl Khmil. All rights reserved.
//
import UIKit
class KapuViewController: UIViewController {
var kapu: Kapu?
@IBOutlet weak var categoryNameLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var kapuCheckboxContainerHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var chartToCheckboxTopConstraint: NSLayoutConstraint!
@IBOutlet weak var chartContainerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.updateUILabels()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func updateUILabels() {
guard let kapu = self.kapu else {
return
}
self.categoryNameLabel.text = kapu.categoryName
self.titleLabel.text = kapu.title
self.authorLabel.text = kapu.creatorName
self.dateLabel.text = kapu.creationDate
}
func changeCheckboxTableViewHeight() {
chartContainerView.frame = CGRect.init(x: chartContainerView.frame.origin.x, y: chartContainerView.frame.origin.y, width: chartContainerView.frame.width, height: chartContainerView.frame.height - 70)
kapuCheckboxContainerHeightConstraint.constant -= 70
chartToCheckboxTopConstraint.constant = 5
self.view.layoutIfNeeded()
self.view.setNeedsLayout()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier, let kapu = self.kapu {
switch identifier {
case "kapuChart":
let childViewController = segue.destination as! KapuChartViewController
childViewController.kapu = kapu
break
case "kapuSelectChoice":
let childViewController = segue.destination as! KapuCheckboxTableViewController
childViewController.kapu = kapu
childViewController.kapuViewController = self
break
case "kapuDescription":
let childViewController = segue.destination as! KapuDescriptionTableViewController
childViewController.kapu = kapu
break
default: break
}
}
}
}
| mit | 2dda8c10c049233cd19265130c7d0d0c | 34.054054 | 207 | 0.654588 | 4.839552 | false | false | false | false |
ghecho/EditableTableViewController-Swift | EditableTVC.swift | 1 | 3560 | //
// EditableTVC.swift
// EditableTableViewController-Swift
//
// Created by Diego on 12/25/14.
// Copyright (c) 2014 Diego.
//
import UIKit
class EditableTVC: UITableViewController {
var myItems:NSMutableArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.editButtonItem()
for i in 0 ... 4
{
myItems.addObject(String(format: "Hey %d", i))
}
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(self.editing)
{
return myItems.count + 1
}
else
{
return myItems.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("EditableCellPrototype", forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
if(self.editing && indexPath.row == myItems.count)
{
cell.textLabel?.text = "Add ..."
}
else
{
cell.textLabel?.text = myItems[indexPath.row] as? String
}
return cell
}
// // Override to support conditional editing of the table view.
// override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// // Return NO if you do not want the specified item to be editable.
// return true
// }
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
self.tableView.reloadData()
}
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if (indexPath.row == myItems.count)
{
return UITableViewCellEditingStyle.Insert
}
else
{
return UITableViewCellEditingStyle.Delete
}
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
myItems.removeObjectAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
myItems.insertObject(String(format: "Added %ld", indexPath.row), atIndex: indexPath.row)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
}
}
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
if (toIndexPath.row == myItems.count) //we only check the toIndexPath because we made the AddCell not to respond to move events
{
var tmp = myItems[fromIndexPath.row] as String
myItems.removeObjectAtIndex(fromIndexPath.row)
myItems.insertObject(tmp, atIndex: toIndexPath.row-1) //to keep it in valid range for the NSMutableArray
self.tableView.reloadData()
}
else
{
var tmp = myItems[fromIndexPath.row] as String
myItems.removeObjectAtIndex(fromIndexPath.row)
myItems.insertObject(tmp, atIndex: toIndexPath.row)
}
}
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if (indexPath.row == myItems.count)
{
return false
}
else
{
return true
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
}
| mit | 64cf1cf37197c6011c8c7015bcd5e364 | 28.421488 | 154 | 0.730056 | 4.068571 | false | false | false | false |
andrebocchini/SwiftChatty | SwiftChatty/Requests/Client Data/SetClientDataRequest.swift | 1 | 813 | //
// SetClientDataRequest.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/28/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.
import Alamofire
/// - Attention: anyone can access this data with just a username.
/// Do not store secret or private information without encrypting it.
/// - SeeAlso - http://winchatty.com/v2/readme#_Toc421451703
public struct SetClientDataRequest: Request {
public let endpoint: ApiEndpoint = .SetClientData
public let httpMethod: HTTPMethod = .post
public var customParameters: [String : Any] = [:]
public init(withUsername username: String, client: String, data: String) {
self.customParameters["username"] = username
self.customParameters["client"] = client
self.customParameters["data"] = data
}
}
| mit | d3197902fe224ee4ae2cea6281ca596e | 31.48 | 78 | 0.703202 | 4.207254 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Common/CGSSSorter.swift | 1 | 2045 | //
// CGSSSorter.swift
// DereGuide
//
// Created by zzk on 16/7/23.
// Copyright © 2016年 zzk. All rights reserved.
//
import Foundation
struct CGSSSorter {
var property: String
var ascending: Bool
var displayName: String = ""
init(property: String, ascending: Bool) {
self.property = property
self.ascending = ascending
}
init(property: String) {
self.init(property: property, ascending: false)
}
func sortList<T: NSObject>(_ list: inout [T]) {
let compare = { (c1: T, c2: T) -> Bool in
if let i1 = c1.value(forKeyPath: self.property) as? Int, let i2 = c2.value(forKeyPath: self.property) as? Int {
return self.ascending ? (i1 < i2) : (i1 > i2)
} else if let i1 = c1.value(forKeyPath: self.property) as? Float, let i2 = c2.value(forKeyPath: self.property) as? Float {
return self.ascending ? (i1 < i2) : (i1 > i2)
} else if let s1 = c1.value(forKeyPath: self.property) as? String, let s2 = c2.value(forKeyPath: self.property) as? String {
return self.ascending ? (s1 < s2) : (s1 > s2)
}
return false
}
list.sort(by: compare)
}
func save(to path: String) {
toDictionary().write(toFile: path, atomically: true)
}
func toDictionary() -> NSDictionary {
let dict = ["property": property, "ascending": ascending, "displayName": displayName] as NSDictionary
return dict
}
init?(fromFile path: String) {
if let dict = NSDictionary.init(contentsOfFile: path) {
if let property = dict.object(forKey: "property") as? String, let ascending = dict.object(forKey: "ascending") as? Bool,
let displayName = dict.object(forKey: "displayName") as? String {
self.init(property: property, ascending: ascending)
self.displayName = displayName
return
}
}
return nil
}
}
| mit | 103c74f38e2c623ef57a8c71e5348bfa | 33.033333 | 136 | 0.573947 | 3.889524 | false | false | false | false |
ylankgz/safebook | Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Defaults.swift | 100 | 739 | //
// Defaults.swift
// Keinex
//
// Created by Андрей on 07.08.16.
// Copyright © 2016 Keinex. All rights reserved.
//
import Foundation
import UIKit
let userDefaults = UserDefaults.standard
let isiPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
let latestPostValue = "postValue"
//Sources
let sourceUrl:NSString = "SourceUrlDefault"
let sourceUrlKeinexRu:NSString = "https://gist.githubusercontent.com/ylankgz/f22089e4824a0845da64a7978736eab8/raw/0b62781babd25e232aab83d5f6660a471ac8f9bb/data.json"
let sourceUrlKeinexCom:NSString = "https://gist.githubusercontent.com/ylankgz/f22089e4824a0845da64a7978736eab8/raw/0b62781babd25e232aab83d5f6660a471ac8f9bb/data.json"
let autoDelCache:NSString = "none"
| mit | 681c98fe978bccb15bc5600c723abb04 | 35.6 | 166 | 0.815574 | 2.837209 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.