repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
appnexus/mobile-sdk-ios | tests/TrackerUITest/UITestApp/AdsViewController/PlacementTest/NativeAdViewController.swift | 1 | 3546 | /* Copyright 2019 APPNEXUS 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 UIKit
import AppNexusSDK
class NativeAdViewController: UIViewController , ANNativeAdRequestDelegate, ANNativeAdDelegate {
func adRequest(_ request: ANNativeAdRequest, didFailToLoadWithError error: Error, with adResponseInfo: ANAdResponseInfo?) {
}
var nativeAdRequest = ANNativeAdRequest()
var nativeAdResponse = ANNativeAdResponse()
var adKey : String = ""
// MARK: IBOutlets
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var viewNative: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var bodyLabel: UILabel!
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var callToActionButton: UIButton!
@IBOutlet weak var sponsoredLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Native Ad"
if ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.NativeAd.testRTBNative) {
adKey = PlacementTestConstants.NativeAd.testRTBNative
initialiseNative()
}
// Do any additional setup after loading the view.
}
func initialiseNative() {
let nativeAdObject : NativeAdObject! = AdObjectModel.decodeNativeObject()
if nativeAdObject != nil {
viewNative.isHidden = true
nativeAdRequest = ANNativeAdRequest()
nativeAdRequest.forceCreativeId = 154679174
nativeAdRequest.placementId = nativeAdObject?.adObject.placement
nativeAdRequest.shouldLoadIconImage = (nativeAdObject?.shouldLoadIconImage)!
nativeAdRequest.shouldLoadMainImage = (nativeAdObject?.shouldLoadMainImage)!
nativeAdRequest.delegate = self
nativeAdRequest.loadAd()
}
}
// MARK: ANNativeAdRequestDelegate
func adRequest(_ request: ANNativeAdRequest, didReceive response: ANNativeAdResponse) {
activityIndicator.stopAnimating()
viewNative.alpha = 1
viewNative.isHidden = false
self.nativeAdResponse = response
self.titleLabel.text = self.nativeAdResponse.title
self.sponsoredLabel.text = self.nativeAdResponse.sponsoredBy
self.bodyLabel.text = self.nativeAdResponse.body
self.iconImageView.image = self.nativeAdResponse.iconImage
self.mainImageView.image = self.nativeAdResponse.mainImage
callToActionButton.setTitle(self.nativeAdResponse.callToAction, for: .normal)
nativeAdResponse.delegate = self
do {
try nativeAdResponse.registerView(forTracking: self.viewNative, withRootViewController: self, clickableViews: [callToActionButton])
} catch let error as NSError {
print(error)
}
}
func adRequest(_ request: ANNativeAdRequest, didFailToLoadWithError error: Error) {
print("requestFailedWithError \(String(describing: error))")
}
}
| apache-2.0 | 29008c7b8ddba5f4c86797a91e07cef0 | 38.842697 | 143 | 0.714608 | 5.022663 | false | false | false | false |
pyanfield/ataturk_olympic | swift_programming_initialization_deinitialization.playground/section-1.swift | 1 | 8144 | // Playground - noun: a place where people can play
import UIKit
// 2.14 构造过程(Initialization)
// 与 Objective-C 中的构造器不同,Swift 的构造器无需返回值,它们的主要任务是保证新实例在第一次使用前完成正确的初始化。
// 当你为存储型属性设置默认值或者在构造器中为其赋值时,它们的值是被直接设置的,不会触发任何属性观测器(property observers)。
// 可以通过输入参数和可选属性类型来定制构造过程,也可以在构造过程中修改常量属性。
// 构造器并不像函数和方法那样在括号前有一个可辨别的名字。所以在调用构造器时,主要通过构造器中的参数名和类型来确定需要调用的构造器。
// 正因为参数如此重要,如果你在定义构造器时没有提供参数的外部名字,Swift 会为每个构造器的参数自动生成一个跟内部名字相同的外部名,就相当于在每个构造参数之前加了一个哈希符号。
// 如果你不希望为构造器的某个参数提供外部名字,你可以使用下划线_来显示描述它的外部名,以此覆盖上面所说的默认行为。
struct Celsius {
var temperatureInCelsius: Double = 0.0
// 如果一个属性在声明的时候没有初始值,而在构造函数中也没有设置初始值,则表示该属性可能为 nil,默认值为 nil,应该声明成 optional type
var value: String?
// 对某个类实例来说,它的常量属性只能在定义它的类的构造过程中修改;不能在子类中修改。如果声明的时候没有设置初始值,则必须在构造函数中设置。
let hello: String
let number: Int = 0
// 两个 init 构造函数都含有唯一的 Double 类型的参数,但是参数名称不同,所以没有冲突
// 如果是普通的方法,不能有重复的方法名出现
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
hello = "temperatureInCelsius"
// 在构造函数中可以对常量重新赋值
number = Int(fahrenheit)
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
hello = "temperatureInCelsius"
}
init(_ name: String){
println(name);
hello = name
}
}
// 结构体对所有存储型属性提供了默认值且自身没有提供定制的构造器,它们能自动获得一个逐一成员构造器。
struct Size {
var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)
// 如果你为某个值类型定义了一个定制的构造器,你将无法访问到默认构造器(如果是结构体,则无法访问逐一对象构造器)。
// 这个限制可以防止你在为值类型定义了一个更复杂的,完成了重要准备构造器之后,别人还是错误的使用了那个自动生成的构造器。
// “Designated Initializers and Convenience Initializers”
// Swift 提供了两种类型的类构造器来确保所有类实例中存储型属性都能获得初始值,它们分别是指定构造器和便利构造器。
// 每一个类都必须拥有至少一个指定构造器。在某些情况下,许多类通过继承了父类中的指定构造器而满足了这个条件。
// 便利构造器是类中比较次要的、辅助型的构造器。你可以定义便利构造器来调用同一个类中的指定构造器,并为其参数提供默认值。你也可以定义便利构造器来创建一个特殊用途或特定输入的实例。
// 指定构造器必须总是向上代理
// 便利构造器必须总是横向代理
// Swift 中类的构造过程包含两个阶段。
// 第一个阶段,每个存储型属性通过引入它们的类的构造器来设置初始值。当每一个存储型属性值被确定后,
// 第二阶段开始,它给每个类一次机会在新实例准备使用之前进一步定制它们的存储型属性。
// 两段式构造过程的使用让构造过程更安全,同时在整个类层级结构中给予了每个类完全的灵活性。
// 两段式构造过程可以防止属性值在初始化之前被访问;也可以防止属性被另外一个构造器意外地赋予不同的值。
// 跟 Objective-C 中的子类不同,Swift 中的子类不会默认继承父类的构造器。Swift 的这种机制可以防止一个父类的简单构造器被一个更专业的子类继承,并被错误的用来创建子类的实例。
// 如果你重载的构造器是一个指定构造器,你可以在子类里重载它的实现,并在自定义版本的构造器中调用父类版本的构造器。
// 如果你重载的构造器是一个便利构造器,你的重载过程必须通过调用同一类中提供的其它指定构造器来实现。
// 与方法、属性和下标不同,在重载构造器时你没有必要使用关键字 override 。
// 类的指定构造器的写法跟值类型简单构造器一样:
// init(parameters) {
// statements
// }
// 便利构造器也采用相同样式的写法,但需要在init关键字之前放置 convenience 关键字,并使用空格将它们俩分开:
// convenience init(parameters) {
// statements
// }
// 通过闭包和函数来设置属性的默认值
// 如果某个存储型属性的默认值需要特别的定制或准备,你就可以使用闭包或全局函数来为其属性提供定制的默认值。
struct Checkerboard {
// 注意这里的闭包设置属性
// 如果你使用闭包来初始化属性的值,请记住在闭包执行时,实例的其它部分都还没有初始化。
// 这意味着你不能够在闭包里访问其它的属性,就算这个属性有默认值也不允许。
// 同样,你也不能使用隐式的self属性,或者调用其它的实例方法。
let boardColors: [Bool] = {
var temporaryBoard = [Bool]()
var isBlack = false
for i in 1...10 {
for j in 1...10 {
temporaryBoard.append(isBlack)
isBlack = !isBlack
}
isBlack = !isBlack
}
return temporaryBoard
}() // 结尾括号,表示执行该闭包,只有执行了该闭包,才是真正的将执行结果赋值了
func squareIsBlackAtRow(row: Int, column: Int) -> Bool {
return boardColors[(row * 10) + column]
}
}
// 2.15 析构过程(Deinitialization)
// 在一个类的实例被释放之前,析构函数被立即调用。用关键字deinit来标示析构函数,类似于初始化函数用init来标示。析构函数只适用于类类型。
// 在类的定义中,每个类最多只能有一个析构函数。析构函数不带任何参数,在写法上不带括号:
// deinit {
// // 执行析构过程
// }
// 析构函数是在实例释放发生前一步被自动调用。不允许主动调用自己的析构函数。
struct Bank {
static var coinsInBank = 10_000
static func vendCoins(var numberOfCoinsToVend: Int) -> Int {
numberOfCoinsToVend = min(numberOfCoinsToVend, coinsInBank)
coinsInBank -= numberOfCoinsToVend
return numberOfCoinsToVend
}
static func receiveCoins(coins: Int) {
coinsInBank += coins
}
}
class Player {
var coinsInPurse: Int
init(coins: Int) {
coinsInPurse = Bank.vendCoins(coins)
}
func winCoins(coins: Int) {
coinsInPurse += Bank.vendCoins(coins)
}
deinit {
Bank.receiveCoins(coinsInPurse)
}
}
var playerOne: Player? = Player(coins: 100)
println("A new player has joined the game with \(playerOne!.coinsInPurse) coins")
println("There are now \(Bank.coinsInBank) coins left in the bank")
playerOne!.winCoins(2_000)
println("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins")
println("The bank now only has \(Bank.coinsInBank) coins left")
playerOne = nil
println("PlayerOne has left the game")
println("The bank now has \(Bank.coinsInBank) coins") | mit | 3244b3a4c2c55afe7985b89e100c2a5b | 31.838028 | 99 | 0.711712 | 2.635387 | false | false | false | false |
vanfanel/RetroArch | pkg/apple/OnScreenKeyboard/EmulatorKeyboardButton.swift | 6 | 1763 | //
// KeyboardButton.swift
// RetroArchiOS
//
// Created by Yoshi Sugawara on 3/3/22.
// Copyright © 2022 RetroArch. All rights reserved.
//
import UIKit
class EmulatorKeyboardButton: UIButton {
let key: KeyCoded
var toggleState = false
// MARK: - Functions
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let newArea = CGRect(
x: self.bounds.origin.x - 5.0,
y: self.bounds.origin.y - 5.0,
width: self.bounds.size.width + 20.0,
height: self.bounds.size.height + 20.0
)
return newArea.contains(point)
}
private func updateColors() {
backgroundColor = isHighlighted ? EmulatorKeyboardView.keyPressedBackgroundColor : isSelected ? EmulatorKeyboardView.keySelectedBackgroundColor : EmulatorKeyboardView.keyNormalBackgroundColor
layer.borderColor = (isHighlighted ? EmulatorKeyboardView.keyPressedBorderColor : isSelected ? EmulatorKeyboardView.keySelectedBorderColor : EmulatorKeyboardView.keyNormalBorderColor).cgColor
titleLabel?.textColor = isHighlighted ? EmulatorKeyboardView.keyPressedTextColor : isSelected ? EmulatorKeyboardView.keySelectedTextColor : EmulatorKeyboardView.keyNormalTextColor
titleLabel?.tintColor = titleLabel?.textColor
}
override open var isHighlighted: Bool {
didSet {
updateColors()
}
}
override open var isSelected: Bool {
didSet {
updateColors()
}
}
required init(key: KeyCoded) {
self.key = key
super.init(frame: .zero)
updateColors()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-3.0 | 7ed6d4a63176af7757182bcf6d81416f | 32.245283 | 199 | 0.667991 | 4.840659 | false | false | false | false |
madcato/OSFramework | Sources/OSFramework/String+subscript.swift | 1 | 931 | //
// String+subscript.swift
// happic-ios
//
// Created by Daniel Vela on 29/04/16.
// Copyright © 2016 Daniel Vela. All rights reserved.
//
import Foundation
extension String {
var length: Int {
return self.count
}
subscript(integerIndex: Int) -> Character {
let index = self.index(startIndex, offsetBy: integerIndex)
return self[index]
}
subscript(integerRange: Range<Int>) -> String {
let start = self.index(startIndex, offsetBy: integerRange.lowerBound)
let end = self.index(startIndex, offsetBy: integerRange.upperBound)
let range = start..<end
return String(self[range])
}
func makeRange(_ integerRange: Range<Int>) -> Range<String.Index> {
let start = self.index(startIndex, offsetBy: integerRange.lowerBound)
let end = self.index(startIndex, offsetBy: integerRange.upperBound)
return start..<end
}
}
| mit | d52c5995694179a55204403125926fee | 27.181818 | 77 | 0.653763 | 4.170404 | false | false | false | false |
dehesa/Metal | commands/Sources/Inspector/main.swift | 1 | 2617 | import Cocoa
import Metal
var result = String()
for device in MTLCopyAllDevices() {
result.append("\n\(device.name)")
// GPU location
result.append("\n\t\(device.location) GPU")
var properties: [String] = []
if (device.isLowPower) { properties.append("low power") }
if (device.isHeadless) { properties.append("headless") }
if (device.isRemovable) { properties.append("removable") }
if !properties.isEmpty {
result.append(" (" + properties.joined(separator: ", ") + ")")
}
// GPU memory
if device.hasUnifiedMemory {
result.append("\n\tUnified memory (shared with CPU)")
} else {
result.append("\n\tDiscrete memory")
}
result.append("\n\t\tmax recommended working set: \(bytes: device.recommendedMaxWorkingSetSize)")
if device.maxTransferRate > 0 {
result.append("\n\t\tmax transfer rate: \(bytes: device.maxTransferRate)/s")
}
// Feature set support
result.append("\n\tFeature set support")
var families: [String] = []
if device.supportsFamily(.common1) { families.append("common 1") }
if device.supportsFamily(.common2) { families.append("common 2") }
if device.supportsFamily(.common3) { families.append("common 3") }
if device.supportsFamily(.mac1) { families.append("mac 1") }
if device.supportsFamily(.mac2) { families.append("mac 2") }
result.append("\n\t\tfamily: \(families.joined(separator: ", "))")
var sets: [String] = []
if device.supportsFeatureSet(.macOS_GPUFamily1_v1) { sets.append("1v1") }
if device.supportsFeatureSet(.macOS_GPUFamily1_v2) { sets.append("1v2") }
if device.supportsFeatureSet(.macOS_GPUFamily1_v3) { sets.append("1v3") }
if device.supportsFeatureSet(.macOS_GPUFamily1_v4) { sets.append("1v4") }
if device.supportsFeatureSet(.macOS_GPUFamily2_v1) { sets.append("2v1") }
result.append("\n\t\tsets: \(sets.joined(separator: ", "))")
// Computing
result.append("\n\tGeneral Purpose Computing")
result.append("\n\t\tmax threadgroup memory: \(bytes: .init(device.maxThreadgroupMemoryLength))")
let t = device.maxThreadsPerThreadgroup
result.append("\n\t\tmax threads per threadgroup: [\(t.width), \(t.height), \(t.depth)]")
let computeDescriptor = MTLComputePipelineDescriptor().set {
$0.label = "io.dehesa.metal.commandline.gpgpu.detector.compute.pipeline"
$0.computeFunction = device.makeDefaultLibrary()!.makeFunction(name: "empty")!
}
let pipeline = try! device.makeComputePipelineState(descriptor: computeDescriptor, options: [], reflection: nil)
result.append("\n\t\tthreads execution width: \(pipeline.threadExecutionWidth)")
result.append("\n")
}
print(result)
| mit | fdda395deb8ef66eb039158810b0ded1 | 38.059701 | 114 | 0.702331 | 3.470822 | false | false | false | false |
Pluto-Y/SwiftyEcharts | SwiftyEchartsTest_iOS/CalendarSpec.swift | 1 | 15957 | //
// CalendarSpec.swift
// SwiftyEcharts
//
// Created by Pluto Y on 21/09/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
import Quick
import Nimble
@testable import SwiftyEcharts
class CalendarSpec: QuickSpec {
override func spec() {
let showLabelValue = true
let firstDayLabelValue: UInt8 = 1
let marginLabelValue: Float = 2.0
let positionLabelValue = Position.start
let nameMapLabelValue = "en"
let colorLabelValue = rgb(200, 172, 27)
let formatterLabelValue = Formatter.string("formatterLabelValue")
let fontStyleLabelValue = FontStyle.oblique
let fontWeightLabelValue = FontWeight.bolder
let fontFamilyLabelValue = "labelFontFamilyValue"
let fontSizeLabelValue: UInt = 22
let alignLabelValue = Align.right
let verticalAlignLabelValue = VerticalAlign.top
let lineHeightLabelValue: Float = 56
let backgroundColorLabelValue = Color.red
let borderColorLabelValue = Color.hexColor("#fff")
let borderWidthLabelValue: Float = 2.0
let borderRadiusLabelValue: Float = 5
let paddingLabelValue: Padding = [3, 4, 3, 4]
let shadowColorLabelValue = Color.yellow
let shadowBlurLabelValue: Float = 8.88
let shadowOffsetXLabelValue: Float = 2.0
let shadowOffsetYLabelValue: Float = 8.88888
let widthLabelValue: LengthValue = 80%
let heightLabelValue: LengthValue = 20
let textBorderColorLabelValue = Color.rgb(100, 100, 100)
let textBorderWidthLabelValue: Float = 84.0
let textShadowColorLabelValue: Color = rgba(88, 99, 0, 0.27)
let textShadowBlurLabelValue: Float = 82.0
let textShadowOffsetXLabelValue: Float = 8247734.29387492
let textShadowOffsetYLabelValue: Float = 0.023842397
let richLabelValue: [String: Jsonable] = [
"a": ["color": "red", "lineHeight": 10],
"b": ["backgroundColor": ["image": "xxx/xxx.jpg"], "height": 40],
"x": ["fontSize": 40, "fontFamily": "Microsoft YaHei", "borderColor": "#449933"]
]
let baseLabel = Calendar.BaseLabel()
baseLabel.show = showLabelValue
baseLabel.firstDay = firstDayLabelValue
baseLabel.margin = marginLabelValue
baseLabel.position = positionLabelValue
baseLabel.nameMap = OneOrMore(one: nameMapLabelValue)
baseLabel.color = colorLabelValue
baseLabel.formatter = formatterLabelValue
baseLabel.fontStyle = fontStyleLabelValue
baseLabel.fontWeight = fontWeightLabelValue
baseLabel.fontFamily = fontFamilyLabelValue
baseLabel.fontSize = fontSizeLabelValue
baseLabel.align = alignLabelValue
baseLabel.verticalAlign = verticalAlignLabelValue
baseLabel.lineHeight = lineHeightLabelValue
baseLabel.backgroundColor = backgroundColorLabelValue
baseLabel.borderColor = borderColorLabelValue
baseLabel.borderWidth = borderWidthLabelValue
baseLabel.borderRadius = borderRadiusLabelValue
baseLabel.padding = paddingLabelValue
baseLabel.shadowColor = shadowColorLabelValue
baseLabel.shadowBlur = shadowBlurLabelValue
baseLabel.shadowOffsetX = shadowOffsetXLabelValue
baseLabel.shadowOffsetY = shadowOffsetYLabelValue
baseLabel.width = widthLabelValue
baseLabel.height = heightLabelValue
baseLabel.textBorderColor = textBorderColorLabelValue
baseLabel.textBorderWidth = textBorderWidthLabelValue
baseLabel.textShadowColor = textShadowColorLabelValue
baseLabel.textShadowBlur = textShadowBlurLabelValue
baseLabel.textShadowOffsetX = textShadowOffsetXLabelValue
baseLabel.textShadowOffsetY = textShadowOffsetYLabelValue
baseLabel.rich = richLabelValue
describe("For BarSerie.BaseLabel") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"show": showLabelValue,
"firstDay": firstDayLabelValue,
"margin": marginLabelValue,
"position": positionLabelValue,
"nameMap": nameMapLabelValue,
"color": colorLabelValue,
"formatter": formatterLabelValue,
"fontStyle": fontStyleLabelValue,
"fontWeight": fontWeightLabelValue,
"fontFamily": fontFamilyLabelValue,
"fontSize": fontSizeLabelValue,
"align": alignLabelValue,
"verticalAlign": verticalAlignLabelValue,
"lineHeight": lineHeightLabelValue,
"backgroundColor": backgroundColorLabelValue,
"borderColor": borderColorLabelValue,
"borderWidth": borderWidthLabelValue,
"borderRadius": borderRadiusLabelValue,
"padding": paddingLabelValue,
"shadowColor": shadowColorLabelValue,
"shadowBlur": shadowBlurLabelValue,
"shadowOffsetX": shadowOffsetXLabelValue,
"shadowOffsetY": shadowOffsetYLabelValue,
"width": widthLabelValue,
"height": heightLabelValue,
"textBorderColor": textBorderColorLabelValue,
"textBorderWidth": textBorderWidthLabelValue,
"textShadowColor": textShadowColorLabelValue,
"textShadowBlur": textShadowBlurLabelValue,
"textShadowOffsetX": textShadowOffsetXLabelValue,
"textShadowOffsetY": textShadowOffsetYLabelValue,
"rich": richLabelValue
]
expect(baseLabel.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let baseLabelByEnums = Calendar.BaseLabel(
.show(showLabelValue),
.firstDay(firstDayLabelValue),
.margin(marginLabelValue),
.position(positionLabelValue),
.nameMap(nameMapLabelValue),
.color(colorLabelValue),
.formatter(formatterLabelValue),
.fontStyle(fontStyleLabelValue),
.fontWeight(fontWeightLabelValue),
.fontFamily(fontFamilyLabelValue),
.fontSize(fontSizeLabelValue),
.align(alignLabelValue),
.verticalAlign(verticalAlignLabelValue),
.lineHeight(lineHeightLabelValue),
.backgroundColor(backgroundColorLabelValue),
.borderColor(borderColorLabelValue),
.borderWidth(borderWidthLabelValue),
.borderRadius(borderRadiusLabelValue),
.padding(paddingLabelValue),
.shadowColor(shadowColorLabelValue),
.shadowBlur(shadowBlurLabelValue),
.shadowOffsetX(shadowOffsetXLabelValue),
.shadowOffsetY(shadowOffsetYLabelValue),
.width(widthLabelValue),
.height(heightLabelValue),
.textBorderColor(textBorderColorLabelValue),
.textBorderWidth(textBorderWidthLabelValue),
.textShadowColor(textShadowColorLabelValue),
.textShadowBlur(textShadowBlurLabelValue),
.textShadowOffsetX(textShadowOffsetXLabelValue),
.textShadowOffsetY(textShadowOffsetYLabelValue),
.rich(richLabelValue)
)
expect(baseLabelByEnums.jsonString).to(equal(baseLabel.jsonString))
}
it("needs to check the nameMaps enum case") {
let nameMapsLabelValue: [String] = [
"一月", "二月", "三月",
"四月", "五月", "六月",
"七月", "八月", "九月",
"十月", "十一月", "十二"
]
baseLabel.nameMap = OneOrMore(more: nameMapsLabelValue)
let baseLabelByEnums = Calendar.BaseLabel(
.show(showLabelValue),
.firstDay(firstDayLabelValue),
.margin(marginLabelValue),
.position(positionLabelValue),
.nameMaps(nameMapsLabelValue),
.color(colorLabelValue),
.formatter(formatterLabelValue),
.fontStyle(fontStyleLabelValue),
.fontWeight(fontWeightLabelValue),
.fontFamily(fontFamilyLabelValue),
.fontSize(fontSizeLabelValue),
.align(alignLabelValue),
.verticalAlign(verticalAlignLabelValue),
.lineHeight(lineHeightLabelValue),
.backgroundColor(backgroundColorLabelValue),
.borderColor(borderColorLabelValue),
.borderWidth(borderWidthLabelValue),
.borderRadius(borderRadiusLabelValue),
.padding(paddingLabelValue),
.shadowColor(shadowColorLabelValue),
.shadowBlur(shadowBlurLabelValue),
.shadowOffsetX(shadowOffsetXLabelValue),
.shadowOffsetY(shadowOffsetYLabelValue),
.width(widthLabelValue),
.height(heightLabelValue),
.textBorderColor(textBorderColorLabelValue),
.textBorderWidth(textBorderWidthLabelValue),
.textShadowColor(textShadowColorLabelValue),
.textShadowBlur(textShadowBlurLabelValue),
.textShadowOffsetX(textShadowOffsetXLabelValue),
.textShadowOffsetY(textShadowOffsetYLabelValue),
.rich(richLabelValue)
)
expect(baseLabelByEnums.jsonString).to(equal(baseLabel.jsonString))
}
}
describe("For Calendar") {
let zlevelValue: Float = 2.0
let zValue: Float = 0.00002384782
let leftValue = Position.right
let topValue = Position.bottom
let rightValue = Position.left
let bottomValue = Position.top
let widthValue: LengthValue = 20%
let heightValue: LengthValue = 80
let rangeValue: Jsonable = 2017
let cellSizeValue: Float = 20
let orientValue = Orient.horizontal
let splitLineValue = SplitLine(
.show(false),
.lineStyle(LineStyle(
.show(false),
.width(20)
))
)
let itemStyleValue = ItemStyle(
.normal(CommonItemStyleContent(
.opacity(0.23878),
.shadowOffsetX(283.0),
.borderColor(Color.red),
.borderType(LineType.dotted),
.areaColor(Color.yellow)
))
)
let dayLabelValue = baseLabel
let monthLabelValue = MonthLabel(
.show(true),
.position(Position.end),
.margin(8.0),
.nameMap("cn"),
.fontStyle(FontStyle.normal),
.fontWeight(FontWeight.bold)
)
let yearLabelValue = YearLabel(
.align(Align.left),
.verticalAlign(VerticalAlign.bottom),
.lineHeight(74.829),
.shadowBlur(20.000),
.textShadowBlur(8.00)
)
let silentValue = true
let calendar = Calendar()
calendar.zlevel = zlevelValue
calendar.z = zValue
calendar.left = leftValue
calendar.top = topValue
calendar.right = rightValue
calendar.bottom = bottomValue
calendar.width = widthValue
calendar.height = heightValue
calendar.range = rangeValue
calendar.cellSize = OneOrMore(one: cellSizeValue)
calendar.orient = orientValue
calendar.splitLine = splitLineValue
calendar.itemStyle = itemStyleValue
calendar.dayLabel = dayLabelValue
calendar.monthLabel = monthLabelValue
calendar.yearLabel = yearLabelValue
calendar.silent = silentValue
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"zlevel": zlevelValue,
"z": zValue,
"left": leftValue,
"top": topValue,
"right": rightValue,
"bottom": bottomValue,
"width": widthValue,
"height": heightValue,
"range": rangeValue,
"cellSize": cellSizeValue,
"orient": orientValue,
"splitLine": splitLineValue,
"itemStyle": itemStyleValue,
"dayLabel": dayLabelValue,
"monthLabel": monthLabelValue,
"yearLabel": yearLabelValue,
"silent": silentValue
]
expect(calendar.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let calendarByEnums = Calendar(
.zlevel(zlevelValue),
.z(zValue),
.left(leftValue),
.top(topValue),
.right(rightValue),
.bottom(bottomValue),
.width(widthValue),
.height(heightValue),
.range(rangeValue),
.cellSize(cellSizeValue),
.orient(orientValue),
.splitLine(splitLineValue),
.itemStyle(itemStyleValue),
.dayLabel(dayLabelValue),
.monthLabel(monthLabelValue),
.yearLabel(yearLabelValue),
.silent(silentValue)
)
expect(calendarByEnums.jsonString).to(equal(calendar.jsonString))
}
it("needs to check the cellSizes enum case") {
let cellSizesValue: [Jsonable] = [20, 40]
calendar.cellSize = OneOrMore(more: cellSizesValue)
let calendarByEnums = Calendar(
.zlevel(zlevelValue),
.z(zValue),
.left(leftValue),
.top(topValue),
.right(rightValue),
.bottom(bottomValue),
.width(widthValue),
.height(heightValue),
.range(rangeValue),
.cellSizes(cellSizesValue),
.orient(orientValue),
.splitLine(splitLineValue),
.itemStyle(itemStyleValue),
.dayLabel(dayLabelValue),
.monthLabel(monthLabelValue),
.yearLabel(yearLabelValue),
.silent(silentValue)
)
expect(calendarByEnums.jsonString).to(equal(calendar.jsonString))
}
}
}
}
| mit | ae35cb45a4f299351057d861b4362daf | 43.932203 | 92 | 0.54294 | 5.975207 | false | false | false | false |
backsofangels/cardsagainstios | cardsagainsthumanity/GameScene.swift | 1 | 1070 | //
// GameScene.swift
// cardsagainsthumanity
//
// Created by Salvatore Penitente on 06/06/2017.
// Copyright © 2017 Salvatore Penitente. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
let title = SKSpriteNode(imageNamed: "Title")
let joinGameButton = SKSpriteNode(imageNamed: "JoinGame")
let createGameButton = SKSpriteNode(imageNamed: "CreateGame")
override func didMove(to view: SKView) {
backgroundColor = UIColor(red:0.31, green:0.31, blue:0.31, alpha:1.0)
title.position = CGPoint(x: 0, y: 235)
addChild(title)
createGameButton.position = CGPoint(x: title.position.x, y: title.position.y - 430)
addChild(createGameButton)
joinGameButton.position = CGPoint(x: createGameButton.position.x, y: createGameButton.position.y - 195)
let joinGameSize = joinGameButton.size
joinGameButton.size.height = joinGameSize.height * 1.014
joinGameButton.size.width = joinGameSize.width * 1.014
addChild(joinGameButton)
}
}
| mit | cf356622af4282df78a4a066bd906d04 | 34.633333 | 111 | 0.694107 | 3.79078 | false | false | false | false |
byu-oit/ios-byuSuite | byuSuite/Apps/JobOpenings/controller/JobOpeningsCategoriesViewController.swift | 1 | 1088 | //
// JobOpeningsCategoriesViewController.swift
// byuSuite
//
// Created by Alex Boswell on 2/16/18.
// Copyright © 2018 Brigham Young University. All rights reserved.
//
class JobOpeningsCategoriesViewController: ByuTableDataViewController {
//MARK: View controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
loadCategories()
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showCategory",
let category: JobOpeningsCategory = objectForSender(tableView: tableView, cellSender: sender),
let vc = segue.destination as? JobOpeningsFamilyViewController {
vc.category = category
}
}
//MARK: Custom Methods
private func loadCategories() {
JobOpeningsClient.getJobCategories { (categories, error) in
self.spinner?.stopAnimating()
if let categories = categories {
self.tableData = TableData(rows: categories.map { Row(text: $0.siteDescription, object: $0) })
self.tableView.reloadData()
} else {
super.displayAlert(error: error)
}
}
}
}
| apache-2.0 | be00f2fd75f41288c14719e211dfc469 | 26.871795 | 98 | 0.721251 | 3.840989 | false | false | false | false |
manfengjun/KYMart | Section/Mine/View/KYMemberTVCell.swift | 1 | 1539 | //
// KYMemberTVCell.swift
// KYMart
//
// Created by JUN on 2017/7/4.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class KYMemberTVCell: UITableViewCell {
@IBOutlet weak var headIV: UIImageView!
@IBOutlet weak var nickNameL: UILabel!
@IBOutlet weak var phoneL: UILabel!
@IBOutlet weak var timeL: UILabel!
@IBOutlet weak var userIDL: UILabel!
var model:List? {
didSet {
if let text = model?.head_pic {
if text.hasSuffix("http") {
let imageUrl = URL(string: text)
headIV.sd_setImage(with: imageUrl, placeholderImage: nil)
}
else{
let imageUrl = URL(string: imgPath + text)
headIV.sd_setImage(with: imageUrl, placeholderImage: nil)
}
}
if let text = model?.nickname {
nickNameL.text = "昵称:" + text
}
if let text = model?.reg_time {
timeL.text = "加盟时间:" + String(text).timeStampToString()
}
if let text = model?.user_id {
userIDL.text = "会员ID:\(text)"
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 655a039e49db71d8ae2b23025b99a7af | 26.527273 | 77 | 0.531044 | 4.426901 | false | false | false | false |
IrenaChou/IRDouYuZB | IRDouYuZBSwift/IRDouYuZBSwift/Classes/Public/ViewModel/IRBaseViewModel.swift | 1 | 1431 | //
// IRBaseViewModel.swift
// IRDouYuZBSwift
//
// Created by zhongdai on 2017/1/20.
// Copyright © 2017年 ir. All rights reserved.
//
import UIKit
class IRBaseViewModel {
// MARK:- 懒加载属性
lazy var anchorGroups : [IRAnchorGroup] = [IRAnchorGroup]()
}
// MARK: - 发送网络数据
extension IRBaseViewModel {
func loadData(isGroupData: Bool? = true, urlString : String,parameters : [String:Any]? = nil,finishCallBack: @escaping ()->()){
NetworkTools.requestData(type: MethodType.Get, URLString: urlString,parameter: parameters) { (result) in
guard let resultDict = result as? [ String : Any ] else { return }
guard let dataArray = resultDict["data"] as? [[String:Any]] else {return}
if isGroupData! {
for dict in dataArray{
let group = IRAnchorGroup(dict: dict)
if(group.tag_name == "颜值"){
continue
}
self.anchorGroups.append(group)
}
}else{
let group = IRAnchorGroup()
for dict in dataArray{
group.anchors.append(IRAnchorModel(dict: dict))
}
self.anchorGroups.append(group)
}
finishCallBack()
}
}
}
| mit | 905e9ad13270bbc5769f4df4ee776a6f | 28.208333 | 131 | 0.512126 | 4.868056 | false | false | false | false |
balazs630/Bad-Jokes | BadJokes/Custom Types/CopyableLabel.swift | 1 | 1519 | //
// CopyableLabel.swift
// BadJokes
//
// Created by Horváth Balázs on 2018. 06. 22..
// Copyright © 2018. Horváth Balázs. All rights reserved.
//
import UIKit
class CopyableLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
func sharedInit() {
isUserInteractionEnabled = true
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(self.showMenu)))
}
@objc func showMenu(sender: AnyObject?) {
self.becomeFirstResponder()
let menu = UIMenuController.shared
if !menu.isMenuVisible {
menu.setTargetRect(bounds, in: self)
menu.setMenuVisible(true, animated: true)
}
}
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == #selector(UIResponderStandardEditActions.copy)
}
override func copy(_ sender: Any?) {
UIPasteboard.general.string = self.text
UIMenuController.shared.setMenuVisible(false, animated: true)
requestStoreReview()
}
private func requestStoreReview() {
let trigger = StoreReviewTrigger(name: UserDefaults.Key.StoreReviewTrigger.copyJoke, rules: [])
StoreReviewService.requestTimedReview(for: trigger)
}
}
| apache-2.0 | a0799def3d38e9189335ad0b5d073d8f | 26.527273 | 106 | 0.656539 | 4.67284 | false | false | false | false |
SamirTalwar/advent-of-code | 2018/AOC_16_2.swift | 1 | 4649 | import Foundation
let beforeAfterParser = try! RegExp(pattern: "^\\w+: +\\[([0-9, ]+)\\]$")
typealias OpCode = Int
let allOpCodes: [OpCode] = Array(0 ..< 16)
typealias UnknownInstruction = (OpCode, ElfCode.Input, ElfCode.Input, ElfCode.Output)
struct Sample {
let instruction: UnknownInstruction
let before: ElfCode.Registers
let after: ElfCode.Registers
}
func main() {
let (samples, program) = parse(lines: Array(StdIn()))
let opCodeMappings = figureOutOpCodes(from: samples)
let instructions = program.map { opCode, a, b, output in
ElfCode.Instruction(operation: opCodeMappings[opCode]!, inputA: a, inputB: b, output: output)
}
let registers = execute(instructions: instructions, registers: ElfCode.Registers(values: [0, 0, 0, 0]))
print("Registers:", registers.values)
}
func execute(instructions: [ElfCode.Instruction], registers: ElfCode.Registers) -> ElfCode.Registers {
var currentRegisters = registers
for instruction in instructions {
currentRegisters = instruction.apply(to: currentRegisters)
}
return currentRegisters
}
func figureOutOpCodes(from samples: [Sample]) -> [OpCode: ElfCode.Operation] {
let allOpCodes: Set<OpCode> = Set(samples.map { sample in sample.instruction.0 })
let allOperations: Set<ElfCode.Operation> = Set(ElfCode.Operation.allCases)
var validOperations: [OpCode: Set<ElfCode.Operation>] = Dictionary(
uniqueKeysWithValues: allOpCodes.map { opCode in (opCode, allOperations) }
)
for sample in samples {
let sampleValidOperations =
ElfCode.Operation.allCases
.filter { operation in
let instruction = ElfCode.Instruction(
operation: operation,
inputA: sample.instruction.1,
inputB: sample.instruction.2,
output: sample.instruction.3
)
let actual = instruction.apply(to: sample.before)
return actual == sample.after
}
validOperations[sample.instruction.0]!.formIntersection(sampleValidOperations)
}
while let (opCodeToSkip, operationToRemove) = findUniqueOperation(in: validOperations) {
for opCode in validOperations.keys {
if opCode != opCodeToSkip {
validOperations[opCode]!.remove(operationToRemove)
}
}
}
let opCodeMappings = validOperations.mapValues { operations -> ElfCode.Operation in
if operations.count != 1 {
fatalError("Multiple operations for an opcode: \(operations)")
}
return operations.first!
}
if opCodeMappings.keys.count != 16 {
fatalError("There aren't enough opcode mappings.")
}
return opCodeMappings
}
func findUniqueOperation(in validOperations: [OpCode: Set<ElfCode.Operation>]) -> (OpCode, ElfCode.Operation)? {
for (opCode, operations) in validOperations {
if operations.count == 1 {
let operation = operations.first!
let otherOperations = validOperations.filter { otherOpCode, otherOperations in
opCode != otherOpCode && otherOperations.contains(operation)
}
if otherOperations.isEmpty {
continue
}
return (opCode, operation)
}
}
return nil
}
func parse(lines: [String]) -> ([Sample], [UnknownInstruction]) {
let chunks =
lines
.split(separator: "")
.map { chunk in Array(chunk) }
let sampleSection = chunks.dropLast()
let programSection = chunks.last!
let samples: [Sample] = Array(sampleSection.map(parseSample))
let instructions: [UnknownInstruction] = Array(programSection.map(parseInstruction))
return (samples, instructions)
}
func parseSample(chunk: [String]) -> Sample {
return Sample(
instruction: parseInstruction(chunk[1]),
before: parseBeforeAfter(chunk[0]),
after: parseBeforeAfter(chunk[2])
)
}
func parseInstruction(_ string: String) -> UnknownInstruction {
let values = string.split(separator: " ").map { value in Int(value)! }
return (values[0], values[1], values[2], values[3])
}
func parseBeforeAfter(_ string: String) -> ElfCode.Registers {
guard let match = beforeAfterParser.firstMatch(in: string) else {
fatalError("Could not parse \"\(string)\".")
}
return ElfCode.Registers(
values: match[1]
.split(separator: ",")
.map { value in Int(value.trimmingCharacters(in: CharacterSet.whitespaces))! }
)
}
| mit | c80979fb00066b8cb15a2c1f234d2a1b | 35.320313 | 112 | 0.637987 | 4.320632 | false | false | false | false |
stupidfive/SwiftDataStructuresAndAlgorithms | SwiftDataStructuresAndAlgorithms/Stack.swift | 1 | 1025 | //
// Stack.swift
// SwiftDataStructuresAndAlgorithms
//
// Created by George Wu on 9/21/15.
// Copyright © 2015 George Wu. All rights reserved.
//
import Foundation
/// A Swift array backed stack.
public class Stack<ItemT>: CustomStringConvertible {
// array's tail as top
private var array = [ItemT]()
public var isEmpty: Bool {
return array.isEmpty
}
public func pop() -> ItemT? {
if array.isEmpty {
return nil
}
let item = array.last
array.removeLast()
return item
}
public func push(item: ItemT) {
array.append(item)
}
public func top() -> ItemT? {
if array.isEmpty {
return nil
}
return array.last
}
// init an empty stack
public init() {
}
// init stack with an array
public init(array: [ItemT]) {
self.array = array
}
public var description: String {
var desc = "["
for (idx, item) in array.enumerate() {
desc += "\(item)"
if idx != (array.count - 1) {
desc += ", "
}
}
desc += "]"
return desc
}
} | mit | 9c934ef9da6e52231dfafd7f180d3fe4 | 13.642857 | 52 | 0.601563 | 3.141104 | false | false | false | false |
crazypoo/PTools | PooToolsSource/Category/UIColor+PTEX.swift | 1 | 4883 | //
// UIColor+PTEX.swift
// Diou
//
// Created by ken lam on 2021/10/21.
// Copyright © 2021 DO. All rights reserved.
//
import UIKit
/// 颜色扩展
public extension UIColor {
var toHexString: String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return String(
format: "%02X%02X%02X",
Int(r * 0xff),
Int(g * 0xff),
Int(b * 0xff)
)
}
/// hex 色值
class func hex(_ hex: String, alpha: CGFloat? = 1.0) -> UIColor{
let tempStr = hex.trimmingCharacters(in: .whitespacesAndNewlines)
let hexint = intFromHexString(tempStr)
let color = UIColor(red: ((CGFloat) ((hexint & 0xFF0000) >> 16))/255, green: ((CGFloat) ((hexint & 0xFF00) >> 8))/255, blue: ((CGFloat) (hexint & 0xFF))/255, alpha: alpha!)
return color
}
/// UIColor -> Hex String
var hex: String? {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
let multiplier = CGFloat(255.999999)
guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else {
return nil
}
if alpha == 1.0 {
return String(
format: "#%02lX%02lX%02lX",
Int(red * multiplier),
Int(green * multiplier),
Int(blue * multiplier)
)
}
else {
return String(
format: "#%02lX%02lX%02lX%02lX",
Int(red * multiplier),
Int(green * multiplier),
Int(blue * multiplier),
Int(alpha * multiplier)
)
}
}
/// 从Hex装换int
private class func intFromHexString(_ hexString:String)->UInt32{
let scanner = Scanner(string: hexString)
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
var result : UInt32 = 0
scanner.scanHexInt32(&result)
return result
}
/// 返回随机颜色
@objc class var randomColor:UIColor{
get
{
return UIColor.randomColorWithAlpha(alpha: 1)
}
}
@objc class func randomColorWithAlpha(alpha:CGFloat)->UIColor
{
let red = CGFloat(arc4random()%256)/255.0
let green = CGFloat(arc4random()%256)/255.0
let blue = CGFloat(arc4random()%256)/255.0
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
@objc class var DevMaskColor:UIColor {
return UIColor(red: 0, green: 0, blue: 0, alpha: 0.15)
}
@objc func createImageWithColor()->UIImage
{
let rect = CGRect.init(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let ccontext = UIGraphicsGetCurrentContext()
ccontext?.setFillColor(self.cgColor)
ccontext!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
@objc func inverseColor()->UIColor {
let componentColors = self.cgColor.components
return UIColor(red: 1 - componentColors![0], green: 1 - componentColors![1], blue: 1 - componentColors![2], alpha:componentColors![3])
}
internal func rgbaValueModel()->PTColorRBGModel
{
var redF:CGFloat = 0
var greenF:CGFloat = 0
var blueF:CGFloat = 0
var alphaF:CGFloat = 0
guard self.getRed(&redF, green: &greenF, blue: &blueF, alpha: &alphaF) else {
return PTColorRBGModel()
}
let colorModel = PTColorRBGModel()
colorModel.redFloat = redF
colorModel.greenFloat = greenF
colorModel.blueFloat = blueF
colorModel.alphaFloat = alphaF
return colorModel
}
internal func mixColor(otherColor:UIColor)->UIColor
{
let rgbaModel = self.rgbaValueModel()
let otherRgbaModel = otherColor.rgbaValueModel()
let newAlpha = 1 - (1 - (rgbaModel.alphaFloat)) * (1 - otherRgbaModel.alphaFloat)
let newRed = (rgbaModel.redFloat) * (rgbaModel.alphaFloat) / newAlpha + (otherRgbaModel.redFloat) * (otherRgbaModel.alphaFloat) * (1 - (rgbaModel.alphaFloat)) / newAlpha
let newGreen = (rgbaModel.greenFloat) * (rgbaModel.alphaFloat) / newAlpha + (otherRgbaModel.greenFloat) * (otherRgbaModel.alphaFloat) * (1 - (rgbaModel.alphaFloat)) / newAlpha
let newBlue = (rgbaModel.blueFloat) * (rgbaModel.alphaFloat) / newAlpha + (otherRgbaModel.blueFloat) * (otherRgbaModel.alphaFloat) * (1 - (rgbaModel.alphaFloat)) / newAlpha
return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: newAlpha)
}
}
| mit | f85e53d7442160e4f76df585057d66bf | 32.232877 | 183 | 0.576876 | 3.973792 | false | false | false | false |
rae/YelpRBC | YelpRBC/MasterViewController.swift | 1 | 2907 | //
// MasterViewController.swift
// YelpRBC
//
// Created by Reid Ellis on 2016-10-08.
// Copyright © 2016 Tnir Technologies. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [Any]()
var yelp = Backend()
override func viewDidLoad() {
super.viewDidLoad()
yelp.search(for: "Ethiopian") {
self.tableView.reloadData()
}
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(_ animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! Date
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count = 0
if let yelpCount = yelp.results?.count {
count = yelpCount
}
return count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
objects.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .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.
}
}
}
| gpl-3.0 | cfad705af5a865843ed97f2e38368e5e | 30.586957 | 138 | 0.73744 | 4.477658 | false | false | false | false |
SoufianeLasri/Sisley | Sisley/SharingButton.swift | 1 | 1294 | //
// SharingButton.swift
// Sisley
//
// Created by Soufiane Lasri on 25/12/2015.
// Copyright © 2015 Soufiane Lasri. All rights reserved.
//
import UIKit
class SharingButton: UIButton {
init( frame: CGRect, imageName: String ) {
super.init( frame: frame )
self.backgroundColor = UIColor.whiteColor()
self.layer.cornerRadius = self.frame.width / 2
self.layer.borderWidth = 2.0
self.layer.borderColor = UIColor( red: 0.89, green: 0.81, blue: 0.47, alpha: 1.0 ).CGColor
self.alpha = 0
self.frame.origin.y += 5
let imageView = UIImageView( frame: CGRect( x: 0, y: 0, width: self.frame.width, height: self.frame.height ) )
imageView.image = UIImage( named: imageName )
imageView.layer.cornerRadius = self.frame.width / 2
imageView.layer.masksToBounds = true
self.addSubview( imageView )
}
func toggleButton( openingState: Bool ) {
if openingState == true {
self.alpha = 1
self.frame.origin.y -= 5
} else {
self.alpha = 0
self.frame.origin.y += 5
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | f0b24bf6ee296551b92b278851316c81 | 29.069767 | 118 | 0.584687 | 3.882883 | false | false | false | false |
Diego5529/tcc-swift3 | tcc-swift3/src/controllers/CompanyListViewController.swift | 1 | 3879 | //
// CompanyListViewController.swift
// tcc-swift3
//
// Created by Diego Oliveira on 28/05/17.
// Copyright © 2017 DO. All rights reserved.
//
import UIKit
import CoreData
import Former
class CompanyListViewController: FormViewController, NSFetchedResultsControllerDelegate {
var managedObjectContext: NSManagedObjectContext? = nil
var delegate: AppDelegate!
var context: NSManagedObjectContext!
var companies: NSMutableDictionary = [:]
override func viewDidLoad() {
super.viewDidLoad()
delegate = UIApplication.shared.delegate as! AppDelegate
context = self.delegate.managedObjectContext
let select = NSFetchRequest<NSFetchRequestResult>(entityName: "Company")
do {
let results = try self.context.fetch(select)
if results.count > 0 {
print(results)
for company in results {
if let key = (company as AnyObject).value(forKey: "title") {
let companyClass = CompanyBean().serializer(companyObject: company as AnyObject)
companies .setValue(companyClass, forKey: key as! String)
print(key)
}
}
}
}catch{
}
configure()
}
override func viewDidAppear(_ animated: Bool) {
}
override func viewWillAppear(_ animated: Bool) {
//self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
former.deselect(animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func configure() {
// Create RowFormers
let createMenu: ((String, (() -> Void)?) -> RowFormer) = { text, onSelected in
return LabelRowFormer<FormLabelCell>() {
$0.titleLabel.textColor = .formerColor()
$0.titleLabel.font = .boldSystemFont(ofSize: 16)
$0.accessoryType = .disclosureIndicator
}.configure {
$0.text = text
}.onSelected { _ in
onSelected?()
}
}
//Companies
let newCompanyRow = createMenu("New Company") { [weak self] in
self?.navigationController?.pushViewController(CompanyFormViewController(), animated: true)
}
// Create Headers and Footers
let createHeader: ((String) -> ViewFormer) = { text in
return LabelViewFormer<FormLabelHeaderView>()
.configure {
$0.text = text
$0.viewHeight = 40
}
}
// Create SectionFormers
let optionsSection = SectionFormer(rowFormer: newCompanyRow)
.set(headerViewFormer: createHeader("Options"))
let arrayCompaniesRow = NSMutableArray()
for company in companies {
let companyRow = createMenu(company.key as! String) { [weak self] in
let companyVC = CompanyFormViewController()
companyVC.companyClass = company.value as! CompanyBean
self?.navigationController?.pushViewController(companyVC, animated: true)
}
arrayCompaniesRow.add(companyRow)
}
let companiesSection = SectionFormer(rowFormers: arrayCompaniesRow as! [RowFormer])
.set(headerViewFormer: createHeader("My Companies"))
former.append(sectionFormer: optionsSection, companiesSection)
}
}
| mit | c1597d24f401e327f2ceb7b5922bf7fb | 32.145299 | 104 | 0.562145 | 5.831579 | false | false | false | false |
movabletype/smartphone-app | MT_iOS/MT_iOS/Classes/Model/EntryDateItem.swift | 1 | 1486 | //
// EntryDateItem.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/06/02.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
class EntryDateItem: BaseEntryItem {
var date: NSDate?
override init() {
super.init()
type = "date"
}
override func encodeWithCoder(aCoder: NSCoder) {
super.encodeWithCoder(aCoder)
aCoder.encodeObject(self.date, forKey: "date")
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.date = aDecoder.decodeObjectForKey("date") as? NSDate
}
override func value()-> String {
if let date = self.date {
let api = DataAPI.sharedInstance
if api.apiVersion.isEmpty {
return Utils.dateTimeTextFromDate(date)
} else {
let dateTime = Utils.ISO8601StringFromDate(date)
let comps = dateTime.componentsSeparatedByString("T")
return comps[0]
}
}
return ""
}
override func dispValue()-> String {
if let date = self.date {
return Utils.dateStringFromDate(date)
}
return ""
}
override func makeParams()-> [String : AnyObject] {
if let _ = self.date {
return [self.id:self.value()]
}
return [self.id:""]
}
override func clear() {
date = nil
}
}
| mit | c55b4049ab53eae05f007a12fc7a69a6 | 22.555556 | 69 | 0.53841 | 4.46988 | false | false | false | false |
ncalexan/firefox-ios | XCUITests/NavigationTest.swift | 1 | 11659 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import XCTest
let website_1 = ["url": "www.mozilla.org", "label": "Internet for people, not profit — Mozilla", "value": "mozilla.org"]
let website_2 = ["url": "www.yahoo.com", "label": "Yahoo", "value": "yahoo"]
let urlAddOns = "addons.mozilla.org"
class NavigationTest: BaseTestCase {
var navigator: Navigator!
var app: XCUIApplication!
override func setUp() {
super.setUp()
app = XCUIApplication()
navigator = createScreenGraph(app).navigator(self)
}
override func tearDown() {
super.tearDown()
}
func testNavigation() {
navigator.goto(URLBarOpen)
let urlPlaceholder = "Search or enter address"
XCTAssert(app.textFields["url"].exists)
let defaultValuePlaceholder = app.textFields["url"].placeholderValue!
// Check the url placeholder text and that the back and forward buttons are disabled
XCTAssert(urlPlaceholder == defaultValuePlaceholder)
if iPad() {
app.buttons["Cancel"].tap()
XCTAssertFalse(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
app.textFields["url"].tap()
} else {
XCTAssertFalse(app.buttons["TabToolbar.backButton"].isEnabled)
XCTAssertFalse(app.buttons["TabToolbar.forwardButton"].isEnabled)
}
// Once an url has been open, the back button is enabled but not the forward button
navigator.openURL(urlString: website_1["url"]!)
waitForValueContains(app.textFields["url"], value: website_1["value"]!)
if iPad() {
XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
} else {
XCTAssertTrue(app.buttons["TabToolbar.backButton"].isEnabled)
XCTAssertFalse(app.buttons["TabToolbar.forwardButton"].isEnabled)
}
// Once a second url is open, back button is enabled but not the forward one till we go back to url_1
navigator.openURL(urlString: website_2["url"]!)
waitForValueContains(app.textFields["url"], value: website_2["value"]!)
if iPad() {
XCTAssertTrue(app.buttons["URLBarView.backButton"].isEnabled)
XCTAssertFalse(app.buttons["Forward"].isEnabled)
// Go back to previous visited web site
app.buttons["URLBarView.backButton"].tap()
} else {
XCTAssertTrue(app.buttons["TabToolbar.backButton"].isEnabled)
XCTAssertFalse(app.buttons["TabToolbar.forwardButton"].isEnabled)
// Go back to previous visited web site
app.buttons["TabToolbar.backButton"].tap()
}
waitForValueContains(app.textFields["url"], value: website_1["value"]!)
if iPad() {
app.buttons["Forward"].tap()
} else {
// Go forward to next visited web site
app.buttons["TabToolbar.forwardButton"].tap()
}
waitForValueContains(app.textFields["url"], value: website_2["value"]!)
}
func testTapSignInShowsFxAFromTour() {
navigator.goto(SettingsScreen)
// Open FxAccount from tour option in settings menu and go throughout all the screens there
// Tour's first screen Organize
navigator.goto(Intro_Welcome)
// Tour's last screen Sync
navigator.goto(Intro_Sync)
// Finally Sign in to Firefox screen should be shown correctly
app.buttons["Sign in to Firefox"].tap()
checkFirefoxSyncScreenShown()
// Go back to NewTabScreen
app.navigationBars["Client.FxAContentView"].buttons["Done"].tap()
navigator.nowAt(NewTabScreen)
}
func testTapSigninShowsFxAFromSettings() {
navigator.goto(SettingsScreen)
// Open FxAccount from settings menu and check the Sign in to Firefox scren
let signInToFirefoxStaticText = app.tables["AppSettingsTableViewController.tableView"].staticTexts["Sign in to Sync"]
signInToFirefoxStaticText.tap()
checkFirefoxSyncScreenShown()
// After that it is possible to go back to Settings
let settingsButton = app.navigationBars["Client.FxAContentView"].buttons["Settings"]
settingsButton.tap()
}
func testTapSignInShowsFxAFromRemoteTabPanel() {
navigator.goto(NewTabScreen)
// Open FxAccount from remote tab panel and check the Sign in to Firefox scren
navigator.goto(HomePanel_History)
XCTAssertTrue(app.tables["History List"].staticTexts["Synced Devices"].isEnabled)
app.tables["History List"].staticTexts["Synced Devices"].tap()
app.tables.buttons["Sign in"].tap()
checkFirefoxSyncScreenShown()
app.navigationBars["Client.FxAContentView"].buttons["Done"].tap()
navigator.nowAt(HomePanel_History)
}
private func checkFirefoxSyncScreenShown() {
waitforExistence(app.webViews.staticTexts["Sign in"])
XCTAssertTrue(app.webViews.textFields["Email"].exists)
XCTAssertTrue(app.webViews.secureTextFields["Password"].exists)
XCTAssertTrue(app.webViews.buttons["Sign in"].exists)
}
func testScrollsToTopWithMultipleTabs() {
navigator.goto(TabTray)
navigator.openURL(urlString: website_1["url"]!)
waitForValueContains(app.textFields["url"], value: website_1["value"]!)
// Element at the TOP. TBChanged once the web page is correclty shown
let topElement = app.webViews.staticTexts["Internet for people, "]
// Element at the BOTTOM
let bottomElement = app.webViews.links.staticTexts["Contact Us"]
// Scroll to bottom
bottomElement.tap()
if iPad() {
app.buttons["URLBarView.backButton"].tap()
} else {
app.buttons["TabToolbar.backButton"].tap()
}
// Scroll to top
topElement.tap()
}
private func checkMobileView() {
let mobileViewElement = app.webViews.links.staticTexts["View classic desktop site"]
waitforExistence(mobileViewElement)
XCTAssertTrue (mobileViewElement.exists, "Mobile view is not available")
}
private func checkDesktopView() {
let desktopViewElement = app.webViews.links.staticTexts["View Mobile Site"]
waitforExistence(desktopViewElement)
XCTAssertTrue (desktopViewElement.exists, "Desktop view is not available")
}
private func clearData() {
navigator.goto(ClearPrivateDataSettings)
app.tables.staticTexts["Clear Private Data"].tap()
app.alerts.buttons["OK"].tap()
navigator.goto(NewTabScreen)
}
func testToggleBetweenMobileAndDesktopSiteFromSite() {
clearData()
let goToDesktopFromMobile = app.webViews.links.staticTexts["View classic desktop site"]
// Open URL by default in mobile view
navigator.openURL(urlString: urlAddOns)
waitForValueContains(app.textFields["url"], value: urlAddOns)
waitforExistence(goToDesktopFromMobile)
// From the website go to Desktop view
goToDesktopFromMobile.tap()
checkDesktopView()
// From the website go back to Mobile view
app.webViews.links.staticTexts["View Mobile Site"].tap()
checkMobileView()
}
func testToggleBetweenMobileAndDesktopSiteFromMenu() {
clearData()
navigator.openURL(urlString: urlAddOns)
waitForValueContains(app.textFields["url"], value: urlAddOns)
// Mobile view by default, desktop view should be available
navigator.browserPerformAction(.requestDesktop)
checkDesktopSite()
// From desktop view it is posible to change to mobile view again
navigator.nowAt(BrowserTab)
navigator.browserPerformAction(.requestMobile)
checkMobileSite()
}
private func checkMobileSite() {
app.buttons["TabToolbar.menuButton"].tap()
waitforExistence(app.collectionViews.cells["RequestDesktopMenuItem"])
navigator.goto(BrowserTab)
}
private func checkDesktopSite() {
app.buttons["TabToolbar.menuButton"].tap()
waitforExistence(app.collectionViews.cells["RequestMobileMenuItem"])
navigator.goto(BrowserTab)
}
func testNavigationPreservesDesktopSiteOnSameHost() {
clearData()
navigator.openURL(urlString: urlAddOns)
// Mobile view by default, desktop view should be available
//navigator.browserPerformAction(.requestDesktop)
navigator.goto(BrowserTabMenu)
waitforExistence(app.collectionViews.cells["RequestDesktopMenuItem"])
app.collectionViews.cells["RequestDesktopMenuItem"].tap()
checkDesktopView()
// Select any link to navigate to another site and check if the view is kept in desktop view
waitforExistence(app.webViews.links["Featured ›"])
app.webViews.links["Featured ›"].tap()
checkDesktopView()
}
func testReloadPreservesMobileOrDesktopSite() {
clearData()
navigator.openURL(urlString: urlAddOns)
// Mobile view by default, desktop view should be available
navigator.browserPerformAction(.requestDesktop)
// After reloading a website the desktop view should be kept
app.buttons["Reload"].tap()
waitForValueContains(app.textFields["url"], value: urlAddOns)
checkDesktopView()
// From desktop view it is posible to change to mobile view again
navigator.nowAt(BrowserTab)
navigator.browserPerformAction(.requestMobile)
waitForValueContains(app.textFields["url"], value: urlAddOns)
// After reloading a website the mobile view should be kept
app.buttons["Reload"].tap()
checkMobileView()
}
/* Test disabled till bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1346157 is fixed
func testBackForwardNavigationRestoresMobileOrDesktopSite() {
clearData()
let desktopViewElement = app.webViews.links.staticTexts["Mobile"]
let collectionViewsQuery = app.collectionViews
// Open first url and keep it in mobile view
navigator.openURL(urlString: urlAddOns)
waitForValueContains(app.textFields["url"], value: urlAddOns)
checkMobileView()
// Open a second url and change it to desktop view
navigator.openURL(urlString: "www.linkedin.com")
navigator.goto(BrowserTabMenu)
waitforExistence(collectionViewsQuery.cells["RequestDesktopMenuItem"])
collectionViewsQuery.cells["RequestDesktopMenuItem"].tap()
waitforExistence(desktopViewElement)
XCTAssertTrue (desktopViewElement.exists, "Desktop view is not available")
// Go back to first url and check that the view is still mobile view
app.buttons["TabToolbar.backButton"].tap()
waitForValueContains(app.textFields["url"], value: urlAddOns)
checkMobileView()
// Go forward to second url and check that the view is still desktop view
app.buttons["TabToolbar.forwardButton"].tap()
waitForValueContains(app.textFields["url"], value: "www.linkedin.com")
waitforExistence(desktopViewElement)
XCTAssertTrue (desktopViewElement.exists, "Desktop view is not available after coming from another site in mobile view")
}*/
}
| mpl-2.0 | 4954bdd7eb4b2b3acf716156280a73ae | 39.887719 | 128 | 0.667897 | 5.025011 | false | false | false | false |
iampikuda/iOS-Scribbles | Codility/FrogRiverOne.playground/Contents.swift | 1 | 353 |
public func solution(_ X : Int, _ A : inout [Int]) -> Int {
var checker = [Int : Bool]()
for number in A {
if number <= X {
checker[number] = true
}
if checker.count == X {
return A.index(of: number)!
}
}
return -1
}
var input = [1, 3, 1, 4, 2, 3, 5, 4]
solution(3, &input)
| mit | bbc2725685c4fae98245abb5a2c37709 | 15.809524 | 59 | 0.456091 | 3.209091 | false | false | false | false |
ustwo/formvalidator-swift | Tests/Unit Tests/Conditions/AlphanumericConditionTests.swift | 1 | 6122 | //
// AlphanumericConditionTests.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 13/01/2016.
// Copyright © 2016 ustwo. All rights reserved.
//
import XCTest
@testable import FormValidatorSwift
final class AlphanumericConditionTests: XCTestCase {
// MARK: - Constants
internal struct Constants {
static let ascii = "abcDefgh1234567890"
static let unicode = "abÅÄcdefÖgh1234567890"
static let asciiSpaces = "abc Def gh1234 567890"
static let unicodeSpaces = "abÅ Äcdef Ögh1234 567890"
static let symbols = "a?!1"
}
// MARK: - Test Success
func testAlphanumericCondition_DefaultInit() {
// Given
let condition = AlphanumericCondition()
let expectedAllowsUnicode = true
let expectedAllowsWhitespace = false
// When
let actualAllowsUnicode = condition.configuration.allowsUnicode
let actualAllowsWhitespace = condition.configuration.allowsWhitespace
// Test
XCTAssertEqual(actualAllowsUnicode,
expectedAllowsUnicode,
"Expected allowsUnicode to be: \(expectedAllowsUnicode) but found: \(actualAllowsUnicode)")
XCTAssertEqual(actualAllowsWhitespace,
expectedAllowsWhitespace,
"Expected allowsWhitespace to be: \(expectedAllowsWhitespace) but found: \(actualAllowsWhitespace)")
}
func testAlphanumericCondition_NoUnicode_NoWhitespace_Success() {
// Given
let testInput = Constants.ascii
let condition = AlphanumericCondition(configuration: ConfigurationSeeds.AlphanumericSeeds.noUnicode_NoWhitespace)
let expectedResult = true
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
func testAlphanumericCondition_NoUnicode_Whitespace_Success() {
// Given
let testInput = Constants.asciiSpaces
let condition = AlphanumericCondition(configuration: ConfigurationSeeds.AlphanumericSeeds.noUnicode_Whitespace)
let expectedResult = true
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
func testAlphanumericCondition_Unicode_NoWhitespace_Success() {
// Given
let testInput = Constants.unicode
let condition = AlphanumericCondition(configuration: ConfigurationSeeds.AlphanumericSeeds.unicode_NoWhitespace)
let expectedResult = true
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
func testAlphanumericCondition_Unicode_Whitespace_Success() {
// Given
let testInput = Constants.unicodeSpaces
let condition = AlphanumericCondition(configuration: ConfigurationSeeds.AlphanumericSeeds.unicode_Whitespace)
let expectedResult = true
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
// MARK: - Test Failure
func testAlphanumericCondition_NoUnicode_NoWhitespace_Failure_Spaces() {
// Given
let testInput = Constants.asciiSpaces
let condition = AlphanumericCondition(configuration: ConfigurationSeeds.AlphanumericSeeds.noUnicode_NoWhitespace)
let expectedResult = false
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
func testAlphanumericCondition_NoUnicode_NoWhitespace_Failure_Unicode() {
// Given
let testInput = Constants.unicode
let condition = AlphanumericCondition(configuration: ConfigurationSeeds.AlphanumericSeeds.noUnicode_NoWhitespace)
let expectedResult = false
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
func testAlphanumericCondition_NoUnicode_Whitespace_Failure_Symbols() {
// Given
let testInput = Constants.symbols
let condition = AlphanumericCondition(configuration: ConfigurationSeeds.AlphanumericSeeds.noUnicode_Whitespace)
let expectedResult = false
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
func testAlphanumericCondition_NoUnicode_Whitespace_Failure_Unicode() {
// Given
let testInput = Constants.unicodeSpaces
let condition = AlphanumericCondition(configuration: ConfigurationSeeds.AlphanumericSeeds.noUnicode_Whitespace)
let expectedResult = false
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
func testAlphanumericCondition_Unicode_NoWhitespace_Failure() {
// Given
let testInput = Constants.unicodeSpaces
let condition = AlphanumericCondition(configuration: ConfigurationSeeds.AlphanumericSeeds.unicode_NoWhitespace)
let expectedResult = false
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
func testAlphanumericCondition_Unicode_Whitespace_Failure() {
// Given
let testInput = Constants.symbols
let condition = AlphanumericCondition(configuration: ConfigurationSeeds.AlphanumericSeeds.unicode_Whitespace)
let expectedResult = false
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
func testAlphanumericCondition_Nil() {
// Given
let testInput: String? = nil
let condition = AlphanumericCondition()
let expectedResult = false
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
}
| mit | 1afb9286386a5dcf80e967317e902222 | 36.286585 | 127 | 0.662796 | 5.615243 | false | true | false | false |
fgengine/quickly | Quickly/ViewControllers/Page/Animation/QPageViewControllerAnimation.swift | 1 | 5251 | //
// Quickly
//
public final class QPageViewControllerForwardAnimation : IQPageViewControllerAnimation {
public var overlapping: CGFloat
public var acceleration: CGFloat
public init(overlapping: CGFloat = 1, acceleration: CGFloat = 1200) {
self.overlapping = overlapping
self.acceleration = acceleration
}
public func animate(
contentView: UIView,
currentViewController: IQPageViewController,
targetViewController: IQPageViewController,
animated: Bool,
complete: @escaping () -> Void
) {
let frame = contentView.bounds
let currentBeginFrame = frame
let currentEndFrame = CGRect(
x: frame.origin.x - frame.width,
y: frame.origin.y,
width: frame.width,
height: frame.height
)
let targetBeginFrame = CGRect(
x: frame.origin.x + (frame.width * self.overlapping),
y: frame.origin.y,
width: frame.width,
height: frame.height
)
let targetEndFrame = frame
currentViewController.view.frame = currentBeginFrame
currentViewController.layoutIfNeeded()
targetViewController.view.frame = targetBeginFrame
targetViewController.layoutIfNeeded()
contentView.insertSubview(targetViewController.view, belowSubview: currentViewController.view)
if animated == true {
currentViewController.willDismiss(animated: animated)
targetViewController.willPresent(animated: animated)
let duration = TimeInterval(abs(targetBeginFrame.midX - targetEndFrame.midX) / acceleration)
UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: {
currentViewController.view.frame = currentEndFrame
targetViewController.view.frame = targetEndFrame
}, completion: { (completed) in
currentViewController.didDismiss(animated: animated)
targetViewController.didPresent(animated: animated)
complete()
})
} else {
currentViewController.view.frame = currentEndFrame
currentViewController.willDismiss(animated: animated)
currentViewController.didDismiss(animated: animated)
targetViewController.view.frame = targetEndFrame
targetViewController.willPresent(animated: animated)
targetViewController.didPresent(animated: animated)
complete()
}
}
}
public final class QPageViewControllerBackwardAnimation : IQPageViewControllerAnimation {
public var overlapping: CGFloat
public var acceleration: CGFloat
public init(overlapping: CGFloat = 1, acceleration: CGFloat = 1200) {
self.overlapping = overlapping
self.acceleration = acceleration
}
public func animate(
contentView: UIView,
currentViewController: IQPageViewController,
targetViewController: IQPageViewController,
animated: Bool,
complete: @escaping () -> Void
) {
let frame = contentView.bounds
let currentBeginFrame = frame
let currentEndFrame = CGRect(
x: frame.origin.x + frame.width,
y: frame.origin.y,
width: frame.width,
height: frame.height
)
let targetBeginFrame = CGRect(
x: frame.origin.x - (frame.width * self.overlapping),
y: frame.origin.y,
width: frame.width,
height: frame.height
)
let targetEndFrame = frame
currentViewController.view.frame = currentBeginFrame
currentViewController.layoutIfNeeded()
targetViewController.view.frame = targetBeginFrame
targetViewController.layoutIfNeeded()
contentView.insertSubview(targetViewController.view, belowSubview: currentViewController.view)
if animated == true {
currentViewController.willDismiss(animated: animated)
targetViewController.willPresent(animated: animated)
let duration = TimeInterval(abs(targetBeginFrame.midX - targetEndFrame.midX) / acceleration)
UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: {
currentViewController.view.frame = currentEndFrame
targetViewController.view.frame = targetEndFrame
}, completion: { (completed) in
currentViewController.didDismiss(animated: animated)
targetViewController.didPresent(animated: animated)
complete()
})
} else {
currentViewController.view.frame = currentEndFrame
currentViewController.willDismiss(animated: animated)
currentViewController.didDismiss(animated: animated)
targetViewController.view.frame = targetEndFrame
targetViewController.willPresent(animated: animated)
targetViewController.didPresent(animated: animated)
complete()
}
}
}
| mit | 4e4efa5ce060ae0abdca688210bf351b | 38.481203 | 128 | 0.641402 | 5.940045 | false | false | false | false |
sunlijian/sinaBlog_repository | sinaBlog_sunlijian/sinaBlog_sunlijian/Classes/Module/Compose/Tool/IWEmotionTools.swift | 1 | 7230 | //
// IWEmotionTools.swift
// sinaBlog_sunlijian
//
// Created by sunlijian on 15/10/23.
// Copyright © 2015年 myCompany. All rights reserved.
//
import UIKit
class IWEmotionTools: NSObject {
//默认表情集合
static let defaultEmotions: [IWEmotion] = {
return IWEmotionTools.loadEmotions("EmotionIcons/default/info.plist")
}()
//emoji表情集合
static let emojiEmotions: [IWEmotion] = {
return IWEmotionTools.loadEmotions("EmotionIcons/emoji/info.plist")
}()
//浪小花表情集合
static let LxhEmotions: [IWEmotion] = {
return IWEmotionTools.loadEmotions("EmotionIcons/lxh/info.plist")
}()
//最近表情集合
static var recentEmotions:[IWEmotion] = {
//解档
let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("recentEmotion.archive")
var result = NSKeyedUnarchiver.unarchiveObjectWithFile(path)
print(result)
if result == nil {
return [IWEmotion]()
}else{
return result as! [IWEmotion]
}
}()
//加载表情
private class func loadEmotions(path: String) -> [IWEmotion]{
//路径
let bundlePath = NSBundle.mainBundle().pathForResource(path, ofType: nil)
//数组
let array = NSArray(contentsOfFile: bundlePath!)
//临时数组
var tempArray = [IWEmotion]()
//遍历数组
for value in array!{
let emotion = IWEmotion(dictionary: (value as! [String: AnyObject]))
emotion.prePath = (path as NSString).stringByDeletingLastPathComponent
//添加到数组中
tempArray.append(emotion)
}
return tempArray
}
//一共多少页
class func emotionsTotalPageCount() -> Int{
// let defaultEmotionPage = (defaultEmotions.count - 1) / 20 + 1
// let emojiEmotionPage = (emojiEmotions.count - 1) / 20 + 1
// let lxhEmotionPage = (LxhEmotions.count - 1) / 20 + 1
// let recentEmotionPage = 1
let defaultEmotionPage = defaultEmotionRange.length
let emojiEmotionPage = emojiEmotionRange.length
let lxhEmotionPage = LxhEmotionRange.length
let recentEmotionPage = recentEmotionRange.length
return defaultEmotionPage + emojiEmotionPage + lxhEmotionPage + recentEmotionPage
}
//默认表情集合范围
static let recentEmotionRange: NSRange = {
return NSMakeRange(0, 1)
}()
static let defaultEmotionRange: NSRange = {
return NSMakeRange(1, 5)
}()
//Emoji 表情集合范围
static let emojiEmotionRange: NSRange = {
return NSMakeRange(6, 4)
}()
//路小花 表情集合范围
static let LxhEmotionRange: NSRange = {
return NSMakeRange(10, 2)
}()
//根据当前页 计算是属于哪个类弄的表情集合
class func emotionTypeWithPageNum(pageNum: Int) -> IWEmotionToolBarButtonType {
if pageNum == 0{
return .Recent
}else if (NSLocationInRange(pageNum, defaultEmotionRange)){
return .Default
}else if (NSLocationInRange(pageNum, emojiEmotionRange)){
return .Emoji
}else{
return .Lxh
}
}
//根据类型 计算出 pageControl 的页数
class func pageControlTotalNumOfPageWithType(type: IWEmotionToolBarButtonType) -> Int{
switch type{
case .Recent: return 1
case .Default: return defaultEmotionRange.length
case .Emoji: return emojiEmotionRange.length
case .Lxh: return LxhEmotionRange.length
}
}
//根据类型和当前的页 算出 currentPage
class func pageControlNumOfCurrenPage(page: Int, type: IWEmotionToolBarButtonType) -> Int{
switch type{
case .Recent: return 0
case .Default: return page - recentEmotionRange.length
case .Emoji: return page - recentEmotionRange.length - defaultEmotionRange.length
case .Lxh: return page - recentEmotionRange.length - defaultEmotionRange.length - emojiEmotionRange.length
}
}
//点击 toolBar 里的 Button的时候 根据类型 获取当前类型的集合的范围 返回 range 的 loaction
class func pageControlFirstNumWithType(type: IWEmotionToolBarButtonType) -> Int{
switch type{
case .Recent: return recentEmotionRange.location
case .Default: return defaultEmotionRange.location
case .Emoji: return emojiEmotionRange.location
case .Lxh: return LxhEmotionRange.location
}
}
//根据indexPath 获取当前页的数据
class func emotionWithIndexPath(indexpath: NSIndexPath) -> [IWEmotion]{
//当前是第几页
let page = indexpath.row
//当前所属的表情类型
let type = IWEmotionTools.emotionTypeWithPageNum(page)
//当前页
let currentPage = IWEmotionTools.pageControlNumOfCurrenPage(page, type: type)
//获取类型的集合
func emotionsArrayWithType(type: IWEmotionToolBarButtonType) -> [IWEmotion]{
switch type{
case .Recent: return recentEmotions
case .Default: return defaultEmotions
case .Emoji: return emojiEmotions
case .Lxh: return LxhEmotions
}
}
let emotionArray = emotionsArrayWithType(type)
print(emotionArray.count)
//从类型集合中截取当前页的数据
let location = currentPage * PAGE_EMOTION_MAX
var length = PAGE_EMOTION_MAX
if (location + length) > emotionArray.count {
length = emotionArray.count - location
}
let emotions = (emotionArray as NSArray).subarrayWithRange(NSMakeRange(location, length))
return emotions as! [IWEmotion]
}
//保存最近使用表情
class func saveEmotion(emotion: IWEmotion){
//保存路径
let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("recentEmotion.archive")
//在保存到集合中进行判断
let result = recentEmotions.contains(emotion)
if result {
let index = (recentEmotions as NSArray).indexOfObject(emotion)
recentEmotions.removeAtIndex(index)
}
//保存到集合中
recentEmotions.insert(emotion, atIndex: 0)
//归档
NSKeyedArchiver.archiveRootObject(recentEmotions, toFile: path)
}
//通过表情描述 找到对应的表情模型
class func emtionWithChs(chs: String) -> IWEmotion?{
//遍历默认表情
for emotion in defaultEmotions{
if (emotion.chs! as NSString).isEqual(chs){
return emotion
}
}
//遍历浪小花
for emotion in LxhEmotions{
if (emotion.chs! as NSString).isEqual(chs){
return emotion
}
}
return nil
}
}
| apache-2.0 | 46536fa3d7fbcf204419ebf751b50826 | 32.167488 | 173 | 0.623942 | 4.512735 | false | false | false | false |
russbishop/swift | validation-test/stdlib/String.swift | 1 | 44516 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// XFAIL: interpret
import StdlibUnittest
import StdlibCollectionUnittest
#if _runtime(_ObjC)
import Foundation // For NSRange
#endif
extension Collection {
internal func index(_nth n: Int) -> Index {
precondition(n >= 0)
return index(startIndex, offsetBy: numericCast(n))
}
internal func index(_nthLast n: Int) -> Index {
precondition(n >= 0)
return index(endIndex, offsetBy: -numericCast(n))
}
}
extension String {
internal func index(_nth n: Int) -> Index {
return characters.index(_nth: n)
}
internal func index(_nthLast n: Int) -> Index {
return characters.index(_nthLast: n)
}
}
extension String {
var bufferID: UInt {
return unsafeBitCast(_core._owner, to: UInt.self)
}
var nativeCapacity: Int {
return _core.nativeBuffer!.capacity
}
var capacity: Int {
return _core.nativeBuffer?.capacity ?? 0
}
}
var StringTests = TestSuite("StringTests")
StringTests.test("sizeof") {
expectEqual(3 * sizeof(Int.self), sizeof(String.self))
}
StringTests.test("AssociatedTypes-UTF8View") {
typealias View = String.UTF8View
expectCollectionAssociatedTypes(
collectionType: View.self,
iteratorType: IndexingIterator<View>.self,
subSequenceType: View.self,
indexType: View.Index.self,
indexDistanceType: Int.self,
indicesType: DefaultIndices<View>.self)
}
StringTests.test("AssociatedTypes-UTF16View") {
typealias View = String.UTF16View
expectCollectionAssociatedTypes(
collectionType: View.self,
iteratorType: IndexingIterator<View>.self,
subSequenceType: View.self,
indexType: View.Index.self,
indexDistanceType: Int.self,
indicesType: View.Indices.self)
}
StringTests.test("AssociatedTypes-UnicodeScalarView") {
typealias View = String.UnicodeScalarView
expectCollectionAssociatedTypes(
collectionType: View.self,
iteratorType: View.Iterator.self,
subSequenceType: View.self,
indexType: View.Index.self,
indexDistanceType: Int.self,
indicesType: DefaultBidirectionalIndices<View>.self)
}
StringTests.test("AssociatedTypes-CharacterView") {
typealias View = String.CharacterView
expectCollectionAssociatedTypes(
collectionType: View.self,
iteratorType: IndexingIterator<View>.self,
subSequenceType: View.self,
indexType: View.Index.self,
indexDistanceType: Int.self,
indicesType: DefaultBidirectionalIndices<View>.self)
}
func checkUnicodeScalarViewIteration(
_ expectedScalars: [UInt32], _ str: String
) {
do {
let us = str.unicodeScalars
var i = us.startIndex
let end = us.endIndex
var decoded: [UInt32] = []
while i != end {
expectTrue(i < us.index(after: i)) // Check for Comparable conformance
decoded.append(us[i].value)
i = us.index(after: i)
}
expectEqual(expectedScalars, decoded)
}
do {
let us = str.unicodeScalars
let start = us.startIndex
var i = us.endIndex
var decoded: [UInt32] = []
while i != start {
i = us.index(before: i)
decoded.append(us[i].value)
}
expectEqual(expectedScalars, decoded)
}
}
StringTests.test("unicodeScalars") {
checkUnicodeScalarViewIteration([], "")
checkUnicodeScalarViewIteration([ 0x0000 ], "\u{0000}")
checkUnicodeScalarViewIteration([ 0x0041 ], "A")
checkUnicodeScalarViewIteration([ 0x007f ], "\u{007f}")
checkUnicodeScalarViewIteration([ 0x0080 ], "\u{0080}")
checkUnicodeScalarViewIteration([ 0x07ff ], "\u{07ff}")
checkUnicodeScalarViewIteration([ 0x0800 ], "\u{0800}")
checkUnicodeScalarViewIteration([ 0xd7ff ], "\u{d7ff}")
checkUnicodeScalarViewIteration([ 0x8000 ], "\u{8000}")
checkUnicodeScalarViewIteration([ 0xe000 ], "\u{e000}")
checkUnicodeScalarViewIteration([ 0xfffd ], "\u{fffd}")
checkUnicodeScalarViewIteration([ 0xffff ], "\u{ffff}")
checkUnicodeScalarViewIteration([ 0x10000 ], "\u{00010000}")
checkUnicodeScalarViewIteration([ 0x10ffff ], "\u{0010ffff}")
}
StringTests.test("indexComparability") {
let empty = ""
expectTrue(empty.startIndex == empty.endIndex)
expectFalse(empty.startIndex != empty.endIndex)
expectTrue(empty.startIndex <= empty.endIndex)
expectTrue(empty.startIndex >= empty.endIndex)
expectFalse(empty.startIndex > empty.endIndex)
expectFalse(empty.startIndex < empty.endIndex)
let nonEmpty = "borkus biqualificated"
expectFalse(nonEmpty.startIndex == nonEmpty.endIndex)
expectTrue(nonEmpty.startIndex != nonEmpty.endIndex)
expectTrue(nonEmpty.startIndex <= nonEmpty.endIndex)
expectFalse(nonEmpty.startIndex >= nonEmpty.endIndex)
expectFalse(nonEmpty.startIndex > nonEmpty.endIndex)
expectTrue(nonEmpty.startIndex < nonEmpty.endIndex)
}
StringTests.test("ForeignIndexes/Valid") {
// It is actually unclear what the correct behavior is. This test is just a
// change detector.
//
// <rdar://problem/18037897> Design, document, implement invalidation model
// for foreign String indexes
do {
let donor = "abcdef"
let acceptor = "uvwxyz"
expectEqual("u", acceptor[donor.startIndex])
expectEqual("wxy",
acceptor[donor.index(_nth: 2)..<donor.index(_nth: 5)])
}
do {
let donor = "abcdef"
let acceptor = "\u{1f601}\u{1f602}\u{1f603}"
expectEqual("\u{fffd}", acceptor[donor.startIndex])
expectEqual("\u{fffd}", acceptor[donor.index(after: donor.startIndex)])
expectEqualUnicodeScalars([ 0xfffd, 0x1f602, 0xfffd ],
acceptor[donor.index(_nth: 1)..<donor.index(_nth: 5)])
expectEqualUnicodeScalars([ 0x1f602, 0xfffd ],
acceptor[donor.index(_nth: 2)..<donor.index(_nth: 5)])
}
}
StringTests.test("ForeignIndexes/UnexpectedCrash")
.xfail(
.always("<rdar://problem/18029290> String.Index caches the grapheme " +
"cluster size, but it is not always correct to use"))
.code {
let donor = "\u{1f601}\u{1f602}\u{1f603}"
let acceptor = "abcdef"
// FIXME: this traps right now when trying to construct Character("ab").
expectEqual("a", acceptor[donor.startIndex])
}
StringTests.test("ForeignIndexes/subscript(Index)/OutOfBoundsTrap") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("u", acceptor[donor.index(_nth: 0)])
expectEqual("v", acceptor[donor.index(_nth: 1)])
expectEqual("w", acceptor[donor.index(_nth: 2)])
let i = donor.index(_nth: 3)
expectCrashLater()
acceptor[i]
}
StringTests.test("String/subscript(_:Range)") {
let s = "foobar"
let from = s.startIndex
let to = s.index(before: s.endIndex)
let actual = s[from..<to]
expectEqual("fooba", actual)
}
StringTests.test("String/subscript(_:ClosedRange)") {
let s = "foobar"
let from = s.startIndex
let to = s.index(before: s.endIndex)
let actual = s[from...to]
expectEqual(s, actual)
}
StringTests.test("ForeignIndexes/subscript(Range)/OutOfBoundsTrap/1") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("uvw", acceptor[donor.startIndex..<donor.index(_nth: 3)])
let r = donor.startIndex..<donor.index(_nth: 4)
expectCrashLater()
acceptor[r]
}
StringTests.test("ForeignIndexes/subscript(Range)/OutOfBoundsTrap/2") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("uvw", acceptor[donor.startIndex..<donor.index(_nth: 3)])
let r = donor.index(_nth: 4)..<donor.index(_nth: 5)
expectCrashLater()
acceptor[r]
}
StringTests.test("ForeignIndexes/replaceSubrange/OutOfBoundsTrap/1") {
let donor = "abcdef"
var acceptor = "uvw"
acceptor.replaceSubrange(
donor.startIndex..<donor.index(_nth: 1), with: "u")
expectEqual("uvw", acceptor)
let r = donor.startIndex..<donor.index(_nth: 4)
expectCrashLater()
acceptor.replaceSubrange(r, with: "")
}
StringTests.test("ForeignIndexes/replaceSubrange/OutOfBoundsTrap/2") {
let donor = "abcdef"
var acceptor = "uvw"
acceptor.replaceSubrange(
donor.startIndex..<donor.index(_nth: 1), with: "u")
expectEqual("uvw", acceptor)
let r = donor.index(_nth: 4)..<donor.index(_nth: 5)
expectCrashLater()
acceptor.replaceSubrange(r, with: "")
}
StringTests.test("ForeignIndexes/removeAt/OutOfBoundsTrap") {
do {
let donor = "abcdef"
var acceptor = "uvw"
let removed = acceptor.remove(at: donor.startIndex)
expectEqual("u", removed)
expectEqual("vw", acceptor)
}
let donor = "abcdef"
var acceptor = "uvw"
let i = donor.index(_nth: 4)
expectCrashLater()
acceptor.remove(at: i)
}
StringTests.test("ForeignIndexes/removeSubrange/OutOfBoundsTrap/1") {
do {
let donor = "abcdef"
var acceptor = "uvw"
acceptor.removeSubrange(
donor.startIndex..<donor.index(after: donor.startIndex))
expectEqual("vw", acceptor)
}
let donor = "abcdef"
var acceptor = "uvw"
let r = donor.startIndex..<donor.index(_nth: 4)
expectCrashLater()
acceptor.removeSubrange(r)
}
StringTests.test("ForeignIndexes/removeSubrange/OutOfBoundsTrap/2") {
let donor = "abcdef"
var acceptor = "uvw"
let r = donor.index(_nth: 4)..<donor.index(_nth: 5)
expectCrashLater()
acceptor.removeSubrange(r)
}
StringTests.test("_splitFirst") {
var (before, after, found) = "foo.bar"._splitFirst(separator: ".")
expectTrue(found)
expectEqual("foo", before)
expectEqual("bar", after)
}
StringTests.test("hasPrefix")
.skip(.nativeRuntime("String.hasPrefix undefined without _runtime(_ObjC)"))
.code {
#if _runtime(_ObjC)
expectFalse("".hasPrefix(""))
expectFalse("".hasPrefix("a"))
expectFalse("a".hasPrefix(""))
expectTrue("a".hasPrefix("a"))
// U+0301 COMBINING ACUTE ACCENT
// U+00E1 LATIN SMALL LETTER A WITH ACUTE
expectFalse("abc".hasPrefix("a\u{0301}"))
expectFalse("a\u{0301}bc".hasPrefix("a"))
expectTrue("\u{00e1}bc".hasPrefix("a\u{0301}"))
expectTrue("a\u{0301}bc".hasPrefix("\u{00e1}"))
#else
expectUnreachable()
#endif
}
StringTests.test("literalConcatenation") {
do {
// UnicodeScalarLiteral + UnicodeScalarLiteral
var s = "1" + "2"
expectType(String.self, &s)
expectEqual("12", s)
}
do {
// UnicodeScalarLiteral + ExtendedGraphemeClusterLiteral
var s = "1" + "a\u{0301}"
expectType(String.self, &s)
expectEqual("1a\u{0301}", s)
}
do {
// UnicodeScalarLiteral + StringLiteral
var s = "1" + "xyz"
expectType(String.self, &s)
expectEqual("1xyz", s)
}
do {
// ExtendedGraphemeClusterLiteral + UnicodeScalar
var s = "a\u{0301}" + "z"
expectType(String.self, &s)
expectEqual("a\u{0301}z", s)
}
do {
// ExtendedGraphemeClusterLiteral + ExtendedGraphemeClusterLiteral
var s = "a\u{0301}" + "e\u{0302}"
expectType(String.self, &s)
expectEqual("a\u{0301}e\u{0302}", s)
}
do {
// ExtendedGraphemeClusterLiteral + StringLiteral
var s = "a\u{0301}" + "xyz"
expectType(String.self, &s)
expectEqual("a\u{0301}xyz", s)
}
do {
// StringLiteral + UnicodeScalar
var s = "xyz" + "1"
expectType(String.self, &s)
expectEqual("xyz1", s)
}
do {
// StringLiteral + ExtendedGraphemeClusterLiteral
var s = "xyz" + "a\u{0301}"
expectType(String.self, &s)
expectEqual("xyza\u{0301}", s)
}
do {
// StringLiteral + StringLiteral
var s = "xyz" + "abc"
expectType(String.self, &s)
expectEqual("xyzabc", s)
}
}
StringTests.test("appendToSubstring") {
for initialSize in 1..<16 {
for sliceStart in [0, 2, 8, initialSize] {
for sliceEnd in [0, 2, 8, sliceStart + 1] {
if sliceStart > initialSize || sliceEnd > initialSize ||
sliceEnd < sliceStart {
continue
}
var s0 = String(repeating: UnicodeScalar("x"), count: initialSize)
let originalIdentity = s0.bufferID
s0 = s0[s0.index(_nth: sliceStart)..<s0.index(_nth: sliceEnd)]
expectEqual(originalIdentity, s0.bufferID)
s0 += "x"
// For a small string size, the allocator could round up the allocation
// and we could get some unused capacity in the buffer. In that case,
// the identity would not change.
if sliceEnd != initialSize {
expectNotEqual(originalIdentity, s0.bufferID)
}
expectEqual(
String(
repeating: UnicodeScalar("x"),
count: sliceEnd - sliceStart + 1),
s0)
}
}
}
}
StringTests.test("appendToSubstringBug") {
// String used to have a heap overflow bug when one attempted to append to a
// substring that pointed to the end of a string buffer.
//
// Unused capacity
// VVV
// String buffer [abcdefghijk ]
// ^ ^
// +----+
// Substring -----------+
//
// In the example above, there are only three elements of unused capacity.
// The bug was that the implementation mistakenly assumed 9 elements of
// unused capacity (length of the prefix "abcdef" plus truly unused elements
// at the end).
let size = 1024 * 16
let suffixSize = 16
let prefixSize = size - suffixSize
for i in 1..<10 {
// We will be overflowing s0 with s1.
var s0 = String(repeating: UnicodeScalar("x"), count: size)
let s1 = String(repeating: UnicodeScalar("x"), count: prefixSize)
let originalIdentity = s0.bufferID
// Turn s0 into a slice that points to the end.
s0 = s0[s0.index(_nth: prefixSize)..<s0.endIndex]
// Slicing should not reallocate.
expectEqual(originalIdentity, s0.bufferID)
// Overflow.
s0 += s1
// We should correctly determine that the storage is too small and
// reallocate.
expectNotEqual(originalIdentity, s0.bufferID)
expectEqual(
String(
repeating: UnicodeScalar("x"),
count: suffixSize + prefixSize),
s0)
}
}
StringTests.test("COW/removeSubrange/start") {
var str = "12345678"
let literalIdentity = str.bufferID
// Check literal-to-heap reallocation.
do {
let slice = str
expectEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("12345678", str)
expectEqual("12345678", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.startIndex..<str.index(_nth: 1))
expectNotEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("2345678", str)
expectEqual("12345678", slice)
// No more reallocations are expected.
str.removeSubrange(str.startIndex..<str.index(_nth: 1))
// FIXME: extra reallocation, should be expectEqual()
expectNotEqual(heapStrIdentity, str.bufferID)
// end FIXME
expectEqual(literalIdentity, slice.bufferID)
expectEqual("345678", str)
expectEqual("12345678", slice)
}
// Check heap-to-heap reallocation.
expectEqual("345678", str)
do {
let heapStrIdentity1 = str.bufferID
let slice = str
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("345678", str)
expectEqual("345678", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.startIndex..<str.index(_nth: 1))
expectNotEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
let heapStrIdentity2 = str.bufferID
expectEqual("45678", str)
expectEqual("345678", slice)
// No more reallocations are expected.
str.removeSubrange(str.startIndex..<str.index(_nth: 1))
// FIXME: extra reallocation, should be expectEqual()
expectNotEqual(heapStrIdentity2, str.bufferID)
// end FIXME
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("5678", str)
expectEqual("345678", slice)
}
}
StringTests.test("COW/removeSubrange/end") {
var str = "12345678"
let literalIdentity = str.bufferID
// Check literal-to-heap reallocation.
expectEqual("12345678", str)
do {
let slice = str
expectEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("12345678", str)
expectEqual("12345678", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectNotEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("1234567", str)
expectEqual("12345678", slice)
// No more reallocations are expected.
str.append(UnicodeScalar("x"))
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
// FIXME: extra reallocation, should be expectEqual()
expectNotEqual(heapStrIdentity, str.bufferID)
// end FIXME
expectEqual(literalIdentity, slice.bufferID)
expectEqual("1234567", str)
expectEqual("12345678", slice)
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
str.append(UnicodeScalar("x"))
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
// FIXME: extra reallocation, should be expectEqual()
//expectNotEqual(heapStrIdentity, str.bufferID)
// end FIXME
expectEqual(literalIdentity, slice.bufferID)
expectEqual("123456", str)
expectEqual("12345678", slice)
}
// Check heap-to-heap reallocation.
expectEqual("123456", str)
do {
let heapStrIdentity1 = str.bufferID
let slice = str
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("123456", str)
expectEqual("123456", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectNotEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("12345", str)
expectEqual("123456", slice)
// No more reallocations are expected.
str.append(UnicodeScalar("x"))
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
// FIXME: extra reallocation, should be expectEqual()
expectNotEqual(heapStrIdentity, str.bufferID)
// end FIXME
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("12345", str)
expectEqual("123456", slice)
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
str.append(UnicodeScalar("x"))
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
// FIXME: extra reallocation, should be expectEqual()
//expectNotEqual(heapStrIdentity, str.bufferID)
// end FIXME
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("1234", str)
expectEqual("123456", slice)
}
}
StringTests.test("COW/replaceSubrange/end") {
// Check literal-to-heap reallocation.
do {
var str = "12345678"
let literalIdentity = str.bufferID
var slice = str[str.startIndex..<str.index(_nth: 7)]
expectEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("12345678", str)
expectEqual("1234567", slice)
// This mutation should reallocate the string.
slice.replaceSubrange(slice.endIndex..<slice.endIndex, with: "a")
expectNotEqual(literalIdentity, slice.bufferID)
expectEqual(literalIdentity, str.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("1234567a", slice)
expectEqual("12345678", str)
// No more reallocations are expected.
slice.replaceSubrange(
slice.index(_nthLast: 1)..<slice.endIndex, with: "b")
// FIXME: extra reallocation, should be expectEqual()
expectNotEqual(heapStrIdentity, slice.bufferID)
// end FIXME
expectEqual(literalIdentity, str.bufferID)
expectEqual("1234567b", slice)
expectEqual("12345678", str)
}
// Check literal-to-heap reallocation.
do {
var str = "12345678"
let literalIdentity = str.bufferID
// Move the string to the heap.
str.reserveCapacity(32)
expectNotEqual(literalIdentity, str.bufferID)
let heapStrIdentity1 = str.bufferID
var slice = str[str.startIndex..<str.index(_nth: 7)]
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
// This mutation should reallocate the string.
slice.replaceSubrange(slice.endIndex..<slice.endIndex, with: "a")
expectNotEqual(heapStrIdentity1, slice.bufferID)
expectEqual(heapStrIdentity1, str.bufferID)
let heapStrIdentity2 = slice.bufferID
expectEqual("1234567a", slice)
expectEqual("12345678", str)
// No more reallocations are expected.
slice.replaceSubrange(
slice.index(_nthLast: 1)..<slice.endIndex, with: "b")
// FIXME: extra reallocation, should be expectEqual()
expectNotEqual(heapStrIdentity2, slice.bufferID)
// end FIXME
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual("1234567b", slice)
expectEqual("12345678", str)
}
}
func asciiString<
S: Sequence where S.Iterator.Element == Character
>(_ content: S) -> String {
var s = String()
s.append(contentsOf: content)
expectEqual(1, s._core.elementWidth)
return s
}
StringTests.test("stringCoreExtensibility")
.skip(.nativeRuntime("Foundation dependency"))
.code {
#if _runtime(_ObjC)
let ascii = UTF16.CodeUnit(UnicodeScalar("X").value)
let nonAscii = UTF16.CodeUnit(UnicodeScalar("é").value)
for k in 0..<3 {
for count in 1..<16 {
for boundary in 0..<count {
var x = (
k == 0 ? asciiString("b".characters)
: k == 1 ? ("b" as NSString as String)
: ("b" as NSMutableString as String)
)._core
if k == 0 { expectEqual(1, x.elementWidth) }
for i in 0..<count {
x.append(contentsOf:
repeatElement(i < boundary ? ascii : nonAscii, count: 3))
}
// Make sure we can append pure ASCII to wide storage
x.append(contentsOf: repeatElement(ascii, count: 2))
expectEqualSequence(
[UTF16.CodeUnit(UnicodeScalar("b").value)]
+ Array(repeatElement(ascii, count: 3*boundary))
+ repeatElement(nonAscii, count: 3*(count - boundary))
+ repeatElement(ascii, count: 2),
x
)
}
}
}
#else
expectUnreachable()
#endif
}
StringTests.test("stringCoreReserve")
.skip(.nativeRuntime("Foundation dependency"))
.code {
#if _runtime(_ObjC)
for k in 0...5 {
var base: String
var startedNative: Bool
let shared: String = "X"
switch k {
case 0: (base, startedNative) = (String(), true)
case 1: (base, startedNative) = (asciiString("x".characters), true)
case 2: (base, startedNative) = ("Ξ", true)
case 3: (base, startedNative) = ("x" as NSString as String, false)
case 4: (base, startedNative) = ("x" as NSMutableString as String, false)
case 5: (base, startedNative) = (shared, true)
default:
fatalError("case unhandled!")
}
expectEqual(!base._core.hasCocoaBuffer, startedNative)
var originalBuffer = base.bufferID
let startedUnique = startedNative && base._core._owner != nil
&& isUniquelyReferencedNonObjC(&base._core._owner!)
base._core.reserveCapacity(0)
// Now it's unique
// If it was already native and unique, no reallocation
if startedUnique && startedNative {
expectEqual(originalBuffer, base.bufferID)
}
else {
expectNotEqual(originalBuffer, base.bufferID)
}
// Reserving up to the capacity in a unique native buffer is a no-op
let nativeBuffer = base.bufferID
let currentCapacity = base.capacity
base._core.reserveCapacity(currentCapacity)
expectEqual(nativeBuffer, base.bufferID)
// Reserving more capacity should reallocate
base._core.reserveCapacity(currentCapacity + 1)
expectNotEqual(nativeBuffer, base.bufferID)
// None of this should change the string contents
var expected: String
switch k {
case 0: expected = ""
case 1,3,4: expected = "x"
case 2: expected = "Ξ"
case 5: expected = shared
default:
fatalError("case unhandled!")
}
expectEqual(expected, base)
}
#else
expectUnreachable()
#endif
}
func makeStringCore(_ base: String) -> _StringCore {
var x = _StringCore()
// make sure some - but not all - replacements will have to grow the buffer
x.reserveCapacity(base._core.count * 3 / 2)
x.append(contentsOf: base._core)
// In case the core was widened and lost its capacity
x.reserveCapacity(base._core.count * 3 / 2)
return x
}
StringTests.test("StringCoreReplace") {
let narrow = "01234567890"
let wide = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪ"
for s1 in [narrow, wide] {
for s2 in [narrow, wide] {
checkRangeReplaceable(
{ makeStringCore(s1) },
{ makeStringCore(s2 + s2)[0..<$0] }
)
checkRangeReplaceable(
{ makeStringCore(s1) },
{ Array(makeStringCore(s2 + s2)[0..<$0]) }
)
}
}
}
StringTests.test("CharacterViewReplace") {
let narrow = "01234567890"
let wide = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪ"
for s1 in [narrow, wide] {
for s2 in [narrow, wide] {
checkRangeReplaceable(
{ String.CharacterView(makeStringCore(s1)) },
{ String.CharacterView(makeStringCore(s2 + s2)[0..<$0]) }
)
checkRangeReplaceable(
{ String.CharacterView(makeStringCore(s1)) },
{ Array(String.CharacterView(makeStringCore(s2 + s2)[0..<$0])) }
)
}
}
}
StringTests.test("UnicodeScalarViewReplace") {
let narrow = "01234567890"
let wide = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪ"
for s1 in [narrow, wide] {
for s2 in [narrow, wide] {
checkRangeReplaceable(
{ String(makeStringCore(s1)).unicodeScalars },
{ String(makeStringCore(s2 + s2)[0..<$0]).unicodeScalars }
)
checkRangeReplaceable(
{ String(makeStringCore(s1)).unicodeScalars },
{ Array(String(makeStringCore(s2 + s2)[0..<$0]).unicodeScalars) }
)
}
}
}
StringTests.test("reserveCapacity") {
var s = ""
let id0 = s.bufferID
let oldCap = s.capacity
let x: Character = "x" // Help the typechecker - <rdar://problem/17128913>
s.insert(contentsOf: repeatElement(x, count: s.capacity + 1), at: s.endIndex)
expectNotEqual(id0, s.bufferID)
s = ""
print("empty capacity \(s.capacity)")
s.reserveCapacity(oldCap + 2)
print("reserving \(oldCap + 2) -> \(s.capacity), width = \(s._core.elementWidth)")
let id1 = s.bufferID
s.insert(contentsOf: repeatElement(x, count: oldCap + 2), at: s.endIndex)
print("extending by \(oldCap + 2) -> \(s.capacity), width = \(s._core.elementWidth)")
expectEqual(id1, s.bufferID)
s.insert(contentsOf: repeatElement(x, count: s.capacity + 100), at: s.endIndex)
expectNotEqual(id1, s.bufferID)
}
StringTests.test("toInt") {
expectEmpty(Int(""))
expectEmpty(Int("+"))
expectEmpty(Int("-"))
expectOptionalEqual(20, Int("+20"))
expectOptionalEqual(0, Int("0"))
expectOptionalEqual(-20, Int("-20"))
expectEmpty(Int("-cc20"))
expectEmpty(Int(" -20"))
expectEmpty(Int(" \t 20ddd"))
expectOptionalEqual(Int.min, Int("\(Int.min)"))
expectOptionalEqual(Int.min + 1, Int("\(Int.min + 1)"))
expectOptionalEqual(Int.max, Int("\(Int.max)"))
expectOptionalEqual(Int.max - 1, Int("\(Int.max - 1)"))
expectEmpty(Int("\(Int.min)0"))
expectEmpty(Int("\(Int.max)0"))
// Make a String from an Int, mangle the String's characters,
// then print if the new String is or is not still an Int.
func testConvertabilityOfStringWithModification(
_ initialValue: Int,
modification: (chars: inout [UTF8.CodeUnit]) -> Void
) {
var chars = Array(String(initialValue).utf8)
modification(chars: &chars)
let str = String._fromWellFormedCodeUnitSequence(UTF8.self, input: chars)
expectEmpty(Int(str))
}
testConvertabilityOfStringWithModification(Int.min) {
$0[2] += 1; () // underflow by lots
}
testConvertabilityOfStringWithModification(Int.max) {
$0[1] += 1; () // overflow by lots
}
// Test values lower than min.
do {
let base = UInt(Int.max)
expectOptionalEqual(Int.min + 1, Int("-\(base)"))
expectOptionalEqual(Int.min, Int("-\(base + 1)"))
for i in 2..<20 {
expectEmpty(Int("-\(base + UInt(i))"))
}
}
// Test values greater than min.
do {
let base = UInt(Int.max)
for i in UInt(0)..<20 {
expectOptionalEqual(-Int(base - i) , Int("-\(base - i)"))
}
}
// Test values greater than max.
do {
let base = UInt(Int.max)
expectOptionalEqual(Int.max, Int("\(base)"))
for i in 1..<20 {
expectEmpty(Int("\(base + UInt(i))"))
}
}
// Test values lower than max.
do {
let base = Int.max
for i in 0..<20 {
expectOptionalEqual(base - i, Int("\(base - i)"))
}
}
}
// Make sure strings don't grow unreasonably quickly when appended-to
StringTests.test("growth") {
var s = ""
var s2 = s
for i in 0..<20 {
s += "x"
s2 = s
}
expectLE(s.nativeCapacity, 34)
}
StringTests.test("Construction") {
expectEqual("abc", String(["a", "b", "c"] as [Character]))
}
StringTests.test("Conversions") {
do {
var c: Character = "a"
let x = String(c)
expectTrue(x._core.isASCII)
var s: String = "a"
expectEqual(s, x)
}
do {
var c: Character = "\u{B977}"
let x = String(c)
expectFalse(x._core.isASCII)
var s: String = "\u{B977}"
expectEqual(s, x)
}
}
// Check the internal functions are correct for ASCII values
StringTests.test(
"forall x: Int8, y: Int8 . x < 128 ==> x <ascii y == x <unicode y")
.skip(.nativeRuntime("String._compareASCII undefined without _runtime(_ObjC)"))
.code {
#if _runtime(_ObjC)
let asciiDomain = (0..<128).map({ String(UnicodeScalar($0)) })
expectEqualMethodsForDomain(
asciiDomain, asciiDomain,
String._compareDeterministicUnicodeCollation, String._compareASCII)
#else
expectUnreachable()
#endif
}
#if os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
import Glibc
#endif
StringTests.test("lowercased()") {
// Use setlocale so tolower() is correct on ASCII.
setlocale(LC_ALL, "C")
// Check the ASCII domain.
let asciiDomain: [Int32] = Array(0..<128)
expectEqualFunctionsForDomain(
asciiDomain,
{ String(UnicodeScalar(Int(tolower($0)))) },
{ String(UnicodeScalar(Int($0))).lowercased() })
expectEqual("", "".lowercased())
expectEqual("abcd", "abCD".lowercased())
expectEqual("абвг", "абВГ".lowercased())
expectEqual("たちつてと", "たちつてと".lowercased())
//
// Special casing.
//
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectEqual("\u{0069}\u{0307}", "\u{0130}".lowercased())
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectEqual("\u{0069}\u{0307}", "\u{0049}\u{0307}".lowercased())
}
StringTests.test("uppercased()") {
// Use setlocale so toupper() is correct on ASCII.
setlocale(LC_ALL, "C")
// Check the ASCII domain.
let asciiDomain: [Int32] = Array(0..<128)
expectEqualFunctionsForDomain(
asciiDomain,
{ String(UnicodeScalar(Int(toupper($0)))) },
{ String(UnicodeScalar(Int($0))).uppercased() })
expectEqual("", "".uppercased())
expectEqual("ABCD", "abCD".uppercased())
expectEqual("АБВГ", "абВГ".uppercased())
expectEqual("たちつてと", "たちつてと".uppercased())
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
expectEqual("\u{0049}", "\u{0069}".uppercased())
// U+00DF LATIN SMALL LETTER SHARP S
// to upper case:
// U+0053 LATIN CAPITAL LETTER S
// U+0073 LATIN SMALL LETTER S
// But because the whole string is converted to uppercase, we just get two
// U+0053.
expectEqual("\u{0053}\u{0053}", "\u{00df}".uppercased())
// U+FB01 LATIN SMALL LIGATURE FI
// to upper case:
// U+0046 LATIN CAPITAL LETTER F
// U+0069 LATIN SMALL LETTER I
// But because the whole string is converted to uppercase, we get U+0049
// LATIN CAPITAL LETTER I.
expectEqual("\u{0046}\u{0049}", "\u{fb01}".uppercased())
}
StringTests.test("unicodeViews") {
// Check the UTF views work with slicing
// U+FFFD REPLACEMENT CHARACTER
// U+1F3C2 SNOWBOARDER
// U+2603 SNOWMAN
let winter = "\u{1F3C2}\u{2603}"
// slices
// It is 4 bytes long, so it should return a replacement character.
expectEqual(
"\u{FFFD}", String(
winter.utf8[
winter.utf8.startIndex
..<
winter.utf8.index(after: winter.utf8.index(after: winter.utf8.startIndex))
]))
expectEqual(
"\u{1F3C2}", String(
winter.utf8[winter.utf8.startIndex..<winter.utf8.index(_nth: 4)]))
expectEqual(
"\u{1F3C2}", String(
winter.utf16[winter.utf16.startIndex..<winter.utf16.index(_nth: 2)]))
expectEqual(
"\u{1F3C2}", String(
winter.unicodeScalars[
winter.unicodeScalars.startIndex..<winter.unicodeScalars.index(_nth: 1)
]))
// views
expectEqual(
winter, String(
winter.utf8[winter.utf8.startIndex..<winter.utf8.index(_nth: 7)]))
expectEqual(
winter, String(
winter.utf16[winter.utf16.startIndex..<winter.utf16.index(_nth: 3)]))
expectEqual(
winter, String(
winter.unicodeScalars[
winter.unicodeScalars.startIndex..<winter.unicodeScalars.index(_nth: 2)
]))
let ga = "\u{304b}\u{3099}"
expectEqual(ga, String(ga.utf8[ga.utf8.startIndex..<ga.utf8.index(_nth: 6)]))
}
// Validate that index conversion does something useful for Cocoa
// programmers.
StringTests.test("indexConversion")
.skip(.nativeRuntime("Foundation dependency"))
.code {
#if _runtime(_ObjC)
let re : RegularExpression
do {
re = try RegularExpression(
pattern: "([^ ]+)er", options: RegularExpression.Options())
} catch { fatalError("couldn't build regexp: \(error)") }
let s = "go further into the larder to barter."
var matches: [String] = []
re.enumerateMatches(
in: s, options: RegularExpression.MatchingOptions(), range: NSRange(0..<s.utf16.count)
) {
result, flags, stop
in
let r = result!.rangeAt(1)
let start = String.UTF16Index(_offset: r.location)
let end = String.UTF16Index(_offset: r.location + r.length)
matches.append(String(s.utf16[start..<end])!)
}
expectEqual(["furth", "lard", "bart"], matches)
#else
expectUnreachable()
#endif
}
StringTests.test("String.append(_: UnicodeScalar)") {
var s = ""
do {
// U+0061 LATIN SMALL LETTER A
let input: UnicodeScalar = "\u{61}"
s.append(input)
expectEqual(["\u{61}"], Array(s.unicodeScalars))
}
do {
// U+304B HIRAGANA LETTER KA
let input: UnicodeScalar = "\u{304b}"
s.append(input)
expectEqual(["\u{61}", "\u{304b}"], Array(s.unicodeScalars))
}
do {
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: UnicodeScalar = "\u{3099}"
s.append(input)
expectEqual(["\u{61}", "\u{304b}", "\u{3099}"], Array(s.unicodeScalars))
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: UnicodeScalar = "\u{1f425}"
s.append(input)
expectEqual(
["\u{61}", "\u{304b}", "\u{3099}", "\u{1f425}"],
Array(s.unicodeScalars))
}
}
StringTests.test("String.append(_: Character)") {
let baseCharacters: [Character] = [
// U+0061 LATIN SMALL LETTER A
"\u{61}",
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
"\u{304b}\u{3099}",
// U+3072 HIRAGANA LETTER HI
// U+309A COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
"\u{3072}\u{309A}",
// U+1F425 FRONT-FACING BABY CHICK
"\u{1f425}",
// U+0061 LATIN SMALL LETTER A
// U+0300 COMBINING GRAVE ACCENT
// U+0301 COMBINING ACUTE ACCENT
"\u{61}\u{0300}\u{0301}",
// U+0061 LATIN SMALL LETTER A
// U+0300 COMBINING GRAVE ACCENT
// U+0301 COMBINING ACUTE ACCENT
// U+0302 COMBINING CIRCUMFLEX ACCENT
"\u{61}\u{0300}\u{0301}\u{0302}",
// U+0061 LATIN SMALL LETTER A
// U+0300 COMBINING GRAVE ACCENT
// U+0301 COMBINING ACUTE ACCENT
// U+0302 COMBINING CIRCUMFLEX ACCENT
// U+0303 COMBINING TILDE
"\u{61}\u{0300}\u{0301}\u{0302}\u{0303}",
]
let baseStrings = [""] + baseCharacters.map { String($0) }
for baseIdx in baseStrings.indices {
for prefix in ["", " "] {
let base = baseStrings[baseIdx]
for inputIdx in baseCharacters.indices {
let input = (prefix + String(baseCharacters[inputIdx])).characters.last!
var s = base
s.append(input)
expectEqualSequence(
Array(base.characters) + [input],
Array(s.characters),
"baseIdx=\(baseIdx) inputIdx=\(inputIdx)")
}
}
}
}
internal func decodeCString<
C : UnicodeCodec
where
C.CodeUnit : UnsignedInteger
>(_ s: String, as codec: C.Type)
-> (result: String, repairsMade: Bool)? {
let units = s.unicodeScalars.map({ $0.value }) + [0]
return units.map({ C.CodeUnit(numericCast($0)) }).withUnsafeBufferPointer {
String.decodeCString($0.baseAddress, as: C.self)
}
}
StringTests.test("String.decodeCString/UTF8") {
let actual = decodeCString("foobar", as: UTF8.self)
expectFalse(actual!.repairsMade)
expectEqual("foobar", actual!.result)
}
StringTests.test("String.decodeCString/UTF16") {
let actual = decodeCString("foobar", as: UTF16.self)
expectFalse(actual!.repairsMade)
expectEqual("foobar", actual!.result)
}
StringTests.test("String.decodeCString/UTF32") {
let actual = decodeCString("foobar", as: UTF32.self)
expectFalse(actual!.repairsMade)
expectEqual("foobar", actual!.result)
}
internal struct ReplaceSubrangeTest {
let original: String
let newElements: String
let rangeSelection: RangeSelection
let expected: String
let closedExpected: String?
let loc: SourceLoc
internal init(
original: String, newElements: String,
rangeSelection: RangeSelection, expected: String, closedExpected: String? = nil,
file: String = #file, line: UInt = #line
) {
self.original = original
self.newElements = newElements
self.rangeSelection = rangeSelection
self.expected = expected
self.closedExpected = closedExpected
self.loc = SourceLoc(file, line, comment: "replaceSubrange() test data")
}
}
internal struct RemoveSubrangeTest {
let original: String
let rangeSelection: RangeSelection
let expected: String
let closedExpected: String
let loc: SourceLoc
internal init(
original: String, rangeSelection: RangeSelection, expected: String,
closedExpected: String? = nil,
file: String = #file, line: UInt = #line
) {
self.original = original
self.rangeSelection = rangeSelection
self.expected = expected
self.closedExpected = closedExpected ?? expected
self.loc = SourceLoc(file, line, comment: "replaceSubrange() test data")
}
}
let replaceSubrangeTests = [
ReplaceSubrangeTest(
original: "",
newElements: "",
rangeSelection: .emptyRange,
expected: ""
),
ReplaceSubrangeTest(
original: "",
newElements: "meela",
rangeSelection: .emptyRange,
expected: "meela"
),
ReplaceSubrangeTest(
original: "eela",
newElements: "m",
rangeSelection: .leftEdge,
expected: "meela",
closedExpected: "mela"
),
ReplaceSubrangeTest(
original: "meel",
newElements: "a",
rangeSelection: .rightEdge,
expected: "meela",
closedExpected: "meea"
),
ReplaceSubrangeTest(
original: "a",
newElements: "meel",
rangeSelection: .leftEdge,
expected: "meela",
closedExpected: "meel"
),
ReplaceSubrangeTest(
original: "m",
newElements: "eela",
rangeSelection: .rightEdge,
expected: "meela",
closedExpected: "eela"
),
ReplaceSubrangeTest(
original: "alice",
newElements: "bob",
rangeSelection: .offsets(1, 1),
expected: "aboblice",
closedExpected: "abobice"
),
ReplaceSubrangeTest(
original: "alice",
newElements: "bob",
rangeSelection: .offsets(1, 2),
expected: "abobice",
closedExpected: "abobce"
),
ReplaceSubrangeTest(
original: "alice",
newElements: "bob",
rangeSelection: .offsets(1, 3),
expected: "abobce",
closedExpected: "abobe"
),
ReplaceSubrangeTest(
original: "alice",
newElements: "bob",
rangeSelection: .offsets(1, 4),
expected: "abobe",
closedExpected: "abob"
),
ReplaceSubrangeTest(
original: "alice",
newElements: "bob",
rangeSelection: .offsets(1, 5),
expected: "abob"
),
ReplaceSubrangeTest(
original: "bob",
newElements: "meela",
rangeSelection: .offsets(1, 2),
expected: "bmeelab",
closedExpected: "bmeela"
),
]
let removeSubrangeTests = [
RemoveSubrangeTest(
original: "",
rangeSelection: .emptyRange,
expected: ""
),
RemoveSubrangeTest(
original: "a",
rangeSelection: .middle,
expected: ""
),
RemoveSubrangeTest(
original: "perdicus",
rangeSelection: .leftHalf,
expected: "icus"
),
RemoveSubrangeTest(
original: "perdicus",
rangeSelection: .rightHalf,
expected: "perd"
),
RemoveSubrangeTest(
original: "alice",
rangeSelection: .middle,
expected: "ae"
),
RemoveSubrangeTest(
original: "perdicus",
rangeSelection: .middle,
expected: "pes"
),
RemoveSubrangeTest(
original: "perdicus",
rangeSelection: .offsets(1, 2),
expected: "prdicus",
closedExpected: "pdicus"
),
RemoveSubrangeTest(
original: "perdicus",
rangeSelection: .offsets(3, 6),
expected: "perus",
closedExpected: "pers"
)
]
StringTests.test("String.replaceSubrange()/characters/range") {
for test in replaceSubrangeTests {
var theString = test.original
let c = test.original.characters
let rangeToReplace = test.rangeSelection.range(in: c)
let newCharacters : [Character] = test.newElements.characters.map { $0 }
theString.replaceSubrange(rangeToReplace, with: newCharacters)
expectEqual(
test.expected,
theString,
stackTrace: SourceLocStack().with(test.loc))
}
}
StringTests.test("String.replaceSubrange()/string/range") {
for test in replaceSubrangeTests {
var theString = test.original
let c = test.original.characters
let rangeToReplace = test.rangeSelection.range(in: c)
theString.replaceSubrange(rangeToReplace, with: test.newElements)
expectEqual(
test.expected,
theString,
stackTrace: SourceLocStack().with(test.loc))
}
}
StringTests.test("String.replaceSubrange()/characters/closedRange") {
for test in replaceSubrangeTests {
guard let closedExpected = test.closedExpected else {
continue
}
var theString = test.original
let c = test.original.characters
let rangeToReplace = test.rangeSelection.closedRange(in: c)
let newCharacters = Array(test.newElements.characters)
theString.replaceSubrange(rangeToReplace, with: newCharacters)
expectEqual(
closedExpected,
theString,
stackTrace: SourceLocStack().with(test.loc))
}
}
StringTests.test("String.replaceSubrange()/string/closedRange") {
for test in replaceSubrangeTests {
guard let closedExpected = test.closedExpected else {
continue
}
var theString = test.original
let c = test.original.characters
let rangeToReplace = test.rangeSelection.closedRange(in: c)
theString.replaceSubrange(rangeToReplace, with: test.newElements)
expectEqual(
closedExpected,
theString,
stackTrace: SourceLocStack().with(test.loc))
}
}
StringTests.test("String.removeSubrange()/range") {
for test in removeSubrangeTests {
var theString = test.original
let c = test.original.characters
let rangeToRemove = test.rangeSelection.range(in: c)
theString.removeSubrange(rangeToRemove)
expectEqual(
test.expected,
theString,
stackTrace: SourceLocStack().with(test.loc))
}
}
StringTests.test("String.removeSubrange()/closedRange") {
for test in removeSubrangeTests {
switch test.rangeSelection {
case .emptyRange: continue
default: break
}
var theString = test.original
let c = test.original.characters
let rangeToRemove = test.rangeSelection.closedRange(in: c)
theString.removeSubrange(rangeToRemove)
expectEqual(
test.closedExpected,
theString,
stackTrace: SourceLocStack().with(test.loc))
}
}
runAllTests()
| apache-2.0 | 159b4c7bc411e6e2dd4ed6b13d4cf003 | 27.713454 | 90 | 0.665067 | 3.964544 | false | true | false | false |
lionhylra/UIView-InterruptibleTap | UIView+InterruptibleTapGestureRecognizer.swift | 1 | 3981 | //
// UIView+InterruptibleTapGestureRecognizer.swift
// GestureTest
//
// Created by HeYilei on 3/12/2015.
// Copyright © 2015 jEyLaBs. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Yilei He, lionhylra.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
var touchResponsibleRange:CGFloat = 80.0
@objc public protocol InterruptibleTapDelegate:class{
optional func viewPressed(view:UIView!)
optional func viewNotPressed(view:UIView!)
optional func action(view:UIView!)
}
public extension UIView {
private struct AssociatedKeys {
static var delegateKey = "delegate"
}
private var interruptibleTapdelegate:InterruptibleTapDelegate! {
get{
return objc_getAssociatedObject(self, &AssociatedKeys.delegateKey) as? InterruptibleTapDelegate
}
set{
objc_setAssociatedObject(self, &AssociatedKeys.delegateKey, newValue as AnyObject, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
func addInterruptibleTapGestureRecognizerWithDelegate(delegate:InterruptibleTapDelegate){
self.interruptibleTapdelegate = delegate
self.userInteractionEnabled = true
let longPress = UILongPressGestureRecognizer(target: self, action: "viewTapped:")
longPress.minimumPressDuration = 0.01
self.addGestureRecognizer(longPress)
}
@objc private func viewTapped(gestureRecognizer:UILongPressGestureRecognizer){
struct staticVariables{
static var startLocation:CGPoint = CGPointZero
static var distance:CGFloat = 0.0
}
switch gestureRecognizer.state {
case .Began:
self.interruptibleTapdelegate.viewPressed?(gestureRecognizer.view)
staticVariables.startLocation = gestureRecognizer.locationInView(nil)
staticVariables.distance = 0.0
case.Changed:
if CGPointEqualToPoint(staticVariables.startLocation, CGPointZero) {
return
}
let currentLocation = gestureRecognizer.locationInView(nil)
staticVariables.distance = hypot(staticVariables.startLocation.x - currentLocation.x, staticVariables.startLocation.y - currentLocation.y)
if staticVariables.distance > touchResponsibleRange {
self.interruptibleTapdelegate.viewNotPressed?(gestureRecognizer.view)
}else{
self.interruptibleTapdelegate.viewPressed?(gestureRecognizer.view)
}
case.Ended:
self.interruptibleTapdelegate.viewNotPressed?(gestureRecognizer.view)
if staticVariables.distance < touchResponsibleRange {
self.interruptibleTapdelegate.action?(gestureRecognizer.view)
}
default:
self.interruptibleTapdelegate.viewNotPressed?(gestureRecognizer.view)
}
}
}
| mit | af7a5630b7f29cc7bf5e6cd466d8ac43 | 42.26087 | 150 | 0.704271 | 4.962594 | false | false | false | false |
64characters/Telephone | DomainTests/SystemToUserAgentAudioDeviceMapTests.swift | 1 | 2513 | //
// SystemToUserAgentAudioDeviceMapTests.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
@testable import Domain
import DomainTestDoubles
import XCTest
final class SystemToUserAgentAudioDeviceMapTests: XCTestCase {
private var factory: SystemAudioDeviceTestFactory!
override func setUp() {
super.setUp()
factory = SystemAudioDeviceTestFactory()
}
func testMapsSystemToUserAgentDeviceByNameAndIOPort() {
let systemDevices = factory.all
let userAgentDevices: [UserAgentAudioDevice] = [
SimpleUserAgentAudioDevice(device: factory.someInput),
SimpleUserAgentAudioDevice(device: factory.someOutput)
]
let sut = SystemToUserAgentAudioDeviceMap(systemDevices: systemDevices, userAgentDevices: userAgentDevices)
XCTAssertTrue(sut.userAgentDevice(for: factory.someInput) == userAgentDevices[0])
XCTAssertTrue(sut.userAgentDevice(for: factory.someOutput) == userAgentDevices[1])
}
func testMapsSystemToUserAgentDeviceByNameAndIOPortWhenTwoDevicesHaveTheSameName() {
let systemDevices = [factory.someInput, factory.outputWithNameLikeSomeInput]
let userAgentDevices: [UserAgentAudioDevice] = [
SimpleUserAgentAudioDevice(device: systemDevices[1]),
SimpleUserAgentAudioDevice(device: systemDevices[0])
]
let sut = SystemToUserAgentAudioDeviceMap(systemDevices: systemDevices, userAgentDevices: userAgentDevices)
XCTAssertTrue(sut.userAgentDevice(for: systemDevices[0]) == userAgentDevices[1])
XCTAssertTrue(sut.userAgentDevice(for: systemDevices[1]) == userAgentDevices[0])
}
func testReturnsNullObjectWhenNoMatchingUserAgentDeviceFound() {
let sut = SystemToUserAgentAudioDeviceMap(systemDevices: factory.all, userAgentDevices: [])
let result = sut.userAgentDevice(for: factory.someInput)
XCTAssertTrue(result.isNil)
}
}
| gpl-3.0 | aa7532956fa9db554c904621cafc79b7 | 38.234375 | 115 | 0.739148 | 4.65 | false | true | false | false |
MangoMade/LyricsView | Source/LRCPaser/LRCPaser.swift | 1 | 2481 | //
// LRCPaser.swift
// LyricsView
//
// Created by Aqua on 23/11/2017.
// Copyright © 2017 Aqua. All rights reserved.
//
import UIKit
public class LRCPaser: PaserProtocol {
public var content: String
public required init(with content: String) {
self.content = content
}
public func generateModel() -> LyricsModel {
let lineContents = content.components(separatedBy: "\n")
let models = LyricsModel()
for line in lineContents {
if let lineModels = paserLine(line) {
models.lines.append(contentsOf: lineModels)
}
}
models.lines.sort { (model1, model2) -> Bool in
return model1.beginTime < model2.beginTime
}
return models
}
private func paserLine(_ text: String) -> [LyricsLineModelProtocol]? {
let pattern = "^(\\[.*\\])(.*)$"
let regExp = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
guard let result = regExp?.matches(in: text, options: [], range: NSMakeRange(0, text.utf16.count)).first else {
return nil
}
let timesRange = result.range(at: 1)
let timesString = (text as NSString).substring(with: timesRange)
let lyricsRange = result.range(at: 2)
let lyricsString = (text as NSString).substring(with: lyricsRange)
if let times = paserTimes(timesString) {
var lines: [LRCLineModel] = []
times.forEach({ (time) in
var model = LRCLineModel()
model.beginTime = time
model.text = lyricsString
lines.append(model)
})
return lines
} else {
return nil
}
}
private func paserTimes(_ timesString: String) -> [TimeInterval]? {
let pattern = "\\[(.*?)\\]"
let regExp = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
guard let results = regExp?.matches(in: timesString, options: [], range: NSMakeRange(0, timesString.utf16.count)) else {
return nil
}
var times: [TimeInterval] = []
results.forEach { result in
let timeRange = result.range(at: 1)
let timeString = (timesString as NSString).substring(with: timeRange)
times.append(stringToTimeInterval(timeString))
}
return times
}
}
| mit | b74c8f797916f96618a906037d2c7adb | 32.066667 | 128 | 0.568952 | 4.389381 | false | false | false | false |
j-chao/venture | source/venture/SettingsVC.swift | 1 | 8467 | //
// SettingsVC.swift
// venture
//
// Created by Justin Chao on 3/17/17.
// Copyright © 2017 Group1. All rights reserved.
//
import UIKit
import Firebase
import FBSDKLoginKit
class SettingsVC: UIViewController {
@IBOutlet weak var developedByLbl: UILabel!
var alertController:UIAlertController? = nil
var newEmail: UITextField? = nil
var newPassword: UITextField? = nil
let fbManager = FBSDKLoginManager()
let firEmail = FIRAuth.auth()?.currentUser?.email
@IBOutlet weak var emailButton: UIButton!
@IBOutlet weak var passButton: UIButton!
@IBOutlet weak var timeSeg: UISegmentedControl!
@IBOutlet weak var backgroundSeg: UISegmentedControl!
override func viewDidLoad() {
self.setBackground()
self.developedByLbl.text = "Developed by Justin Chao, \n Julianne Crea, and Connie Liu"
super.viewDidLoad()
if firEmail == nil {
self.emailButton.setTitle("Add Email", for: [])
self.passButton.setTitle("Add Password", for: [])
}
let defaults = UserDefaults.standard
let timeFormatDefault = defaults.string(forKey: "timeFormat")
if timeFormatDefault == "military" {
self.timeSeg.selectedSegmentIndex = 1
}
else {
self.timeSeg.selectedSegmentIndex = 0
}
let backgroundDefault = defaults.integer(forKey: "background")
if backgroundDefault == 1 {
self.backgroundSeg.selectedSegmentIndex = 0
}
else if backgroundDefault == 2 {
self.backgroundSeg.selectedSegmentIndex = 1
}
else if backgroundDefault == 3 {
self.backgroundSeg.selectedSegmentIndex = 2
}
else if backgroundDefault == 4 {
self.backgroundSeg.selectedSegmentIndex = 3
}
else if backgroundDefault == 5 {
self.backgroundSeg.selectedSegmentIndex = 4
}
}
@IBAction func changeEmail(_ sender: Any) {
if firEmail != nil {
self.alertController = UIAlertController(title: "Change Email", message: "Change your current email.", preferredStyle: UIAlertControllerStyle.alert)
}
else {
self.alertController = UIAlertController(title: "Add an Email", message: "Add an email address to your user account.", preferredStyle: UIAlertControllerStyle.alert)
}
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) -> Void in
FIRAuth.auth()?.currentUser?.updateEmail((self.newEmail?.text!)!) {
(error) in
if error != nil {
self.alertController = UIAlertController(title:"Email is already in use!", message: "", preferredStyle: UIAlertControllerStyle.alert)
self.present(self.alertController!, animated: true, completion: nil)
let cancel = UIAlertAction(title: "cancel", style: UIAlertActionStyle.cancel) {
(action) -> Void in
}
self.alertController!.addAction(cancel)
}
else {
print ("email updated")
}
}
})
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (action) -> Void in
}
self.alertController!.addAction(ok)
self.alertController!.addAction(cancel)
self.alertController!.addTextField { (textField) -> Void in
self.newEmail = textField
self.newEmail?.placeholder = "enter new email"
}
present(self.alertController!, animated: true, completion: nil)
}
@IBAction func changePassword(_ sender: Any) {
if firEmail != nil {
self.alertController = UIAlertController(title: "Change Password", message: "Password must be at least 6 characters long.", preferredStyle: UIAlertControllerStyle.alert)
}
else {
self.alertController = UIAlertController(title: "Add Password", message: "Password must be at least 6 characters long.", preferredStyle: UIAlertControllerStyle.alert)
}
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) -> Void in
FIRAuth.auth()?.currentUser?.updatePassword((self.newPassword?.text!)!) { (error) in
if error != nil {
// Firebase requires a minimum length 6-characters password
print (error.debugDescription)
}
else {
}
}
})
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (action) -> Void in
}
self.alertController!.addAction(ok)
self.alertController!.addAction(cancel)
self.alertController!.addTextField { (textField) -> Void in
self.newPassword = textField
self.newPassword?.placeholder = "enter new password"
}
present(self.alertController!, animated: true, completion: nil)
}
@IBAction func deleteAccount(_ sender: Any) {
self.alertController = UIAlertController(title: "Delete Account", message: "Are you sure you want to delete your account?", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "Delete", style: UIAlertActionStyle.default, handler: { (action) -> Void in
let defaults = UserDefaults.standard
defaults.set(nil, forKey: "userID")
let user = FIRAuth.auth()?.currentUser
let ref = FIRDatabase.database().reference().child("users")
ref.child((user?.uid)!).removeValue()
user?.delete { error in
if error != nil {
print ("delete account error")
} else {
self.fbManager.logOut()
let storyboard: UIStoryboard = UIStoryboard(name: "login", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "Login")
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true, completion: nil)
}
}
})
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (action) -> Void in
}
self.alertController!.addAction(ok)
self.alertController!.addAction(cancel)
present(self.alertController!, animated: true, completion: nil)
}
@IBAction func logOut(_ sender: Any) {
let defaults = UserDefaults.standard
defaults.set(nil, forKey: "userID")
self.fbManager.logOut()
}
@IBAction func timeSegAction(_ sender: Any) {
let defaults = UserDefaults.standard
switch self.timeSeg.selectedSegmentIndex {
case 0:
timeFormat = "regular"
defaults.set(timeFormat, forKey: "timeFormat")
case 1:
timeFormat = "military"
defaults.set(timeFormat, forKey: "timeFormat")
default:
break
}
}
@IBAction func backgroundSegAction(_ sender: Any) {
let defaults = UserDefaults.standard
switch self.backgroundSeg.selectedSegmentIndex {
case 0:
background = 1
defaults.set(background, forKey: "background")
case 1:
background = 2
defaults.set(background, forKey: "background")
case 2:
background = 3
defaults.set(background, forKey: "background")
case 3:
background = 4
defaults.set(background, forKey: "background")
case 4:
background = 5
defaults.set(background, forKey: "background")
default:
break
}
let parent = self.view.superview
self.view.removeFromSuperview()
self.view = nil
parent?.addSubview(self.view)
}
@IBAction func tripsButton(_ sender: UIBarButtonItem) {
_ = self.navigationController?.popViewController(animated:true)
}
}
| mit | 729706cbc77173438436f468e5a8fd3d | 35.969432 | 181 | 0.577959 | 5.307837 | false | false | false | false |
Zewo/Zewo | Sources/Core/Logger/StandardOutputAppender.swift | 2 | 740 | public struct StandardOutputAppender : LogAppender {
public let levels: Logger.Level
public init(levels: Logger.Level = .all) {
self.levels = levels
}
public func append(event: Logger.Event) {
var logMessage = ""
let level = event.level.description
logMessage += level == "" ? "" : "[" + level + "]"
logMessage += "[" + event.timestamp.description + "]"
logMessage += "[" + event.locationInfo.description + "]"
if let message = event.message {
logMessage += ":" + String(describing: message)
}
if let error = event.error {
logMessage += ":" + String(describing: error)
}
print(logMessage)
}
}
| mit | 0ceac5cbc21c6b924bca0811890057bf | 26.407407 | 64 | 0.55 | 4.713376 | false | false | false | false |
nguyenantinhbk77/practice-swift | playgrounds/HealthKit Measures.playground/Contents.swift | 2 | 1844 | import UIKit
import HealthKit
/**
** Convert grams to Kilograms
**/
let gramUnit = HKUnit(fromMassFormatterUnit: NSMassFormatterUnit.Gram)
let kilogramUnit = HKUnit(fromMassFormatterUnit: NSMassFormatterUnit.Kilogram)
let weightInGrams:Double = 74_250
// Create a quantity object
let weightQuantity = HKQuantity(unit: gramUnit, doubleValue: weightInGrams)
// Convert the quantity to Kilograms
let weightInKilograms = weightQuantity.doubleValueForUnit(kilogramUnit)
println("Your wieght is \(weightInKilograms) kilograms")
println("Your weight is \(weightInGrams) grams")
/**
** Convert an exercise from 1500 calories to kilojaules
**/
let caloriesValue:Double = 1_500
// Calories unit
let caloriesUnit = HKQuantity(unit: HKUnit.calorieUnit(), doubleValue: caloriesValue)
let kilojoulesValue = caloriesUnit.doubleValueForUnit(HKUnit.jouleUnitWithMetricPrefix(HKMetricPrefix.Kilo))
// Energy formatter
let energyFormatter = NSEnergyFormatter()
let caloriesString = energyFormatter.stringFromValue(caloriesValue, unit: NSEnergyFormatterUnit.Calorie)
let kilojoulesString = energyFormatter.stringFromValue(kilojoulesValue, unit: NSEnergyFormatterUnit.Kilojoule)
println("You've burned \(caloriesString)")
println("You've burned \(kilojoulesString)")
/**
** Converting meters to feet
**/
let distanceInMeters:Double = 1_234
let metersUnit = HKQuantity(unit: HKUnit.meterUnit(),
doubleValue: distanceInMeters)
let feetValue = metersUnit.doubleValueForUnit(HKUnit.footUnit())
let lengthFormatter = NSLengthFormatter()
let metersString = lengthFormatter.stringFromValue(distanceInMeters, unit: NSLengthFormatterUnit.Meter)
let feetString = lengthFormatter.stringFromValue(feetValue, unit: NSLengthFormatterUnit.Foot)
println("You've driven \(metersString)")
println("You've driven \(feetString)")
println(NSUUID().UUIDString)
| mit | f040107b6c642e0b93bbf608f7ffa61d | 29.733333 | 110 | 0.80423 | 3.87395 | false | false | false | false |
TurfDb/Turf | Turf/Cache/Cache.swift | 1 | 5472 | import Foundation
/**
* Cache port from YapDatabase
*/
internal class Cache<Key: Hashable, Value> where Key: Any {
// MARK: Internal properties
var onEviction: ((Value?) -> Void)?
var hasEntries: Bool {
return container.count > 0
}
// MARK: Private properties
private let capacity: Int
private var container: [Key: CacheEntry<Key, Value>]
private var mostRecentEntry: CacheEntry<Key, Value>?
private var leastRecentEntry: CacheEntry<Key, Value>?
private var evictedEntry: CacheEntry<Key, Value>?
// MARK: Object lifecycle
init(capacity: Int) {
self.capacity = capacity
self.container = Dictionary()
}
// MARK: Internal methods
subscript(key: Key) -> Value? {
get {
return valueForKey(key)
}
set {
seValue(newValue!, forKey: key)
}
}
func seValue(_ value: Value, forKey key: Key) {
if let existingEntry = container[key] {
// Update item value
existingEntry.value = value
if existingEntry !== mostRecentEntry {
// Remove item from current position in linked-list
//
// Notes:
// We fetched the item from the list,
// so we know there's a valid mostRecentCacheItem & leastRecentCacheItem.
// Furthermore, we know the item isn't the mostRecentCacheItem.
existingEntry.previous?.next = existingEntry.next
if existingEntry === leastRecentEntry {
leastRecentEntry = existingEntry.previous
} else {
existingEntry.next?.previous = existingEntry.previous
}
// Move item to beginning of linked-list
existingEntry.previous = nil
existingEntry.next = mostRecentEntry
mostRecentEntry?.previous = existingEntry
mostRecentEntry = existingEntry
}
} else {
var entry: CacheEntry<Key, Value>
if let evictedEntry = evictedEntry {
entry = evictedEntry
entry.key = key
entry.value = value
self.evictedEntry = nil
} else {
entry = CacheEntry(key: key, value: value)
}
container[key] = entry
// Add item to beginning of linked-list
entry.next = mostRecentEntry
mostRecentEntry?.previous = entry
mostRecentEntry = entry
// Evict leastRecentCacheItem if needed
if capacity > 0 && container.count > capacity {
leastRecentEntry?.previous?.next = nil
evictedEntry = leastRecentEntry
leastRecentEntry = leastRecentEntry?.previous
if let evictedEntry = evictedEntry, let key = evictedEntry.key {
container.removeValue(forKey: key)
evictedEntry.previous = nil
evictedEntry.next = nil
evictedEntry.key = nil
onEviction?(evictedEntry.value)
evictedEntry.value = nil
}
} else {
if (leastRecentEntry == nil) {
leastRecentEntry = entry
}
}
}
}
func valueForKey(_ key: Key) -> Value? {
if let entry = container[key] {
if entry !== mostRecentEntry {
// Remove item from current position in linked-list.
//
// Notes:
// We fetched the item from the list,
// so we know there's a valid mostRecentCacheItem & leastRecentCacheItem.
// Furthermore, we know the item isn't the mostRecentCacheItem.
entry.previous?.next = entry.next
if (entry === leastRecentEntry) {
leastRecentEntry = entry.previous
} else {
entry.next?.previous = entry.previous
}
// Move item to beginning of linked-list
entry.previous = nil
entry.next = mostRecentEntry;
mostRecentEntry?.previous = entry
mostRecentEntry = entry
}
return entry.value
}
return nil
}
func removeValueForKey(_ key: Key) {
if let entry = container[key] {
entry.previous?.next = entry.next
entry.next?.previous = entry.previous
if mostRecentEntry === entry {
mostRecentEntry = entry.next
}
if leastRecentEntry === entry {
leastRecentEntry = entry.previous
}
container.removeValue(forKey: key)
}
}
func removeAllValues() {
mostRecentEntry = nil
leastRecentEntry = nil
evictedEntry = nil
container.removeAll()
}
func removeAllValues(_ each: (Value) -> Void) {
mostRecentEntry = nil
leastRecentEntry = nil
evictedEntry = nil
for (_, entry) in container {
if let value = entry.value {
each(value)
}
}
container.removeAll()
}
func hasKey(_ key: Key) -> Bool {
return container[key] != nil
}
}
| mit | f575b8ad18ff478c89fb72735f6f0889 | 27.206186 | 89 | 0.522295 | 5.216397 | false | false | false | false |
geocore/geocore-swift | GeocoreKit/GeocoreUser.swift | 1 | 29751 | //
// GeocoreUser.swift
// GeocoreKit
//
// Created by Purbo Mohamad on 11/21/15.
//
//
import Foundation
import Alamofire
import SwiftyJSON
import PromiseKit
#if os(iOS)
import UIKit
#endif
public enum GeocoreUserEventRelationshipType: String {
case organizer = "ORGANIZER"
case performer = "PERFORMER"
case participant = "PARTICIPANT"
case attendant = "ATTENDANT"
case custom01 = "CUSTOM01"
case custom02 = "CUSTOM02"
case custom03 = "CUSTOM03"
case custom04 = "CUSTOM04"
case custom05 = "CUSTOM05"
case custom06 = "CUSTOM06"
case custom07 = "CUSTOM07"
case custom08 = "CUSTOM08"
case custom09 = "CUSTOM09"
case custom10 = "CUSTOM10"
}
public enum GeocoreUserPlaceRelationshipType: String {
case creator = "CREATOR"
case owner = "OWNER"
case manager = "MANAGER"
case organizer = "ORGANIZER"
case staff = "STAFF"
case seller = "SELLER"
case agent = "AGENT"
case realtor = "REALTOR"
case follower = "FOLLOWER"
case supporter = "SUPPORTER"
case visitor = "VISITOR"
case customer = "CUSTOMER"
case player = "PLAYER"
case member = "MEMBER"
case buyer = "BUYER"
case custom01 = "CUSTOM01"
case custom02 = "CUSTOM02"
case custom03 = "CUSTOM03"
case custom04 = "CUSTOM04"
case custom05 = "CUSTOM05"
case custom06 = "CUSTOM06"
case custom07 = "CUSTOM07"
case custom08 = "CUSTOM08"
case custom09 = "CUSTOM09"
case custom10 = "CUSTOM10"
}
open class GeocoreUserOperation: GeocoreTaggableOperation {
fileprivate var groupIds: [String]?
open func addTo(groupIds: [String]) {
self.groupIds = groupIds
}
open override func buildQueryParameters() -> Alamofire.Parameters {
var dict = super.buildQueryParameters()
if let groupIds = self.groupIds {
dict["group_ids"] = groupIds.joined(separator: ",")
}
dict["project_id"] = Geocore.sharedInstance.projectId
return dict
}
open func register(user: GeocoreUser, callback: @escaping (GeocoreResult<GeocoreUser>) -> Void) {
Geocore.sharedInstance.POST(
"/register",
parameters: buildQueryParameters(),
body: user.asDictionary(),
callback: callback)
}
open func register(user: GeocoreUser) -> Promise<GeocoreUser> {
let params = buildQueryParameters()
if params.count > 0 {
return Geocore.sharedInstance.promisedPOST(
"/register",
parameters: params,
body: user.asDictionary())
} else {
return Geocore.sharedInstance.promisedPOST(
"/register",
parameters: user.asDictionary())
}
}
}
open class GeocoreUserTagOperation: GeocoreTaggableOperation {
open func update() -> Promise<[GeocoreTag]> {
let params = buildQueryParameters()
if params.count > 0 {
if let path = buildPath(forService: "/users", withSubPath: "/tags") {
// body cannot be nil, otherwise params will go to body
return Geocore.sharedInstance.promisedPOST(path, parameters: params, body: [String: Any]())
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting id")) }
}
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting tag parameters")) }
}
}
}
open class GeocoreUserQuery: GeocoreTaggableQuery {
fileprivate(set) open var alternateIdIndex: Int?
open func forAlternateIdIndex(_ alternateIdIndex: Int) -> Self {
self.alternateIdIndex = alternateIdIndex
return self
}
open override func buildQueryParameters() -> Alamofire.Parameters {
var dict = super.buildQueryParameters()
if let alternateIdIndex = self.alternateIdIndex {
dict["alt"] = alternateIdIndex
}
return dict
}
open func get() -> Promise<GeocoreUser> {
return self.get(forService: "/users")
}
open func eventRelationships() -> Promise<[GeocoreUserEvent]> {
if let userId = self.id {
return GeocoreUserEventQuery().with(object1Id: userId).all()
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting id")) }
}
}
open func eventRelationships(_ event: GeocoreEvent) -> Promise<[GeocoreUserEvent]> {
if let userId = self.id {
return GeocoreUserEventQuery()
.with(object1Id: userId)
.with(object2Id: event.id!)
.all()
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting id")) }
}
}
open func placeRelationships() -> Promise<[GeocoreUserPlace]> {
if let userId = self.id {
return GeocoreUserPlaceQuery().with(object1Id: userId).all()
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting id")) }
}
}
open func placeRelationships(_ place: GeocorePlace) -> Promise<[GeocoreUserPlace]> {
if let userId = self.id {
return GeocoreUserPlaceQuery()
.with(object1Id: userId)
.with(object2Id: place.id!)
.all()
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting id")) }
}
}
open func itemRelationships() -> Promise<[GeocoreUserItem]> {
if let userId = self.id {
return GeocoreUserItemQuery().with(object1Id: userId).all()
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting id")) }
}
}
}
open class GeocoreUser: GeocoreTaggable {
public static let customDataKeyFacebookID = "sns.fb.id"
public static let customDataKeyFacebookName = "sns.fb.name"
public static let customDataKeyFacebookEmail = "sns.fb.email"
public static let customDataKeyTwitterID = "sns.tw.id"
public static let customDataKeyTwitterName = "sns.tw.name"
public static let customDataKeyGooglePlusID = "sns.gp.id"
public static let customDataKeyGooglePlusName = "sns.gp.name"
public static let customDataKeyiOSPushToken = "push.ios.token"
public static let customDataKeyiOSPushLanguage = "push.ios.lang"
public static let customDataKeyiOSPushEnabled = "push.enabled"
public var alternateId1: String?
public var alternateId2: String?
public var alternateId3: String?
public var alternateId4: String?
public var alternateId5: String?
public var password: String?
public var email: String?
private(set) public var lastLocationTime: Date?
private(set) public var lastLocation: GeocorePoint?
public override init() {
super.init()
}
public required init(_ json: JSON) {
self.email = json["email"].string
self.alternateId1 = json["alternateId1"].string
self.alternateId2 = json["alternateId2"].string
self.alternateId3 = json["alternateId3"].string
self.alternateId4 = json["alternateId4"].string
self.alternateId5 = json["alternateId5"].string
self.lastLocationTime = Date.fromGeocoreFormattedString(json["lastLocationTime"].string)
self.lastLocation = GeocorePoint(json["lastLocation"])
super.init(json)
}
open override func asDictionary() -> [String: Any] {
var dict = super.asDictionary()
if let password = self.password { dict["password"] = password as AnyObject? }
if let email = self.email { dict["email"] = email as AnyObject? }
if let alternateId1 = self.alternateId1 { dict["alternateId1"] = alternateId1 as AnyObject? }
if let alternateId2 = self.alternateId2 { dict["alternateId2"] = alternateId2 as AnyObject? }
if let alternateId3 = self.alternateId3 { dict["alternateId3"] = alternateId3 as AnyObject? }
if let alternateId4 = self.alternateId4 { dict["alternateId4"] = alternateId4 as AnyObject? }
if let alternateId5 = self.alternateId5 { dict["alternateId5"] = alternateId5 as AnyObject? }
return dict
}
open class func userId(withSuffix suffix: String) -> String {
if let projectId = Geocore.sharedInstance.projectId {
if projectId.hasPrefix("PRO") {
// user ID pattern: USE-[project_suffix]-[user_id_suffix]
return "USE\(projectId[projectId.index(projectId.startIndex, offsetBy: 3)...])-\(suffix)"
} else {
return suffix
}
} else {
return suffix
}
}
open class func defaultName() -> String {
#if os(iOS)
#if (arch(i386) || arch(x86_64))
// iOS simulator
return "IOS_SIMULATOR"
#else
// iOS device
return UIDevice.current.identifierForVendor!.uuidString
#endif
#else
// TODO: generate ID on OSX based on user's device ID
return "DEFAULT"
#endif
}
open class func defaultId() -> String {
return userId(withSuffix: defaultName())
}
open class func defaultEmail() -> String {
return "\(defaultName())@geocore.jp"
}
open class func defaultPassword() -> String {
return String(defaultId().reversed())
}
open func setFacebookUser(_ id: String, name: String) {
_ = self
.addCustomData(GeocoreUser.customDataKeyFacebookID, value: id)
.addCustomData(GeocoreUser.customDataKeyFacebookName, value: name)
}
open func isFacebookUser() -> Bool {
if let customData = self.customData {
return customData[GeocoreUser.customDataKeyFacebookID] != nil
}
return false
}
open func facebookID() -> String? {
if let customData = self.customData {
if let val = customData[GeocoreUser.customDataKeyFacebookID] {
return val
}
}
return nil
}
open func facebookName() -> String? {
if let customData = self.customData {
if let val = customData[GeocoreUser.customDataKeyFacebookName] {
return val
}
}
return nil
}
open func setTwitterUser(_ id: String, name: String) {
_ = self
.addCustomData(GeocoreUser.customDataKeyTwitterID, value: id)
.addCustomData(GeocoreUser.customDataKeyTwitterName, value: name)
}
open func isTwitterUser() -> Bool {
if let customData = self.customData {
return customData[GeocoreUser.customDataKeyTwitterID] != nil
}
return false
}
open func twitterID() -> String? {
if let customData = self.customData {
if let val = customData[GeocoreUser.customDataKeyTwitterID] {
return val
}
}
return nil
}
open func twitterName() -> String? {
if let customData = self.customData {
if let val = customData[GeocoreUser.customDataKeyTwitterName] {
return val
}
}
return nil
}
open func setGooglePlusUser(_ id: String, name: String) {
_ = self
.addCustomData(GeocoreUser.customDataKeyGooglePlusID, value: id)
.addCustomData(GeocoreUser.customDataKeyGooglePlusName, value: name)
}
open func isGooglePlusUser() -> Bool {
if let customData = self.customData {
return customData[GeocoreUser.customDataKeyGooglePlusID] != nil
}
return false
}
open func googlePlusID() -> String? {
if let customData = self.customData {
if let val = customData[GeocoreUser.customDataKeyGooglePlusID] {
return val
}
}
return nil
}
open func googlePlusName() -> String? {
if let customData = self.customData {
if let val = customData[GeocoreUser.customDataKeyGooglePlusName] {
return val
}
}
return nil
}
open func registerForPushNotications(_ token: Data, preferredLanguage: String? = nil, enabled: Bool = true) -> Promise<GeocoreUser> {
let tokenUpdated = self.updateCustomData(GeocoreUser.customDataKeyiOSPushToken, value: token.description)
let langUpdated = self.updateCustomData(GeocoreUser.customDataKeyiOSPushLanguage, value: preferredLanguage)
let enabledUpdated = self.updateCustomData(GeocoreUser.customDataKeyiOSPushEnabled, value: enabled.description)
if (tokenUpdated || langUpdated || enabledUpdated) {
return self.save()
} else {
return Promise { fulfill, reject in fulfill(self) }
}
}
open class func defaultUser() -> GeocoreUser {
let user = GeocoreUser()
user.id = GeocoreUser.defaultId()
user.name = GeocoreUser.defaultName()
user.email = GeocoreUser.defaultEmail()
user.password = GeocoreUser.defaultPassword()
return user
}
open class func get(_ id: String) -> Promise<GeocoreUser> {
return GeocoreUserQuery().with(id: id).get();
}
open func register() -> Promise<GeocoreUser> {
return GeocoreUserOperation().register(user: self)
}
open func save() -> Promise<GeocoreUser> {
return GeocoreObjectOperation().save(self, forService: "/users")
}
open func eventRelationships() -> Promise<[GeocoreUserEvent]> {
return GeocoreUserQuery().with(id: self.id!).eventRelationships()
}
open func eventRelationships(_ event: GeocoreEvent) -> Promise<[GeocoreUserEvent]> {
return GeocoreUserQuery().with(id: self.id!).eventRelationships(event)
}
open func placeRelationships() -> Promise<[GeocoreUserPlace]> {
return GeocoreUserQuery().with(id: self.id!).placeRelationships()
}
open func placeRelationships(_ place: GeocorePlace) -> Promise<[GeocoreUserPlace]> {
return GeocoreUserQuery().with(id: self.id!).placeRelationships(place)
}
open func itemRelationships() -> Promise<[GeocoreUserItem]> {
return GeocoreUserQuery().with(id: self.id!).itemRelationships()
}
open func tagOperation() -> GeocoreUserTagOperation {
return GeocoreUserTagOperation().with(id: self.id!)
}
}
open class GeocoreUserEventOperation: GeocoreRelationshipOperation {
private(set) open var relationshipType: GeocoreUserEventRelationshipType?
open func with(user: GeocoreUser) -> Self {
_ = super.with(object1Id: user.id!)
return self
}
open func with(event: GeocoreEvent) -> Self {
_ = super.with(object2Id: event.id!)
return self
}
open func with(relationshipType: GeocoreUserEventRelationshipType) -> Self {
self.relationshipType = relationshipType
return self
}
open override func buildPath(forService: String, withSubPath: String) -> String {
if let id1 = self.id1, let id2 = self.id2, let relationshipType = self.relationshipType {
return "\(forService)/\(id1)\(withSubPath)/\(id2)/\(relationshipType.rawValue)"
} else {
return super.buildPath(forService: forService, withSubPath: withSubPath)
}
}
open func save() -> Promise<GeocoreUserEvent> {
if self.id1 != nil && id2 != nil && self.relationshipType != nil {
if let customData = self.customData {
return Geocore.sharedInstance.promisedPOST(
buildPath(
forService: "/users",
withSubPath: "/events"),
parameters: nil,
body: customData.filter{ $0.value != nil }.map{ ($0, $1!) })
} else {
return Geocore.sharedInstance.promisedPOST(buildPath(forService: "/users", withSubPath: "/events"),
parameters: nil, body: [String: Any]())
}
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting ids & relationship type")) }
}
}
open func organize() -> Promise<GeocoreUserEvent> {
return with(relationshipType: .organizer).save()
}
open func perform() -> Promise<GeocoreUserEvent> {
return with(relationshipType: .performer).save()
}
open func participate() -> Promise<GeocoreUserEvent> {
return with(relationshipType: .participant).save()
}
open func attend() -> Promise<GeocoreUserEvent> {
return with(relationshipType: .attendant).save()
}
open func leaveAs(_ relationshipType: GeocoreUserEventRelationshipType) -> Promise<GeocoreUserEvent> {
self.relationshipType = relationshipType
if self.id1 != nil && id2 != nil && self.relationshipType != nil {
return Geocore.sharedInstance.promisedDELETE(buildPath(forService: "/users", withSubPath: "/events"))
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting ids & relationship type")) }
}
}
}
open class GeocoreUserEventQuery: GeocoreRelationshipQuery {
fileprivate(set) open var relationshipType: GeocoreUserEventRelationshipType?
open func withUser(_ user: GeocoreUser) -> Self {
_ = super.with(object1Id: user.id!)
return self
}
open func withEvent(_ event: GeocoreEvent) -> Self {
_ = super.with(object2Id: event.id!)
return self
}
open func with(relationshipType: GeocoreUserEventRelationshipType) -> Self {
self.relationshipType = relationshipType
return self
}
open override func buildPath(forService: String, withSubPath: String) -> String {
if let id1 = self.id1, let id2 = self.id2, let relationshipType = self.relationshipType {
return "\(forService)/\(id1)\(withSubPath)/\(id2)/\(relationshipType.rawValue)"
} else {
return super.buildPath(forService: forService, withSubPath: withSubPath)
}
}
open func get() -> Promise<GeocoreUserEvent> {
if self.id1 != nil && id2 != nil && self.relationshipType != nil {
return Geocore.sharedInstance.promisedGET(self.buildPath(forService: "/users", withSubPath: "/events"))
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting ids & relationship type")) }
}
}
open func all() -> Promise<[GeocoreUserEvent]> {
if self.id1 != nil {
return Geocore.sharedInstance.promisedGET(super.buildPath(forService: "/users", withSubPath: "/events"))
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting id")) }
}
}
open func organization() -> Promise<GeocoreUserEvent> {
return with(relationshipType: .organizer).get()
}
open func performance() -> Promise<GeocoreUserEvent> {
return with(relationshipType: .performer).get()
}
open func participation() -> Promise<GeocoreUserEvent> {
return with(relationshipType:.participant).get()
}
open func attendance() -> Promise<GeocoreUserEvent> {
return with(relationshipType: .attendant).get()
}
}
open class GeocoreUserEvent: GeocoreRelationship {
open var user: GeocoreUser?
open var event: GeocoreEvent?
open var relationshipType: GeocoreUserEventRelationshipType?
public required init(_ json: JSON) {
super.init(json)
if let pk = json["pk"].dictionary {
if let userDict = pk["user"] {
self.user = GeocoreUser(userDict)
}
if let eventDict = pk["event"] {
self.event = GeocoreEvent(eventDict)
}
if let relationshipType = pk["relationship"]?.string {
self.relationshipType = GeocoreUserEventRelationshipType(rawValue: relationshipType)!
}
}
}
open override func asDictionary() -> [String: Any] {
var dict = super.asDictionary()
var pk = [String: Any]()
if let user = self.user { pk["user"] = user.asDictionary() }
if let event = self.event { pk["event"] = event.asDictionary() }
if let relationshipType = self.relationshipType { pk["relationship"] = relationshipType.rawValue as AnyObject? }
dict["pk"] = pk as AnyObject?
return dict
}
}
open class GeocoreUserPlaceOperation: GeocoreRelationshipOperation {
private(set) open var relationshipType: GeocoreUserPlaceRelationshipType?
open func with(user: GeocoreUser) -> Self {
_ = super.with(object1Id: user.id!)
return self
}
open func with(place: GeocorePlace) -> Self {
_ = super.with(object2Id: place.id!)
return self
}
open func with(relationshipType: GeocoreUserPlaceRelationshipType) -> Self {
self.relationshipType = relationshipType
return self
}
open override func buildPath(forService: String, withSubPath: String) -> String {
if let id1 = self.id1, let id2 = self.id2, let relationshipType = self.relationshipType {
return "\(forService)/\(id1)\(withSubPath)/\(id2)/\(relationshipType.rawValue)"
} else {
return super.buildPath(forService: forService, withSubPath: withSubPath)
}
}
open func save() -> Promise<GeocoreUserPlace> {
if self.id1 != nil && id2 != nil && self.relationshipType != nil {
if let customData = self.customData {
return Geocore.sharedInstance.promisedPOST(buildPath(forService: "/users", withSubPath: "/places"),
parameters: nil, body: customData.filter{ $0.value != nil }.map{ ($0, $1!) })
} else {
return Geocore.sharedInstance.promisedPOST(buildPath(forService: "/users", withSubPath: "/places"),
parameters: nil, body: [String: AnyObject]())
}
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting ids & relationship type")) }
}
}
open func follow() -> Promise<GeocoreUserPlace> {
return with(relationshipType: .follower).save()
}
open func leaveAs(_ relationshipType: GeocoreUserPlaceRelationshipType) -> Promise<GeocoreUserPlace> {
_ = self.with(relationshipType: relationshipType)
if self.id1 != nil && id2 != nil && self.relationshipType != nil {
return Geocore.sharedInstance.promisedDELETE(buildPath(forService: "/users", withSubPath: "/places"))
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting ids & relationship type")) }
}
}
open func unfollow() -> Promise<GeocoreUserPlace> {
return leaveAs(.follower)
}
}
open class GeocoreUserPlaceQuery: GeocoreRelationshipQuery {
fileprivate(set) open var relationshipType: GeocoreUserPlaceRelationshipType?
open func with(user: GeocoreUser) -> Self {
_ = super.with(object1Id: user.id!)
return self
}
open func with(place: GeocorePlace) -> Self {
_ = super.with(object2Id: place.id!)
return self
}
open func with(relationshipType: GeocoreUserPlaceRelationshipType) -> Self {
self.relationshipType = relationshipType
return self
}
open override func buildPath(forService: String, withSubPath: String) -> String {
if let id1 = self.id1, let id2 = self.id2, let relationshipType = self.relationshipType {
return "\(forService)/\(id1)\(withSubPath)/\(id2)/\(relationshipType.rawValue)"
} else {
return super.buildPath(forService: forService, withSubPath: withSubPath)
}
}
open func get() -> Promise<GeocoreUserPlace> {
if self.id1 != nil && id2 != nil && self.relationshipType != nil {
return Geocore.sharedInstance.promisedGET(self.buildPath(forService: "/users", withSubPath: "/places"))
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting ids & relationship type")) }
}
}
open func all() -> Promise<[GeocoreUserPlace]> {
if self.id1 != nil {
var params = buildQueryParameters()
params["output_format"] = "json.relationship"
return Geocore.sharedInstance.promisedGET(super.buildPath(forService: "/users", withSubPath: "/places"), parameters: params)
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting id")) }
}
}
open func asFollower() -> Promise<GeocoreUserPlace> {
return with(relationshipType: .follower).get()
}
}
open class GeocoreUserPlace: GeocoreRelationship {
open var user: GeocoreUser?
open var place: GeocorePlace?
open var relationshipType: GeocoreUserPlaceRelationshipType?
public required init(_ json: JSON) {
super.init(json)
if let pk = json["pk"].dictionary {
if let userDict = pk["user"] {
self.user = GeocoreUser(userDict)
}
if let placeDict = pk["place"] {
self.place = GeocorePlace(placeDict)
}
if let relationshipType = pk["relationship"]?.string {
self.relationshipType = GeocoreUserPlaceRelationshipType(rawValue: relationshipType)!
}
}
}
open override func asDictionary() -> [String: Any] {
var dict = super.asDictionary()
var pk = [String: Any]()
if let user = self.user { pk["user"] = user.asDictionary() }
if let place = self.place { pk["place"] = place.asDictionary() }
if let relationshipType = self.relationshipType { pk["relationship"] = relationshipType.rawValue as AnyObject? }
dict["pk"] = pk as AnyObject?
return dict
}
}
open class GeocoreUserItemOperation: GeocoreRelationshipOperation {
open func with(_ user: GeocoreUser) -> Self {
_ = super.with(object1Id: user.id!)
return self
}
open func with(_ item: GeocoreItem) -> Self {
_ = super.with(object2Id: item.id!)
return self
}
open func adjustAmount(_ amount: Int) -> Promise<GeocoreUserItem> {
if let id1 = self.id1, let id2 = self.id2 {
var sign = "-"
if amount > 0 {
sign = "+"
}
return Geocore.sharedInstance.promisedPOST("/users/\(id1)/items/\(id2)/amount/\(sign)\(abs(amount))")
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting ids")) }
}
}
}
open class GeocoreUserItemQuery: GeocoreRelationshipQuery {
open func with(user: GeocoreUser) -> Self {
_ = super.with(object1Id: user.id!)
return self
}
open func with(item: GeocoreItem) -> Self {
_ = super.with(object2Id: item.id!)
return self
}
open func all() -> Promise<[GeocoreUserItem]> {
if self.id1 != nil {
return Geocore.sharedInstance.promisedGET(super.buildPath(forService: "/users", withSubPath: "/items"), parameters: ["output_format": "json.relationship"])
} else {
return Promise { fulfill, reject in reject(GeocoreError.invalidParameter(message: "Expecting id")) }
}
}
}
open class GeocoreUserItem: GeocoreRelationship {
open var user: GeocoreUser?
open var item: GeocoreItem?
open var createTime: Date?
open var amount: Int64?
open var orderNumber: Int?
public required init(_ json: JSON) {
super.init(json)
if let pk = json["pk"].dictionary {
if let userDict = pk["user"] {
self.user = GeocoreUser(userDict)
}
if let itemDict = pk["item"] {
self.item = GeocoreItem(itemDict)
}
if let createTimeString = pk["createTime"] {
self.createTime = Date.fromGeocoreFormattedString(createTimeString.string)
}
}
self.amount = json["amount"].int64
self.orderNumber = json["orderNumber"].int
}
open override func asDictionary() -> [String: Any] {
var dict = super.asDictionary()
var pk = [String: Any]()
if let user = self.user { pk["user"] = user.asDictionary() }
if let item = self.item { pk["item"] = item.asDictionary() }
if let createTime = self.createTime { pk["createTime"] = createTime }
dict["pk"] = pk
if let amount = self.amount { dict["amount"] = amount }
if let orderNumber = self.orderNumber { dict["orderNumber"] = orderNumber }
return dict
}
}
| apache-2.0 | 228416b33b433a436a1c2c1288505b83 | 34.672662 | 167 | 0.611072 | 4.405598 | false | false | false | false |
klundberg/sweep | Sources/GriftKit/GraphStructure.swift | 1 | 2309 | import Foundation
import SourceKittenFramework
import Graphviz
private func filesInDirectory(at path: String, using fileManager: FileManager = .default) throws -> [String] {
guard let enumerator = fileManager.enumerator(at: URL(fileURLWithPath: path), includingPropertiesForKeys: nil) else {
return [] // TODO: throw error
}
return enumerator.flatMap({
guard let url = $0 as? URL,
!url.pathComponents.contains(".build"),
!url.pathComponents.contains("Carthage"),
url.pathExtension == "swift" else {
return nil
}
return url.relativePath
})
// let contents = try fileManager.contentsOfDirectory(atPath: path)
//
// return contents.flatMap({ (filename: String) -> String? in
// guard filename.hasSuffix(".swift") else {
// return nil
// }
//
// return (path as NSString).appendingPathComponent(filename)
//
// })
}
public func syntaxMaps(for code: String) throws -> [SyntaxMap] {
return try [SyntaxMap(file: File(contents: code))]
}
public func docs(for code: String) -> [SwiftDocs] {
return SwiftDocs(file: File(contents: code), arguments: []).map({ [$0] }) ?? []
}
public func structures(at path: String, using fileManager: FileManager = .default) throws -> [Structure] {
let filePaths = try filesInDirectory(at: path, using: fileManager)
return try filePaths.flatMap({ try structure(forFile: $0) })
}
func structures(for code: String) throws -> [Structure] {
return try [Structure(file: File(contents: code))]
}
public func structure(forFile path: String) throws -> Structure? {
guard let file = File(path: path) else {
return nil
}
return try Structure(file: file)
}
extension Dictionary {
subscript (keyEnum: SwiftDocKey) -> Value? {
guard let key = keyEnum.rawValue as? Key else {
return nil
}
return self[key]
}
}
func kindIsEnclosingType(kind: SourceKitRepresentable?) -> Bool {
guard let kind = kind as? String,
let declarationKind = SwiftDeclarationKind(rawValue: kind) else {
return false
}
switch declarationKind {
case .`struct`, .`class`, .`enum`, .`protocol`:
return true
default:
return false
}
}
| mit | d01c53aedee15695eb33f8ad87ea6e00 | 27.8625 | 121 | 0.637505 | 4.244485 | false | false | false | false |
renzifeng/ZFZhiHuDaily | ZFZhiHuDaily/Other/Lib/CyclePictureView/AuxiliaryModels.swift | 1 | 4879 | //
// AuxiliaryModels.swift
// CyclePictureView
//
// Created by wl on 15/11/8.
// Copyright © 2015年 wl. All rights reserved.
//
import UIKit
//========================================================
// MARK: - 图片类型处理
//========================================================
enum ImageSource {
case Local(name: String)
case Network(urlStr: String)
}
enum ImageType {
case Local
case Network
}
struct ImageBox {
var imageType: ImageType
var imageArray: [ImageSource]
init(imageType: ImageType, imageArray: [String]) {
self.imageType = imageType
self.imageArray = []
switch imageType {
case .Local:
for str in imageArray {
self.imageArray.append(ImageSource.Local(name: str))
}
case .Network:
for str in imageArray {
self.imageArray.append(ImageSource.Network(urlStr: str))
}
}
}
subscript (index: Int) -> ImageSource {
get {
return self.imageArray[index]
}
}
}
//========================================================
// MARK: - PageControl对齐协议
//========================================================
enum PageControlAliment {
case CenterBottom
case LeftBottom
case RightBottom
}
protocol PageControlAlimentProtocol: class{
var pageControlAliment: PageControlAliment {get set}
func AdjustPageControlPlace(pageControl: UIPageControl)
}
extension PageControlAlimentProtocol where Self : UIView {
func AdjustPageControlPlace(pageControl: UIPageControl) {
if !pageControl.hidden {
switch self.pageControlAliment {
case .CenterBottom:
let pageW:CGFloat = CGFloat(pageControl.numberOfPages * 15)
let pageH:CGFloat = 20
let pageX = self.center.x - 0.5 * pageW
let pageY = self.bounds.height - pageH
pageControl.frame = CGRectMake(pageX, pageY, pageW, pageH)
case .LeftBottom:
let pageW:CGFloat = CGFloat(pageControl.numberOfPages * 15)
let pageH:CGFloat = 20
let pageX = self.bounds.origin.x
let pageY = self.bounds.height - pageH
pageControl.frame = CGRectMake(pageX, pageY, pageW, pageH)
case .RightBottom:
let pageW:CGFloat = CGFloat(pageControl.numberOfPages * 15)
let pageH:CGFloat = 20
let pageX = self.bounds.width - pageW
let pageY = self.bounds.height - pageH
pageControl.frame = CGRectMake(pageX, pageY, pageW, pageH)
}
}
}
}
//========================================================
// MARK: - 无限滚动协议
//========================================================
protocol EndlessCycleProtocol: class{
/// 是否开启自动滚动
var autoScroll: Bool {get set}
/// 开启自动滚动后,自动翻页的时间
var timeInterval: Double {get set}
/// 用于控制自动滚动的定时器
var timer: NSTimer? {get set}
/// 是否开启无限滚动模式
var needEndlessScroll: Bool {get set}
/// 开启无限滚动模式后,cell需要增加的倍数
var imageTimes: Int {get}
/// 开启无限滚动模式后,真实的cell数量
var actualItemCount: Int {get set}
/**
设置定时器,用于控制自动翻页
*/
func setupTimer(userInfo: AnyObject?)
/**
在无限滚动模式中,显示的第一页其实是最中间的那一个cell
*/
func showFirstImagePageInCollectionView(collectionView: UICollectionView)
}
extension EndlessCycleProtocol where Self : UIView {
func autoChangePicture(collectionView: UICollectionView) {
guard actualItemCount != 0 else {
return
}
let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let currentIndex = Int(collectionView.contentOffset.x / flowLayout.itemSize.width)
let nextIndex = currentIndex + 1
if nextIndex >= actualItemCount {
showFirstImagePageInCollectionView(collectionView)
}else {
collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: nextIndex, inSection: 0), atScrollPosition: .None, animated: true)
}
}
func showFirstImagePageInCollectionView(collectionView: UICollectionView) {
guard actualItemCount != 0 else {
return
}
var newIndex = 0
if needEndlessScroll {
newIndex = actualItemCount / 2
}
collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: newIndex, inSection: 0), atScrollPosition: .None, animated: false)
}
}
| apache-2.0 | 399377b63906eb20830b31423c269ef4 | 28.780645 | 138 | 0.565425 | 4.793354 | false | false | false | false |
voloshynslavik/MVx-Patterns-In-Swift | MVX Patterns In Swift/Patterns/MVVM/ViewModel.swift | 1 | 2708 | //
// ModelView.swift
// MVX Patterns In Swift
//
// Created by Yaroslav Voloshyn on 17/07/2017.
//
import Foundation
final class ViewModel: NSObject {
weak var delegate: ViewModelDelegate?
fileprivate let picsumPhotos = PicsumPhotosManager()
fileprivate var lastPageIndex: Int?
fileprivate var photos: [(PicsumPhoto, Data?)] = []
fileprivate var isLoading = false {
didSet {
self.delegate?.didLoadingStateChanged(in: self, from: oldValue, to: isLoading)
}
}
var photosCount: Int {
return photos.count
}
func getPhotoData(for index: Int, width: Int, height: Int) -> Data? {
guard let data = photos[index].1 else {
startLoadPhoto(for: index, width: width, height: height)
return nil
}
return data
}
func getPhotoAuthor(for index: Int) -> String {
return photos[index].0.author
}
}
// MARK: - Load items
extension ViewModel {
func loadMoreItems() {
guard !isLoading else {
return
}
var pageIndex = 1
if let lastPageIndex = lastPageIndex {
pageIndex = lastPageIndex + 1
}
loadItems(with: pageIndex)
}
private func loadItems(with pageIndex: Int) {
isLoading = true
picsumPhotos.getPhotos(pageIndex) { [weak self] (photos, error) in
defer {
self?.isLoading = false
}
guard let sself = self else {
return
}
sself.lastPageIndex = pageIndex
photos?.forEach {
sself.photos.append(($0, nil))
}
sself.delegate?.didUpdatedData(in: sself)
}
}
}
// MARK: - Load Photo
extension ViewModel {
func stopLoadPhoto(for index: Int, width: Int, height: Int) {
let url = photos[index].0.getResizedImageURL(width: width, height: height)
DataLoader.shared.stopDownload(with: url)
}
func startLoadPhoto(for index: Int, width: Int, height: Int) {
let url = photos[index].0.getResizedImageURL(width: width, height: height)
DataLoader.shared.downloadData(with: url) { [weak self] (data) in
guard let sself = self else {
return
}
sself.photos[index].1 = data
sself.delegate?.didDownloadPhoto(in: sself, with: index)
}
}
}
protocol ViewModelDelegate: class {
func didLoadingStateChanged(in viewModel: ViewModel, from oldState: Bool, to newState:Bool)
func didUpdatedData(in viewModel: ViewModel)
func didDownloadPhoto(in viewMode: ViewModel, with index: Int)
}
| mit | 118d8d678530489e0948eedceae72d55 | 24.790476 | 95 | 0.589734 | 4.360709 | false | false | false | false |
BrisyIOS/zhangxuWeiBo | zhangxuWeiBo/zhangxuWeiBo/classes/Compose/View/ZXEmotion.swift | 1 | 1895 | //
// ZXEmotion.swift
// zhangxuWeiBo
//
// Created by zhangxu on 16/6/25.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
class ZXEmotion: NSObject , NSCoding {
// 繁体汉字
var cht : String?;
// 简体汉字
var chs : String?;
// 静态图名
var png : String?;
// emoji 编码
var code : String? {
didSet {
if code == nil {
return;
}
self.emoji = NSString.emojiWithStringCode(code!);
}
};
// 表情的存放目录和文件
var directory : String?;
// emoji表情的字符
var emoji : String?;
override init() {
super.init();
}
required init?(coder aDecoder: NSCoder) {
self.cht = aDecoder.decodeObjectForKey("cht") as? String;
self.chs = aDecoder.decodeObjectForKey("chs") as? String;
self.png = aDecoder.decodeObjectForKey("png") as? String;
self.code = aDecoder.decodeObjectForKey("code") as? String;
self.directory = aDecoder.decodeObjectForKey("directory") as? String;
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(cht, forKey: "cht");
aCoder.encodeObject(chs, forKey: "chs");
aCoder.encodeObject(png, forKey: "png");
aCoder.encodeObject(code, forKey: "code");
aCoder.encodeObject(directory, forKey: "directory");
}
func isEqual(otherEmotion : ZXEmotion?) -> Bool? {
if (self.code != nil) {
// emoji表情
return self.code == otherEmotion?.code;
} else {
// 图片表情
return self.png == otherEmotion?.png && self.chs == otherEmotion?.chs && self.cht == otherEmotion?.cht;
}
}
}
| apache-2.0 | 8d7d79ff632dcdba1a047f5e13276953 | 22.662338 | 115 | 0.525796 | 4.369305 | false | false | false | false |
JNDisrupter/JNMultipleImages | Example/Example/MultipleImagesTableViewController.swift | 1 | 1297 | //
// MultipleImagesTableViewController.swift
// Example
//
// Created by Mohammad Nabulsi on 11/6/17.
// Copyright © 2017 JNDisrupter. All rights reserved.
//
import UIKit
class MultipleImagesTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Set footer view
self.tableView.tableFooterView = UIView()
// Set navigation item back button
self.navigationItem.backBarButtonItem = UIBarButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "ShowExample", sender: indexPath.row)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? ViewController , segue.identifier == "ShowExample" , let index = sender as? Int {
destination.itemIndex = index
}
}
}
| mit | 3ea0fe0860de8be417e73fbe170818e5 | 27.8 | 132 | 0.673611 | 5.12253 | false | false | false | false |
iOkay/MiaoWuWu | Pods/Material/Sources/iOS/SnackbarController.swift | 1 | 7464 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* 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
@objc(SnackbarControllerDelegate)
public protocol SnackbarControllerDelegate {
/**
A delegation method that is executed when a Snackbar will show.
- Parameter snackbarController: A SnackbarController.
- Parameter snackbar: A Snackbar.
*/
@objc
optional func snackbarController(snackbarController: SnackbarController, willShow snackbar: Snackbar)
/**
A delegation method that is executed when a Snackbar did show.
- Parameter snackbarController: A SnackbarController.
- Parameter snackbar: A Snackbar.
*/
@objc
optional func snackbarController(snackbarController: SnackbarController, didShow snackbar: Snackbar)
/**
A delegation method that is executed when a Snackbar will hide.
- Parameter snackbarController: A SnackbarController.
- Parameter snackbar: A Snackbar.
*/
@objc
optional func snackbarController(snackbarController: SnackbarController, willHide snackbar: Snackbar)
/**
A delegation method that is executed when a Snackbar did hide.
- Parameter snackbarController: A SnackbarController.
- Parameter snackbar: A Snackbar.
*/
@objc
optional func snackbarController(snackbarController: SnackbarController, didHide snackbar: Snackbar)
}
@objc(SnackbarAlignment)
public enum SnackbarAlignment: Int {
case top
case bottom
}
extension UIViewController {
/**
A convenience property that provides access to the SnackbarController.
This is the recommended method of accessing the SnackbarController
through child UIViewControllers.
*/
public var snackbarController: SnackbarController? {
var viewController: UIViewController? = self
while nil != viewController {
if viewController is SnackbarController {
return viewController as? SnackbarController
}
viewController = viewController?.parent
}
return nil
}
}
open class SnackbarController: RootController {
/// Reference to the Snackbar.
open private(set) lazy var snackbar: Snackbar = Snackbar()
/// A boolean indicating if the Snacbar is animating.
open internal(set) var isAnimating = false
/// Delegation handler.
open weak var delegate: SnackbarControllerDelegate?
/// Snackbar alignment setting.
open var snackbarAlignment = SnackbarAlignment.bottom
/**
Animates to a SnackbarStatus.
- Parameter status: A SnackbarStatus enum value.
*/
@discardableResult
open func animate(snackbar status: SnackbarStatus, delay: TimeInterval = 0, animations: ((Snackbar) -> Void)? = nil, completion: ((Snackbar) -> Void)? = nil) -> AnimationDelayCancelBlock? {
return Animation.delay(time: delay) { [weak self, status = status, animations = animations, completion = completion] in
guard let s = self else {
return
}
if .visible == status {
s.delegate?.snackbarController?(snackbarController: s, willShow: s.snackbar)
} else {
s.delegate?.snackbarController?(snackbarController: s, willHide: s.snackbar)
}
s.isAnimating = true
s.isUserInteractionEnabled = false
UIView.animate(withDuration: 0.25, animations: { [weak self, status = status, animations = animations] in
guard let s = self else {
return
}
s.layoutSnackbar(status: status)
animations?(s.snackbar)
}) { [weak self, status = status, completion = completion] _ in
guard let s = self else {
return
}
s.isAnimating = false
s.isUserInteractionEnabled = true
s.snackbar.status = status
s.layoutSubviews()
if .visible == status {
s.delegate?.snackbarController?(snackbarController: s, didShow: s.snackbar)
} else {
s.delegate?.snackbarController?(snackbarController: s, didHide: s.snackbar)
}
completion?(s.snackbar)
}
}
}
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
reload()
}
open override func layoutSubviews() {
super.layoutSubviews()
guard !isAnimating else {
return
}
reload()
}
/// Reloads the view.
open func reload() {
snackbar.width = view.width
layoutSnackbar(status: snackbar.status)
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open override func prepare() {
super.prepare()
prepareSnackbar()
}
/// Prepares the snackbar.
private func prepareSnackbar() {
snackbar.zPosition = 10000
view.addSubview(snackbar)
}
/**
Lays out the Snackbar.
- Parameter status: A SnackbarStatus enum value.
*/
private func layoutSnackbar(status: SnackbarStatus) {
if .bottom == snackbarAlignment {
snackbar.y = .visible == status ? view.height - snackbar.height : view.height
} else {
snackbar.y = .visible == status ? 0 : -snackbar.height
}
}
}
| gpl-3.0 | 9c5cbd1e6e5e798e370f05a338fde78a | 35.768473 | 193 | 0.64724 | 5.271186 | false | false | false | false |
namdq1969/DownloadManager | DownloadManager/Classes/DownloadTask.swift | 1 | 2588 | //
// DownloadTask.swift
// Pods
//
// Created by Nam Dam on 08/28/2016.
// Copyright © 2016 Nam dam. All rights reserved.
//
import UIKit
internal class DownloadTask: NSObject {
func requestUrl(urlString: String, requestId: Int?) -> DownloadRequest<AnyObject>? {
let serviceRequest = DownloadRequest<AnyObject>()
FireRequest().request(urlString, requestId: requestId).onResult = { (data, response, error) in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode >= 200 && httpResponse.statusCode < 300 {
serviceRequest.onSuccess?(data!)
} else {
serviceRequest.onFailure?(status: "Unknown error", code: -9999)
}
} else {
serviceRequest.onFailure?(status: "Unknown error", code: -9999)
}
}
return serviceRequest
}
func cancelRequest(requestId: Int) {
FireRequest().cancel(requestId)
}
func cacheInMemory(coreObject: CoreObject) {
if DownloadTaskManager.manager.cacheObjects {
DownloadTaskManager.manager.cacheObject(coreObject)
}
}
func parseImage(urlString: String, data: NSData) -> CoreObject? {
if let image = UIImage(data: data) {
let value: AnyObject = image
let coreObject = CoreObject(urlString: urlString, value: value)
cacheInMemory(coreObject)
return coreObject
}
return nil
}
func parseJson(urlString: String, data: NSData) -> CoreObject? {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
if let result = json as? [String : AnyObject] {
let value: AnyObject = result
let coreObject = CoreObject(urlString: urlString, value: value)
cacheInMemory(coreObject)
return coreObject
}
return nil
} catch let parseError {
print("parse error \(parseError)")
return nil
}
}
func parseXml(urlString: String, data: NSData, delegate: NSXMLParserDelegate?) -> CoreObject? {
let parser = FireParser(data: data)
let success = parser.parse(delegate)
if success {
let value: AnyObject = parser.result!
let coreObject = CoreObject(urlString: urlString, value: value)
cacheInMemory(coreObject)
return coreObject
} else {
return nil
}
}
} | mit | 3e3b813031a5e9ccaa6576d661680a79 | 32.179487 | 102 | 0.584461 | 4.937023 | false | false | false | false |
Q42/pomotv-app | PomoTv/AppDelegate.swift | 1 | 2739 | //
// AppDelegate.swift
// PomoTv
//
// Created by Tom Lokhorst on 2015-12-20.
// Copyright © 2015 pomo.tv. All rights reserved.
//
import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Setup default colors
UINavigationBar.appearance().barTintColor = UIColor.darkTintColor()
UINavigationBar.appearance().tintColor = UIColor.lightTintColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
// TODO: Figure out how to set color of unselected items
UITabBar.appearance().barTintColor = UIColor.darkTintColor()
UITabBar.appearance().tintColor = UIColor.lightTintColor()
UITabBar.appearance().translucent = false
// Setup audio session
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
}
catch {
print("¯\\_(ツ)_/¯: \(error)")
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 028aed2067e6aae9e552534fec1804e4 | 40.424242 | 281 | 0.761522 | 5.371316 | false | false | false | false |
e78l/swift-corelibs-foundation | Foundation/JSONSerialization.swift | 2 | 41113 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
extension JSONSerialization {
public struct ReadingOptions : OptionSet {
public let rawValue: UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let mutableContainers = ReadingOptions(rawValue: 1 << 0)
public static let mutableLeaves = ReadingOptions(rawValue: 1 << 1)
public static let allowFragments = ReadingOptions(rawValue: 1 << 2)
}
public struct WritingOptions : OptionSet {
public let rawValue: UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let prettyPrinted = WritingOptions(rawValue: 1 << 0)
public static let sortedKeys = WritingOptions(rawValue: 1 << 1)
}
}
/* A class for converting JSON to Foundation/Swift objects and converting Foundation/Swift objects to JSON.
An object that may be converted to JSON must have the following properties:
- Top level object is a `Swift.Array` or `Swift.Dictionary`
- All objects are `Swift.String`, `Foundation.NSNumber`, `Swift.Array`, `Swift.Dictionary`,
or `Foundation.NSNull`
- All dictionary keys are `Swift.String`s
- `NSNumber`s are not NaN or infinity
*/
open class JSONSerialization : NSObject {
/* Determines whether the given object can be converted to JSON.
Other rules may apply. Calling this method or attempting a conversion are the definitive ways
to tell if a given object can be converted to JSON data.
- parameter obj: The object to test.
- returns: `true` if `obj` can be converted to JSON, otherwise `false`.
*/
open class func isValidJSONObject(_ obj: Any) -> Bool {
// TODO: - revisit this once bridging story gets fully figured out
func isValidJSONObjectInternal(_ obj: Any?) -> Bool {
// Emulate the SE-0140 behavior bridging behavior for nils
guard let obj = obj else {
return true
}
if !(obj is _NSNumberCastingWithoutBridging) {
if obj is String || obj is NSNull || obj is Int || obj is Bool || obj is UInt ||
obj is Int8 || obj is Int16 || obj is Int32 || obj is Int64 ||
obj is UInt8 || obj is UInt16 || obj is UInt32 || obj is UInt64 {
return true
}
}
// object is a Double and is not NaN or infinity
if let number = obj as? Double {
return number.isFinite
}
// object is a Float and is not NaN or infinity
if let number = obj as? Float {
return number.isFinite
}
if let number = obj as? Decimal {
return number.isFinite
}
// object is Swift.Array
if let array = obj as? [Any?] {
for element in array {
guard isValidJSONObjectInternal(element) else {
return false
}
}
return true
}
// object is Swift.Dictionary
if let dictionary = obj as? [String: Any?] {
for (_, value) in dictionary {
guard isValidJSONObjectInternal(value) else {
return false
}
}
return true
}
// object is NSNumber and is not NaN or infinity
// For better performance, this (most expensive) test should be last.
if let number = __SwiftValue.store(obj) as? NSNumber {
if CFNumberIsFloatType(number._cfObject) {
let dv = number.doubleValue
let invalid = dv.isInfinite || dv.isNaN
return !invalid
} else {
return true
}
}
// invalid object
return false
}
// top level object must be an Swift.Array or Swift.Dictionary
guard obj is [Any?] || obj is [String: Any?] else {
return false
}
return isValidJSONObjectInternal(obj)
}
/* Generate JSON data from a Foundation object. If the object will not produce valid JSON then an exception will be thrown. Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated. If an error occurs, the error parameter will be set and the return value will be nil. The resulting data is a encoded in UTF-8.
*/
internal class func _data(withJSONObject value: Any, options opt: WritingOptions, stream: Bool) throws -> Data {
var jsonStr = String()
var writer = JSONWriter(
pretty: opt.contains(.prettyPrinted),
sortedKeys: opt.contains(.sortedKeys),
writer: { (str: String?) in
if let str = str {
jsonStr.append(str)
}
}
)
if let container = value as? NSArray {
try writer.serializeJSON(container._bridgeToSwift())
} else if let container = value as? NSDictionary {
try writer.serializeJSON(container._bridgeToSwift())
} else if let container = value as? Array<Any> {
try writer.serializeJSON(container)
} else if let container = value as? Dictionary<AnyHashable, Any> {
try writer.serializeJSON(container)
} else {
fatalError("Top-level object was not NSArray or NSDictionary") // This is a fatal error in objective-c too (it is an NSInvalidArgumentException)
}
let count = jsonStr.utf8.count
return jsonStr.withCString {
Data(bytes: $0, count: count)
}
}
open class func data(withJSONObject value: Any, options opt: WritingOptions = []) throws -> Data {
return try _data(withJSONObject: value, options: opt, stream: false)
}
/* Create a Foundation object from JSON data. Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary. Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries. Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects. If an error occurs during the parse, then the error parameter will be set and the result will be nil.
The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.
*/
open class func jsonObject(with data: Data, options opt: ReadingOptions = []) throws -> Any {
return try data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Any in
let encoding: String.Encoding
let buffer: UnsafeBufferPointer<UInt8>
if let detected = parseBOM(bytes, length: data.count) {
encoding = detected.encoding
buffer = UnsafeBufferPointer(start: bytes.advanced(by: detected.skipLength), count: data.count - detected.skipLength)
}
else {
encoding = detectEncoding(bytes, data.count)
buffer = UnsafeBufferPointer(start: bytes, count: data.count)
}
let source = JSONReader.UnicodeSource(buffer: buffer, encoding: encoding)
let reader = JSONReader(source: source)
if let (object, _) = try reader.parseObject(0, options: opt) {
return object
}
else if let (array, _) = try reader.parseArray(0, options: opt) {
return array
}
else if opt.contains(.allowFragments), let (value, _) = try reader.parseValue(0, options: opt) {
return value
}
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "JSON text did not start with array or object and option to allow fragments not set."
])
}
}
/* Write JSON data into a stream. The stream should be opened and configured. The return value is the number of bytes written to the stream, or 0 on error. All other behavior of this method is the same as the dataWithJSONObject:options:error: method.
*/
open class func writeJSONObject(_ obj: Any, toStream stream: OutputStream, options opt: WritingOptions) throws -> Int {
let jsonData = try _data(withJSONObject: obj, options: opt, stream: true)
let count = jsonData.count
return jsonData.withUnsafeBytes { (bytePtr: UnsafePointer<UInt8>) -> Int in
let res: Int = stream.write(bytePtr, maxLength: count)
/// TODO: If the result here is negative the error should be obtained from the stream to propagate as a throw
return res
}
}
/* Create a JSON object from JSON data stream. The stream should be opened and configured. All other behavior of this method is the same as the JSONObjectWithData:options:error: method.
*/
open class func jsonObject(with stream: InputStream, options opt: ReadingOptions = []) throws -> Any {
var data = Data()
guard stream.streamStatus == .open || stream.streamStatus == .reading else {
fatalError("Stream is not available for reading")
}
repeat {
var buffer = [UInt8](repeating: 0, count: 1024)
var bytesRead: Int = 0
bytesRead = stream.read(&buffer, maxLength: buffer.count)
if bytesRead < 0 {
throw stream.streamError!
} else {
data.append(&buffer, count: bytesRead)
}
} while stream.hasBytesAvailable
return try jsonObject(with: data, options: opt)
}
}
//MARK: - Encoding Detection
internal extension JSONSerialization {
/// Detect the encoding format of the NSData contents
class func detectEncoding(_ bytes: UnsafePointer<UInt8>, _ length: Int) -> String.Encoding {
if length >= 4 {
switch (bytes[0], bytes[1], bytes[2], bytes[3]) {
case (0, 0, 0, _):
return .utf32BigEndian
case (_, 0, 0, 0):
return .utf32LittleEndian
case (0, _, 0, _):
return .utf16BigEndian
case (_, 0, _, 0):
return .utf16LittleEndian
default:
break
}
}
else if length >= 2 {
switch (bytes[0], bytes[1]) {
case (0, _):
return .utf16BigEndian
case (_, 0):
return .utf16LittleEndian
default:
break
}
}
return .utf8
}
static func parseBOM(_ bytes: UnsafePointer<UInt8>, length: Int) -> (encoding: String.Encoding, skipLength: Int)? {
if length >= 2 {
switch (bytes[0], bytes[1]) {
case (0xEF, 0xBB):
if length >= 3 && bytes[2] == 0xBF {
return (.utf8, 3)
}
case (0x00, 0x00):
if length >= 4 && bytes[2] == 0xFE && bytes[3] == 0xFF {
return (.utf32BigEndian, 4)
}
case (0xFF, 0xFE):
if length >= 4 && bytes[2] == 0 && bytes[3] == 0 {
return (.utf32LittleEndian, 4)
}
return (.utf16LittleEndian, 2)
case (0xFE, 0xFF):
return (.utf16BigEndian, 2)
default:
break
}
}
return nil
}
}
//MARK: - JSONSerializer
private struct JSONWriter {
var indent = 0
let pretty: Bool
let sortedKeys: Bool
let writer: (String?) -> Void
init(pretty: Bool = false, sortedKeys: Bool = false, writer: @escaping (String?) -> Void) {
self.pretty = pretty
self.sortedKeys = sortedKeys
self.writer = writer
}
mutating func serializeJSON(_ object: Any?) throws {
var toSerialize = object
if let number = toSerialize as? _NSNumberCastingWithoutBridging {
toSerialize = number._swiftValueOfOptimalType
}
guard let obj = toSerialize else {
try serializeNull()
return
}
// For better performance, the most expensive conditions to evaluate should be last.
switch (obj) {
case let str as String:
try serializeString(str)
case let boolValue as Bool:
writer(boolValue.description)
case let num as Int:
writer(num.description)
case let num as Int8:
writer(num.description)
case let num as Int16:
writer(num.description)
case let num as Int32:
writer(num.description)
case let num as Int64:
writer(num.description)
case let num as UInt:
writer(num.description)
case let num as UInt8:
writer(num.description)
case let num as UInt16:
writer(num.description)
case let num as UInt32:
writer(num.description)
case let num as UInt64:
writer(num.description)
case let array as Array<Any?>:
try serializeArray(array)
case let dict as Dictionary<AnyHashable, Any?>:
try serializeDictionary(dict)
case let num as Float:
try serializeFloat(num)
case let num as Double:
try serializeFloat(num)
case let num as Decimal:
writer(num.description)
case let num as NSDecimalNumber:
writer(num.description)
case is NSNull:
try serializeNull()
case _ where __SwiftValue.store(obj) is NSNumber:
let num = __SwiftValue.store(obj) as! NSNumber
writer(num.description)
default:
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "Invalid object cannot be serialized"])
}
}
func serializeString(_ str: String) throws {
writer("\"")
for scalar in str.unicodeScalars {
switch scalar {
case "\"":
writer("\\\"") // U+0022 quotation mark
case "\\":
writer("\\\\") // U+005C reverse solidus
case "/":
writer("\\/") // U+002F solidus
case "\u{8}":
writer("\\b") // U+0008 backspace
case "\u{c}":
writer("\\f") // U+000C form feed
case "\n":
writer("\\n") // U+000A line feed
case "\r":
writer("\\r") // U+000D carriage return
case "\t":
writer("\\t") // U+0009 tab
case "\u{0}"..."\u{f}":
writer("\\u000\(String(scalar.value, radix: 16))") // U+0000 to U+000F
case "\u{10}"..."\u{1f}":
writer("\\u00\(String(scalar.value, radix: 16))") // U+0010 to U+001F
default:
writer(String(scalar))
}
}
writer("\"")
}
private func serializeFloat<T: FloatingPoint & LosslessStringConvertible>(_ num: T) throws {
guard num.isFinite else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "Invalid number value (\(num)) in JSON write"])
}
var str = num.description
if str.hasSuffix(".0") {
str.removeLast(2)
}
writer(str)
}
mutating func serializeNumber(_ num: NSNumber) throws {
if CFNumberIsFloatType(num._cfObject) {
try serializeFloat(num.doubleValue)
} else {
switch num._cfTypeID {
case CFBooleanGetTypeID():
writer(num.boolValue.description)
default:
writer(num.stringValue)
}
}
}
mutating func serializeArray(_ array: [Any?]) throws {
writer("[")
if pretty {
writer("\n")
incAndWriteIndent()
}
var first = true
for elem in array {
if first {
first = false
} else if pretty {
writer(",\n")
writeIndent()
} else {
writer(",")
}
try serializeJSON(elem)
}
if pretty {
writer("\n")
decAndWriteIndent()
}
writer("]")
}
mutating func serializeDictionary(_ dict: Dictionary<AnyHashable, Any?>) throws {
writer("{")
if pretty {
writer("\n")
incAndWriteIndent()
}
var first = true
func serializeDictionaryElement(key: AnyHashable, value: Any?) throws {
if first {
first = false
} else if pretty {
writer(",\n")
writeIndent()
} else {
writer(",")
}
if let key = key as? String {
try serializeString(key)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "NSDictionary key must be NSString"])
}
pretty ? writer(" : ") : writer(":")
try serializeJSON(value)
}
if sortedKeys {
let elems = try dict.sorted(by: { a, b in
guard let a = a.key as? String,
let b = b.key as? String else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: ["NSDebugDescription" : "NSDictionary key must be NSString"])
}
let options: NSString.CompareOptions = [.numeric, .caseInsensitive, .forcedOrdering]
let range: Range<String.Index> = a.startIndex..<a.endIndex
let locale = NSLocale.system
return a.compare(b, options: options, range: range, locale: locale) == .orderedAscending
})
for elem in elems {
try serializeDictionaryElement(key: elem.key, value: elem.value)
}
} else {
for (key, value) in dict {
try serializeDictionaryElement(key: key, value: value)
}
}
if pretty {
writer("\n")
decAndWriteIndent()
}
writer("}")
}
func serializeNull() throws {
writer("null")
}
let indentAmount = 2
mutating func incAndWriteIndent() {
indent += indentAmount
writeIndent()
}
mutating func decAndWriteIndent() {
indent -= indentAmount
writeIndent()
}
func writeIndent() {
for _ in 0..<indent {
writer(" ")
}
}
}
//MARK: - JSONDeserializer
private struct JSONReader {
static let whitespaceASCII: [UInt8] = [
0x09, // Horizontal tab
0x0A, // Line feed or New line
0x0D, // Carriage return
0x20, // Space
]
struct Structure {
static let BeginArray: UInt8 = 0x5B // [
static let EndArray: UInt8 = 0x5D // ]
static let BeginObject: UInt8 = 0x7B // {
static let EndObject: UInt8 = 0x7D // }
static let NameSeparator: UInt8 = 0x3A // :
static let ValueSeparator: UInt8 = 0x2C // ,
static let QuotationMark: UInt8 = 0x22 // "
static let Escape: UInt8 = 0x5C // \
}
typealias Index = Int
typealias IndexDistance = Int
struct UnicodeSource {
let buffer: UnsafeBufferPointer<UInt8>
let encoding: String.Encoding
let step: Int
init(buffer: UnsafeBufferPointer<UInt8>, encoding: String.Encoding) {
self.buffer = buffer
self.encoding = encoding
self.step = {
switch encoding {
case .utf8:
return 1
case .utf16BigEndian, .utf16LittleEndian:
return 2
case .utf32BigEndian, .utf32LittleEndian:
return 4
default:
return 1
}
}()
}
func takeASCII(_ input: Index) -> (UInt8, Index)? {
guard hasNext(input) else {
return nil
}
let index: Int
switch encoding {
case .utf8:
index = input
case .utf16BigEndian where buffer[input] == 0:
index = input + 1
case .utf32BigEndian where buffer[input] == 0 && buffer[input+1] == 0 && buffer[input+2] == 0:
index = input + 3
case .utf16LittleEndian where buffer[input+1] == 0:
index = input
case .utf32LittleEndian where buffer[input+1] == 0 && buffer[input+2] == 0 && buffer[input+3] == 0:
index = input
default:
return nil
}
return (buffer[index] < 0x80) ? (buffer[index], input + step) : nil
}
func takeString(_ begin: Index, end: Index) throws -> String {
let byteLength = begin.distance(to: end)
guard let chunk = String(data: Data(bytes: buffer.baseAddress!.advanced(by: begin), count: byteLength), encoding: encoding) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Unable to convert data to a string using the detected encoding. The data may be corrupt."
])
}
return chunk
}
func hasNext(_ input: Index) -> Bool {
return input + step <= buffer.endIndex
}
func distanceFromStart(_ index: Index) -> IndexDistance {
return buffer.startIndex.distance(to: index) / step
}
}
let source: UnicodeSource
func consumeWhitespace(_ input: Index) -> Index? {
var index = input
while let (char, nextIndex) = source.takeASCII(index), JSONReader.whitespaceASCII.contains(char) {
index = nextIndex
}
return index
}
func consumeStructure(_ ascii: UInt8, input: Index) throws -> Index? {
return try consumeWhitespace(input).flatMap(consumeASCII(ascii)).flatMap(consumeWhitespace)
}
func consumeASCII(_ ascii: UInt8) -> (Index) throws -> Index? {
return { (input: Index) throws -> Index? in
switch self.source.takeASCII(input) {
case nil:
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Unexpected end of file during JSON parse."
])
case let (taken, index)? where taken == ascii:
return index
default:
return nil
}
}
}
func consumeASCIISequence(_ sequence: String, input: Index) throws -> Index? {
var index = input
for scalar in sequence.unicodeScalars {
guard let nextIndex = try consumeASCII(UInt8(scalar.value))(index) else {
return nil
}
index = nextIndex
}
return index
}
func takeMatching(_ match: @escaping (UInt8) -> Bool) -> ([Character], Index) -> ([Character], Index)? {
return { input, index in
guard let (byte, index) = self.source.takeASCII(index), match(byte) else {
return nil
}
return (input + [Character(UnicodeScalar(byte))], index)
}
}
//MARK: - String Parsing
func parseString(_ input: Index) throws -> (String, Index)? {
guard let beginIndex = try consumeWhitespace(input).flatMap(consumeASCII(Structure.QuotationMark)) else {
return nil
}
var chunkIndex: Int = beginIndex
var currentIndex: Int = chunkIndex
var output: String = ""
while source.hasNext(currentIndex) {
guard let (ascii, index) = source.takeASCII(currentIndex) else {
currentIndex += source.step
continue
}
switch ascii {
case Structure.QuotationMark:
output += try source.takeString(chunkIndex, end: currentIndex)
return (output, index)
case Structure.Escape:
output += try source.takeString(chunkIndex, end: currentIndex)
if let (escaped, nextIndex) = try parseEscapeSequence(index) {
output += escaped
chunkIndex = nextIndex
currentIndex = nextIndex
continue
}
else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Invalid escape sequence at position \(source.distanceFromStart(currentIndex))"
])
}
default:
currentIndex = index
}
}
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Unexpected end of file during string parse."
])
}
func parseEscapeSequence(_ input: Index) throws -> (String, Index)? {
guard let (byte, index) = source.takeASCII(input) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Early end of unicode escape sequence around character"
])
}
let output: String
switch byte {
case 0x22: output = "\""
case 0x5C: output = "\\"
case 0x2F: output = "/"
case 0x62: output = "\u{08}" // \b
case 0x66: output = "\u{0C}" // \f
case 0x6E: output = "\u{0A}" // \n
case 0x72: output = "\u{0D}" // \r
case 0x74: output = "\u{09}" // \t
case 0x75: return try parseUnicodeSequence(index)
default: return nil
}
return (output, index)
}
func parseUnicodeSequence(_ input: Index) throws -> (String, Index)? {
guard let (codeUnit, index) = parseCodeUnit(input) else {
return nil
}
let isLeadSurrogate = UTF16.isLeadSurrogate(codeUnit)
let isTrailSurrogate = UTF16.isTrailSurrogate(codeUnit)
guard isLeadSurrogate || isTrailSurrogate else {
// The code units that are neither lead surrogates nor trail surrogates
// form valid unicode scalars.
return (String(UnicodeScalar(codeUnit)!), index)
}
// Surrogates must always come in pairs.
guard isLeadSurrogate else {
// Trail surrogate must come after lead surrogate
throw CocoaError.error(.propertyListReadCorrupt,
userInfo: [
"NSDebugDescription" : """
Unable to convert unicode escape sequence (no high-surrogate code point) \
to UTF8-encoded character at position \(source.distanceFromStart(input))
"""
])
}
guard let (trailCodeUnit, finalIndex) = try consumeASCIISequence("\\u", input: index).flatMap(parseCodeUnit),
UTF16.isTrailSurrogate(trailCodeUnit) else {
throw CocoaError.error(.propertyListReadCorrupt,
userInfo: [
"NSDebugDescription" : """
Unable to convert unicode escape sequence (no low-surrogate code point) \
to UTF8-encoded character at position \(source.distanceFromStart(input))
"""
])
}
return (String(UTF16.decode(UTF16.EncodedScalar([codeUnit, trailCodeUnit]))), finalIndex)
}
func isHexChr(_ byte: UInt8) -> Bool {
return (byte >= 0x30 && byte <= 0x39)
|| (byte >= 0x41 && byte <= 0x46)
|| (byte >= 0x61 && byte <= 0x66)
}
func parseCodeUnit(_ input: Index) -> (UTF16.CodeUnit, Index)? {
let hexParser = takeMatching(isHexChr)
guard let (result, index) = hexParser([], input).flatMap(hexParser).flatMap(hexParser).flatMap(hexParser),
let value = Int(String(result), radix: 16) else {
return nil
}
return (UTF16.CodeUnit(value), index)
}
//MARK: - Number parsing
private static let ZERO = UInt8(ascii: "0")
private static let ONE = UInt8(ascii: "1")
private static let NINE = UInt8(ascii: "9")
private static let MINUS = UInt8(ascii: "-")
private static let PLUS = UInt8(ascii: "+")
private static let LOWER_EXPONENT = UInt8(ascii: "e")
private static let UPPER_EXPONENT = UInt8(ascii: "E")
private static let DECIMAL_SEPARATOR = UInt8(ascii: ".")
private static let allDigits = (ZERO...NINE)
private static let oneToNine = (ONE...NINE)
private static let numberCodePoints: [UInt8] = {
var numberCodePoints = Array(ZERO...NINE)
numberCodePoints.append(contentsOf: [DECIMAL_SEPARATOR, MINUS, PLUS, LOWER_EXPONENT, UPPER_EXPONENT])
return numberCodePoints
}()
func parseNumber(_ input: Index, options opt: JSONSerialization.ReadingOptions) throws -> (Any, Index)? {
var isNegative = false
var string = ""
var isInteger = true
var exponent = 0
var positiveExponent = true
var index = input
var digitCount: Int?
var ascii: UInt8 = 0 // set by nextASCII()
// Validate the input is a valid JSON number, also gather the following
// about the input: isNegative, isInteger, the exponent and if it is +/-,
// and finally the count of digits including excluding an '.'
func checkJSONNumber() throws -> Bool {
// Return true if the next character is any one of the valid JSON number characters
func nextASCII() -> Bool {
guard let (ch, nextIndex) = source.takeASCII(index),
JSONReader.numberCodePoints.contains(ch) else { return false }
index = nextIndex
ascii = ch
string.append(Character(UnicodeScalar(ascii)))
return true
}
// Consume as many digits as possible and return with the next non-digit
// or nil if end of string.
func readDigits() -> UInt8? {
while let (ch, nextIndex) = source.takeASCII(index) {
if !JSONReader.allDigits.contains(ch) {
return ch
}
string.append(Character(UnicodeScalar(ch)))
index = nextIndex
}
return nil
}
guard nextASCII() else { return false }
if ascii == JSONReader.MINUS {
isNegative = true
guard nextASCII() else { return false }
}
if JSONReader.oneToNine.contains(ascii) {
guard let ch = readDigits() else { return true }
ascii = ch
if [ JSONReader.DECIMAL_SEPARATOR, JSONReader.LOWER_EXPONENT, JSONReader.UPPER_EXPONENT ].contains(ascii) {
guard nextASCII() else { return false } // There should be at least one char as readDigits didn't remove the '.eE'
}
} else if ascii == JSONReader.ZERO {
guard nextASCII() else { return true }
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue,
userInfo: ["NSDebugDescription" : "Numbers must start with a 1-9 at character \(input)." ])
}
if ascii == JSONReader.DECIMAL_SEPARATOR {
isInteger = false
guard readDigits() != nil else { return true }
guard nextASCII() else { return true }
} else if JSONReader.allDigits.contains(ascii) {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue,
userInfo: ["NSDebugDescription" : "Leading zeros not allowed at character \(input)." ])
}
digitCount = string.count - (isInteger ? 0 : 1) - (isNegative ? 1 : 0)
guard ascii == JSONReader.LOWER_EXPONENT || ascii == JSONReader.UPPER_EXPONENT else {
// End of valid number characters
return true
}
digitCount = digitCount! - 1
// Process the exponent
isInteger = false
guard nextASCII() else { return false }
if ascii == JSONReader.MINUS {
positiveExponent = false
guard nextASCII() else { return false }
} else if ascii == JSONReader.PLUS {
positiveExponent = true
guard nextASCII() else { return false }
}
guard JSONReader.allDigits.contains(ascii) else { return false }
exponent = Int(ascii - JSONReader.ZERO)
while nextASCII() {
guard JSONReader.allDigits.contains(ascii) else { return false } // Invalid exponent character
exponent = (exponent * 10) + Int(ascii - JSONReader.ZERO)
if exponent > 324 {
// Exponent is too large to store in a Double
return false
}
}
return true
}
guard try checkJSONNumber() == true else { return nil }
digitCount = digitCount ?? string.count - (isInteger ? 0 : 1) - (isNegative ? 1 : 0)
// Try Int64() or UInt64() first
if isInteger {
if isNegative {
if digitCount! <= 19, let intValue = Int64(string) {
return (NSNumber(value: intValue), index)
}
} else {
if digitCount! <= 20, let uintValue = UInt64(string) {
return (NSNumber(value: uintValue), index)
}
}
}
// Decimal holds more digits of precision but a smaller exponent than Double
// so try that if the exponent fits and there are more digits than Double can hold
if digitCount! > 17 && exponent >= -128 && exponent <= 127,
let decimal = Decimal(string: string), decimal.isFinite {
return (NSDecimalNumber(decimal: decimal), index)
}
// Fall back to Double() for everything else
if let doubleValue = Double(string) {
return (NSNumber(value: doubleValue), index)
}
return nil
}
//MARK: - Value parsing
func parseValue(_ input: Index, options opt: JSONSerialization.ReadingOptions) throws -> (Any, Index)? {
if let (value, parser) = try parseString(input) {
return (value, parser)
}
else if let parser = try consumeASCIISequence("true", input: input) {
return (NSNumber(value: true), parser)
}
else if let parser = try consumeASCIISequence("false", input: input) {
return (NSNumber(value: false), parser)
}
else if let parser = try consumeASCIISequence("null", input: input) {
return (NSNull(), parser)
}
else if let (object, parser) = try parseObject(input, options: opt) {
return (object, parser)
}
else if let (array, parser) = try parseArray(input, options: opt) {
return (array, parser)
}
else if let (number, parser) = try parseNumber(input, options: opt) {
return (number, parser)
}
return nil
}
//MARK: - Object parsing
func parseObject(_ input: Index, options opt: JSONSerialization.ReadingOptions) throws -> ([String: Any], Index)? {
guard let beginIndex = try consumeStructure(Structure.BeginObject, input: input) else {
return nil
}
var index = beginIndex
var output: [String: Any] = [:]
while true {
if let finalIndex = try consumeStructure(Structure.EndObject, input: index) {
return (output, finalIndex)
}
if let (key, value, nextIndex) = try parseObjectMember(index, options: opt) {
output[key] = value
if let finalParser = try consumeStructure(Structure.EndObject, input: nextIndex) {
return (output, finalParser)
}
else if let nextIndex = try consumeStructure(Structure.ValueSeparator, input: nextIndex) {
index = nextIndex
continue
}
else {
return nil
}
}
return nil
}
}
func parseObjectMember(_ input: Index, options opt: JSONSerialization.ReadingOptions) throws -> (String, Any, Index)? {
guard let (name, index) = try parseString(input) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Missing object key at location \(source.distanceFromStart(input))"
])
}
guard let separatorIndex = try consumeStructure(Structure.NameSeparator, input: index) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Invalid separator at location \(source.distanceFromStart(index))"
])
}
guard let (value, finalIndex) = try parseValue(separatorIndex, options: opt) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Invalid value at location \(source.distanceFromStart(separatorIndex))"
])
}
return (name, value, finalIndex)
}
//MARK: - Array parsing
func parseArray(_ input: Index, options opt: JSONSerialization.ReadingOptions) throws -> ([Any], Index)? {
guard let beginIndex = try consumeStructure(Structure.BeginArray, input: input) else {
return nil
}
var index = beginIndex
var output: [Any] = []
while true {
if let finalIndex = try consumeStructure(Structure.EndArray, input: index) {
return (output, finalIndex)
}
if let (value, nextIndex) = try parseValue(index, options: opt) {
output.append(value)
if let finalIndex = try consumeStructure(Structure.EndArray, input: nextIndex) {
return (output, finalIndex)
}
else if let nextIndex = try consumeStructure(Structure.ValueSeparator, input: nextIndex) {
index = nextIndex
continue
}
}
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.propertyListReadCorrupt.rawValue, userInfo: [
"NSDebugDescription" : "Badly formed array at location \(source.distanceFromStart(index))"
])
}
}
}
| apache-2.0 | eafab46ef90cf84e64963038cc17ba45 | 38.838178 | 499 | 0.552866 | 4.96354 | false | false | false | false |
cliqz-oss/browser-ios | Account/TokenServerClient.swift | 5 | 7384 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Alamofire
import Shared
import Foundation
import Deferred
import SwiftyJSON
let TokenServerClientErrorDomain = "org.mozilla.token.error"
let TokenServerClientUnknownError = TokenServerError.local(
NSError(domain: TokenServerClientErrorDomain, code: 999,
userInfo: [NSLocalizedDescriptionKey: "Invalid server response"]))
public struct TokenServerToken {
public let id: String
public let key: String
public let api_endpoint: String
public let uid: UInt64
public let durationInSeconds: UInt64
// A healthy token server reports its timestamp.
public let remoteTimestamp: Timestamp
/**
* Return true if this token points to the same place as the other token.
*/
public func sameDestination(_ other: TokenServerToken) -> Bool {
return self.uid == other.uid &&
self.api_endpoint == other.api_endpoint
}
public static func fromJSON(_ json: JSON) -> TokenServerToken? {
if let
id = json["id"].string,
let key = json["key"].string,
let api_endpoint = json["api_endpoint"].string,
let uid = json["uid"].int64,
let durationInSeconds = json["duration"].int64,
let remoteTimestamp = json["remoteTimestamp"].int64 {
return TokenServerToken(id: id, key: key, api_endpoint: api_endpoint, uid: UInt64(uid),
durationInSeconds: UInt64(durationInSeconds), remoteTimestamp: Timestamp(remoteTimestamp))
}
return nil
}
public func asJSON() -> JSON {
let D: [String: AnyObject] = [
"id": id as AnyObject,
"key": key as AnyObject,
"api_endpoint": api_endpoint as AnyObject,
"uid": NSNumber(value: uid as UInt64),
"duration": NSNumber(value: durationInSeconds as UInt64),
"remoteTimestamp": NSNumber(value: remoteTimestamp),
]
return JSON(D as NSDictionary)
}
}
enum TokenServerError {
// A Remote error definitely has a status code, but we may not have a well-formed JSON response
// with a status; and we could have an unhealthy server that is not reporting its timestamp.
case remote(code: Int32, status: String?, remoteTimestamp: Timestamp?)
case local(NSError)
}
extension TokenServerError: MaybeErrorType {
var description: String {
switch self {
case let .remote(code: code, status: status, remoteTimestamp: _):
if let status = status {
return "<TokenServerError.Remote \(code): \(status)>"
} else {
return "<TokenServerError.Remote \(code)>"
}
case let .local(error):
return "<TokenServerError.Local Error Domain=\(error.domain) Code=\(error.code) \"\(error.localizedDescription)\">"
}
}
}
open class TokenServerClient {
let URL: URL
public init(URL: URL? = nil) {
self.URL = URL ?? ProductionSync15Configuration().tokenServerEndpointURL
}
open class func getAudience(forURL URL: URL) -> String {
if let port = URL.port {
return "\(URL.scheme!)://\(URL.host!):\(port)"
} else {
return "\(URL.scheme!)://\(URL.host!)"
}
}
fileprivate class func parseTimestampHeader(_ header: String?) -> Timestamp? {
if let timestampString = header {
return decimalSecondsStringToTimestamp(timestampString)
} else {
return nil
}
}
fileprivate class func remoteError(fromJSON json: JSON, statusCode: Int, remoteTimestampHeader: String?) -> TokenServerError? {
if json.error != nil {
return nil
}
if 200 <= statusCode && statusCode <= 299 {
return nil
}
return TokenServerError.remote(code: Int32(statusCode), status: json["status"].string,
remoteTimestamp: parseTimestampHeader(remoteTimestampHeader))
}
fileprivate class func token(fromJSON json: JSON, remoteTimestampHeader: String?) -> TokenServerToken? {
if json.error != nil {
return nil
}
if let
remoteTimestamp = parseTimestampHeader(remoteTimestampHeader), // A token server that is not providing its timestamp is not healthy.
let id = json["id"].string,
let key = json["key"].string,
let api_endpoint = json["api_endpoint"].string,
let uid = json["uid"].int,
let durationInSeconds = json["duration"].int64, durationInSeconds > 0 {
return TokenServerToken(id: id, key: key, api_endpoint: api_endpoint, uid: UInt64(uid),
durationInSeconds: UInt64(durationInSeconds), remoteTimestamp: remoteTimestamp)
}
return nil
}
lazy fileprivate var alamofire: SessionManager = {
let ua = UserAgent.tokenServerClientUserAgent
let configuration = URLSessionConfiguration.ephemeral
return SessionManager.managerWithUserAgent(ua, configuration: configuration)
}()
open func token(_ assertion: String, clientState: String? = nil) -> Deferred<Maybe<TokenServerToken>> {
let deferred = Deferred<Maybe<TokenServerToken>>()
var mutableURLRequest = URLRequest(url: URL)
mutableURLRequest.setValue("BrowserID " + assertion, forHTTPHeaderField: "Authorization")
if let clientState = clientState {
mutableURLRequest.setValue(clientState, forHTTPHeaderField: "X-Client-State")
}
alamofire.request(mutableURLRequest)
.validate(contentType: ["application/json"])
.responseJSON { response in
// Don't cancel requests just because our Manager is deallocated.
withExtendedLifetime(self.alamofire) {
if let error = response.result.error {
deferred.fill(Maybe(failure: TokenServerError.local(error as NSError)))
return
}
if let data = response.result.value as AnyObject? { // Declaring the type quiets a Swift warning about inferring AnyObject.
let json = JSON(data)
let remoteTimestampHeader = response.response?.allHeaderFields["X-Timestamp"] as? String
if let remoteError = TokenServerClient.remoteError(fromJSON: json, statusCode: response.response!.statusCode,
remoteTimestampHeader: remoteTimestampHeader) {
deferred.fill(Maybe(failure: remoteError))
return
}
if let token = TokenServerClient.token(fromJSON: json, remoteTimestampHeader: remoteTimestampHeader) {
deferred.fill(Maybe(success: token))
return
}
}
deferred.fill(Maybe(failure: TokenServerClientUnknownError))
}
}
return deferred
}
}
| mpl-2.0 | 177fb4acfd6fdf724da730f2f4dd1232 | 40.022222 | 147 | 0.604686 | 5.266762 | false | false | false | false |
zhouxj6112/ARKit | ARKitInteraction/ARKitInteraction/ViewController.swift | 1 | 7033 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Main view controller for the AR experience.
*/
import ARKit
import SceneKit
import UIKit
class ViewController: UIViewController {
// MARK: IBOutlets
@IBOutlet var sceneView: VirtualObjectARView!
@IBOutlet weak var addObjectButton: UIButton!
@IBOutlet weak var blurView: UIVisualEffectView!
@IBOutlet weak var spinner: UIActivityIndicatorView!
// MARK: - UI Elements
var focusSquare = FocusSquare()
/// The view controller that displays the status and "restart experience" UI.
lazy var statusViewController: StatusViewController = {
return childViewControllers.lazy.flatMap({ $0 as? StatusViewController }).first!
}()
// MARK: - ARKit Configuration Properties
/// A type which manages gesture manipulation of virtual content in the scene.
lazy var virtualObjectInteraction = VirtualObjectInteraction(sceneView: sceneView)
/// Coordinates the loading and unloading of reference nodes for virtual objects.
let virtualObjectLoader = VirtualObjectLoader()
/// Marks if the AR experience is available for restart.
var isRestartAvailable = true
/// A serial queue used to coordinate adding or removing nodes from the scene.
let updateQueue = DispatchQueue(label: "com.example.apple-samplecode.arkitexample.serialSceneKitQueue")
var screenCenter: CGPoint {
let bounds = sceneView.bounds
return CGPoint(x: bounds.midX, y: bounds.midY)
}
/// Convenience accessor for the session owned by ARSCNView.
var session: ARSession {
return sceneView.session
}
// MARK: - View Controller Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
sceneView.delegate = self
sceneView.session.delegate = self
// sceneView.showsStatistics = true
// sceneView.allowsCameraControl = false
// sceneView.antialiasingMode = .multisampling4X
// sceneView.debugOptions = SCNDebugOptions.showBoundingBoxes
// Set up scene content.
setupCamera()
sceneView.scene.rootNode.addChildNode(focusSquare)
/*
The `sceneView.automaticallyUpdatesLighting` option creates an
ambient light source and modulates its intensity. This sample app
instead modulates a global lighting environment map for use with
physically based materials, so disable automatic lighting.
*/
sceneView.automaticallyUpdatesLighting = false
if let environmentMap = UIImage(named: "Models.scnassets/sharedImages/environment_blur.exr") {
sceneView.scene.lightingEnvironment.contents = environmentMap
}
// Hook up status view controller callback(s).
statusViewController.restartExperienceHandler = { [unowned self] in
self.restartExperience()
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(showVirtualObjectSelectionViewController))
// Set the delegate to ensure this gesture is only used when there are no virtual objects in the scene.
tapGesture.delegate = self
sceneView.addGestureRecognizer(tapGesture)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Prevent the screen from being dimmed to avoid interuppting the AR experience.
UIApplication.shared.isIdleTimerDisabled = true
// Start the `ARSession`.
resetTracking()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
session.pause()
}
// MARK: - Scene content setup
func setupCamera() {
guard let camera = sceneView.pointOfView?.camera else {
fatalError("Expected a valid `pointOfView` from the scene.")
}
/*
Enable HDR camera settings for the most realistic appearance
with environmental lighting and physically based materials.
*/
camera.wantsHDR = true
camera.exposureOffset = -1
camera.minimumExposure = -1
camera.maximumExposure = 3
}
// MARK: - Session management
/// Creates a new AR configuration to run on the `session`.
func resetTracking() {
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .horizontal
session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
statusViewController.scheduleMessage("FIND A SURFACE TO PLACE AN OBJECT", inSeconds: 7.5, messageType: .planeEstimation)
}
// MARK: - Focus Square
func updateFocusSquare() {
let isObjectVisible = virtualObjectLoader.loadedObjects.contains { object in
return sceneView.isNode(object, insideFrustumOf: sceneView.pointOfView!)
}
if isObjectVisible {
focusSquare.hide()
} else {
focusSquare.unhide()
statusViewController.scheduleMessage("TRY MOVING LEFT OR RIGHT", inSeconds: 5.0, messageType: .focusSquare)
}
// We should always have a valid world position unless the sceen is just being initialized.
guard let (worldPosition, planeAnchor, _) = sceneView.worldPosition(fromScreenPosition: screenCenter, objectPosition: focusSquare.lastPosition) else {
updateQueue.async {
self.focusSquare.state = .initializing
self.sceneView.pointOfView?.addChildNode(self.focusSquare)
}
addObjectButton.isHidden = true
return
}
updateQueue.async {
self.sceneView.scene.rootNode.addChildNode(self.focusSquare)
let camera = self.session.currentFrame?.camera
if let planeAnchor = planeAnchor {
self.focusSquare.state = .planeDetected(anchorPosition: worldPosition, planeAnchor: planeAnchor, camera: camera)
} else {
self.focusSquare.state = .featuresDetected(anchorPosition: worldPosition, camera: camera)
}
}
addObjectButton.isHidden = false
statusViewController.cancelScheduledMessage(for: .focusSquare)
}
// MARK: - Error handling
func displayErrorMessage(title: String, message: String) {
// Blur the background.
blurView.isHidden = false
// Present an alert informing about the error that has occurred.
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Restart Session", style: .default) { _ in
alertController.dismiss(animated: true, completion: nil)
self.blurView.isHidden = true
self.resetTracking()
}
alertController.addAction(restartAction)
present(alertController, animated: true, completion: nil)
}
}
| apache-2.0 | 5852c86522c5619dc67b05dbf67dd014 | 35.242268 | 158 | 0.66989 | 5.346768 | false | false | false | false |
brentvatne/react-native-video | ios/Video/Features/RCTPlayerOperations.swift | 1 | 9287 | import AVFoundation
import MediaAccessibility
import Promises
let RCTVideoUnset = -1
/*!
* Collection of mutating functions
*/
enum RCTPlayerOperations {
static func setSideloadedText(player:AVPlayer?, textTracks:[TextTrack]?, criteria:SelectedTrackCriteria?) {
let type = criteria?.type
let textTracks:[TextTrack]! = textTracks ?? RCTVideoUtils.getTextTrackInfo(player)
// The first few tracks will be audio & video track
let firstTextIndex:Int = 0
for firstTextIndex in 0..<(player?.currentItem?.tracks.count ?? 0) {
if player?.currentItem?.tracks[firstTextIndex].assetTrack?.hasMediaCharacteristic(.legible) ?? false {
break
}
}
var selectedTrackIndex:Int = RCTVideoUnset
if (type == "disabled") {
// Do nothing. We want to ensure option is nil
} else if (type == "language") {
let selectedValue = criteria?.value as? String
for i in 0..<textTracks.count {
let currentTextTrack = textTracks[i]
if (selectedValue == currentTextTrack.language) {
selectedTrackIndex = i
break
}
}
} else if (type == "title") {
let selectedValue = criteria?.value as? String
for i in 0..<textTracks.count {
let currentTextTrack = textTracks[i]
if (selectedValue == currentTextTrack.title) {
selectedTrackIndex = i
break
}
}
} else if (type == "index") {
if let value = criteria?.value, let index = value as? Int {
if textTracks.count > index {
selectedTrackIndex = index
}
}
}
// in the situation that a selected text track is not available (eg. specifies a textTrack not available)
if (type != "disabled") && selectedTrackIndex == RCTVideoUnset {
let captioningMediaCharacteristics = MACaptionAppearanceCopyPreferredCaptioningMediaCharacteristics(.user) as! CFArray
let captionSettings = captioningMediaCharacteristics as? [AnyHashable]
if ((captionSettings?.contains(AVMediaCharacteristic.transcribesSpokenDialogForAccessibility)) != nil) {
selectedTrackIndex = 0 // If we can't find a match, use the first available track
let systemLanguage = NSLocale.preferredLanguages.first
for i in 0..<textTracks.count {
let currentTextTrack = textTracks[i]
if systemLanguage == currentTextTrack.language {
selectedTrackIndex = i
break
}
}
}
}
for i in firstTextIndex..<(player?.currentItem?.tracks.count ?? 0) {
var isEnabled = false
if selectedTrackIndex != RCTVideoUnset {
isEnabled = i == selectedTrackIndex + firstTextIndex
}
player?.currentItem?.tracks[i].isEnabled = isEnabled
}
}
// UNUSED
static func setStreamingText(player:AVPlayer?, criteria:SelectedTrackCriteria?) {
let type = criteria?.type
let group:AVMediaSelectionGroup! = player?.currentItem?.asset.mediaSelectionGroup(forMediaCharacteristic: AVMediaCharacteristic.legible)
var mediaOption:AVMediaSelectionOption!
if (type == "disabled") {
// Do nothing. We want to ensure option is nil
} else if (type == "language") || (type == "title") {
let value = criteria?.value as? String
for i in 0..<group.options.count {
let currentOption:AVMediaSelectionOption! = group.options[i]
var optionValue:String!
if (type == "language") {
optionValue = currentOption.extendedLanguageTag
} else {
optionValue = currentOption.commonMetadata.map(\.value)[0] as! String
}
if (value == optionValue) {
mediaOption = currentOption
break
}
}
//} else if ([type isEqualToString:@"default"]) {
// option = group.defaultOption; */
} else if (type == "index") {
if let value = criteria?.value, let index = value as? Int {
if group.options.count > index {
mediaOption = group.options[index]
}
}
} else { // default. invalid type or "system"
#if TARGET_OS_TV
// Do noting. Fix for tvOS native audio menu language selector
#else
player?.currentItem?.selectMediaOptionAutomatically(in: group)
return
#endif
}
#if TARGET_OS_TV
// Do noting. Fix for tvOS native audio menu language selector
#else
// If a match isn't found, option will be nil and text tracks will be disabled
player?.currentItem?.select(mediaOption, in:group)
#endif
}
static func setMediaSelectionTrackForCharacteristic(player:AVPlayer?, characteristic:AVMediaCharacteristic, criteria:SelectedTrackCriteria?) {
let type = criteria?.type
let group:AVMediaSelectionGroup! = player?.currentItem?.asset.mediaSelectionGroup(forMediaCharacteristic: characteristic)
var mediaOption:AVMediaSelectionOption!
if (type == "disabled") {
// Do nothing. We want to ensure option is nil
} else if (type == "language") || (type == "title") {
let value = criteria?.value as? String
for i in 0..<group.options.count {
let currentOption:AVMediaSelectionOption! = group.options[i]
var optionValue:String!
if (type == "language") {
optionValue = currentOption.extendedLanguageTag
} else {
optionValue = currentOption.commonMetadata.map(\.value)[0] as? String
}
if (value == optionValue) {
mediaOption = currentOption
break
}
}
//} else if ([type isEqualToString:@"default"]) {
// option = group.defaultOption; */
} else if type == "index" {
if let value = criteria?.value, let index = value as? Int {
if group.options.count > index {
mediaOption = group.options[index]
}
}
} else if let group = group { // default. invalid type or "system"
player?.currentItem?.selectMediaOptionAutomatically(in: group)
return
}
if let group = group {
// If a match isn't found, option will be nil and text tracks will be disabled
player?.currentItem?.select(mediaOption, in:group)
}
}
static func seek(player: AVPlayer, playerItem:AVPlayerItem, paused:Bool, seekTime:Float, seekTolerance:Float) -> Promise<Bool> {
let timeScale:Int = 1000
let cmSeekTime:CMTime = CMTimeMakeWithSeconds(Float64(seekTime), preferredTimescale: Int32(timeScale))
let current:CMTime = playerItem.currentTime()
let tolerance:CMTime = CMTimeMake(value: Int64(seekTolerance), timescale: Int32(timeScale))
return Promise<Bool>(on: .global()) { fulfill, reject in
guard CMTimeCompare(current, cmSeekTime) != 0 else {
reject(NSError())
return
}
if !paused { player.pause() }
player.seek(to: cmSeekTime, toleranceBefore:tolerance, toleranceAfter:tolerance, completionHandler:{ (finished:Bool) in
fulfill(finished)
})
}
}
static func configureAudio(ignoreSilentSwitch:String, mixWithOthers:String) {
let session:AVAudioSession! = AVAudioSession.sharedInstance()
var category:AVAudioSession.Category? = nil
var options:AVAudioSession.CategoryOptions? = nil
if (ignoreSilentSwitch == "ignore") {
category = AVAudioSession.Category.playback
} else if (ignoreSilentSwitch == "obey") {
category = AVAudioSession.Category.ambient
}
if (mixWithOthers == "mix") {
options = .mixWithOthers
} else if (mixWithOthers == "duck") {
options = .duckOthers
}
if let category = category, let options = options {
do {
try session.setCategory(category, options: options)
} catch {
}
} else if let category = category, options == nil {
do {
try session.setCategory(category)
} catch {
}
} else if category == nil, let options = options {
do {
try session.setCategory(session.category, options: options)
} catch {
}
}
}
}
| mit | 91942e9c8bf162882d92b1b1ba096df7 | 40.64574 | 146 | 0.555185 | 5.136615 | false | false | false | false |
novi/tsssm-crawler | Sources/CrawlerBase/RSS.swift | 1 | 2331 | //
// RSS.swift
// CrawlerBase
//
// Created by Yusuke Ito on 6/25/16.
// Copyright © 2016 Yusuke Ito. All rights reserved.
//
import Foundation
import MySQL
public enum URLError: ErrorProtocol {
case invalidURLString(String)
}
extension NSURL {
public static func from(string: String) throws -> NSURL {
guard let url = NSURL(string: string) else {
throw URLError.invalidURLString(string)
}
return url
}
}
public enum Row {
public struct RSS: QueryRowResultType {
public let rssID: AutoincrementID<RSSID>
public let title: String
public let url: NSURL
public let createdAt: NSDate
public static func decodeRow(r: QueryRowResult) throws -> RSS {
return try RSS(rssID: r <| "rss_id",
title: r <| "title",
url: NSURL.from(string: r <| "url"),
createdAt: (r <| "created_at" as SQLDate).date()
)
}
}
}
extension Row.RSS: QueryParameterDictionaryType {
public func queryParameter() throws -> QueryDictionary {
return QueryDictionary([
"rss_id": rssID,
"title": title,
"url": url.absoluteString,
"created_at": createdAt
])
}
}
extension Row.RSS {
public enum Error: ErrorProtocol {
case noRSS(RSSID)
}
public static func fetch(byID rssID: RSSID, pool: ConnectionPool) throws -> Row.RSS {
let rss: [Row.RSS] = try pool.execute { conn in
try conn.query("SELECT rss_id,title,url,created_at FROM rss WHERE rss_id = ? LIMIT 1", [rssID])
}
guard let first = rss.first else {
throw Error.noRSS(rssID)
}
return first
}
public static func fetchAll(pool: ConnectionPool) throws -> [Row.RSS] {
return try pool.execute { conn in
try conn.query("SELECT rss_id,title,url,created_at FROM rss")
}
}
public static func createNew(title: String, url: NSURL, pool: ConnectionPool) throws {
try pool.execute { conn in
let rss = Row.RSS(rssID: .noID, title: title, url: url, createdAt: NSDate())
let _: QueryStatus = try conn.query("INSERT INTO rss SET ?", [rss])
}
}
}
| mit | 6de037bd905963cbf0031224c3a2ae36 | 27.414634 | 107 | 0.572961 | 4.109347 | false | false | false | false |
peterlafferty/Emojirama | Emojirama/ViewController.swift | 1 | 4865 | //
// ViewController.swift
// CollectionView
//
// Created by Peter Lafferty on 16/09/2015.
// Copyright © 2015 Peter Lafferty. All rights reserved.
//
import UIKit
import EmojiramaKit
class ViewController: UIViewController {
var emoji: Emoji?
var currentSelectedValue = ""
var activity: NSUserActivity?
@IBOutlet weak var value: UILabel!
@IBOutlet weak var desc: UILabel!
@IBOutlet weak var tags: UILabel!
@IBOutlet weak var version: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
guard let e = emoji else {
return
}
//self.title = e.value
value.text = e.value
currentSelectedValue = e.value
toolbarItems = createToolbarItems(e)
desc.text = "Description: " + e.text
tags.text = "Tags: " + e.tags.joined(separator: ", ")
if e.version.isEmpty == false {
version.text = "From Unicode: " + e.version
} else {
version.text = ""
}
if #available(iOS 9.0, *) {
activity = NSUserActivity(activityType: "com.peterlafferty.emojirama.view")
activity?.isEligibleForHandoff = false
activity?.isEligibleForPublicIndexing = false
activity?.isEligibleForSearch = true
activity?.title = "\(e.value) - \(e.text)"
activity?.keywords = Set(e.tags)
activity?.keywords.insert("emoji")
activity?.userInfo = ["emoji.value": e.value]
activity?.becomeCurrent()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateSkinTone(_ sender: AnyObject) {
if let button = sender as? UIBarButtonItem {
self.value.text = button.title
if let value = button.title {
currentSelectedValue = value
}
}
}
func share(_ sender: AnyObject) {
guard let e = emoji else {
return
}
UIPasteboard.general.string = currentSelectedValue
let textToShare = "\(e.value), \(e.text) @emojirama https://appsto.re/ie/4b-q-.i"
let objectsToShare = [textToShare, screenshot()] as [Any]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
if let shareButton = sender as? UIBarButtonItem {
activityVC.popoverPresentationController?.barButtonItem = shareButton
present(activityVC, animated: true, completion: nil)
}
}
func screenshot() -> Data {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 1.0)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIImageJPEGRepresentation(image!, 0.7)!
}
@IBAction func copyEmoji(_ sender: AnyObject) {
UIPasteboard.general.string = currentSelectedValue
}
@available(iOS 9, *)
override var previewActionItems: [UIPreviewActionItem] {
let copyAction = UIPreviewAction(title: "Copy", style: .default, handler: { (_, viewController) -> Void in
guard let viewController = viewController as? ViewController,
let emoji = viewController.emoji
else { return }
UIPasteboard.general.string = emoji.value
})
return [copyAction]
}
fileprivate func createToolbarItems(_ emoji: Emoji) -> [UIBarButtonItem] {
var items = [UIBarButtonItem]()
if emoji.hasSkinTone {
for tone in emoji.tones {
items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
let barButtonItem = UIBarButtonItem(
title: tone,
style: UIBarButtonItemStyle.plain,
target: self,
action: #selector(ViewController.updateSkinTone(_:))
)
items.append(barButtonItem)
items.append(
UIBarButtonItem(
barButtonSystemItem: .flexibleSpace,
target: nil,
action: nil
)
)
}
} else {
//make sure the share button is on the right
items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
}
//add button for sharing
let shareButton = UIBarButtonItem(
barButtonSystemItem: .action,
target: self,
action: #selector(ViewController.share(_:))
)
items.append(shareButton)
return items
}
}
| mit | 56a8f680393532c107390e24e5c1fbfd | 30.380645 | 114 | 0.586965 | 5.152542 | false | false | false | false |
PatrickChow/Swift-Awsome | News/Modules/Reader/ReaderAdapter.swift | 1 | 2638 | //
// Created by Patrick Chow on 2017/4/20.
// Copyright (c) 2017 Jiemian Technology. All rights reserved.
import Foundation
import MGTemplateEngine
protocol ReaderHTMLStringSynthesizer {
func htmlString(forEmptyView night: Bool) -> String
func htmlString(forArticle dic: [String: Any]) -> String
func htmlString(forRelatedNews array: [[String: String]]) -> String
func htmlString(forTags array: [[String: String]]) -> String
func htmlString(forComments array: [[String: String]]) -> String
}
class ReaderAdapter {
// MARK: Properties
let templateEngine: MGTemplateEngine = {
let templateEngine = MGTemplateEngine()
let matcher = ICUTemplateMatcher(templateEngine: templateEngine)
templateEngine.matcher = matcher!
return templateEngine
}()
/*
* Reader assets path, include template,css,js and base64 file path
*/
fileprivate struct AssetsPath {
static let templatePath: String! = {
let path = Bundle.main.path(forResource: "template", ofType: "html")
return path!
}()
static let cssPath: String! = {
let path = Bundle.main.path(forResource: "css", ofType: "css")
return path!
}()
static let javaScriptPath: String! = {
let path = Bundle.main.path(forResource: "content", ofType: "js")
return path!
}()
}
init() {
}
// MARK: Public Func
// MARK: UIViewController / Lifecycle
// MARK: Target Func
}
extension ReaderAdapter: ReaderHTMLStringSynthesizer {
func htmlString(forArticle dic: [String: Any]) -> String {
return templateEngine.processTemplateInFile(atPath: AssetsPath.templatePath, withVariables: dic.templateVariable)
}
func htmlString(forEmptyView night: Bool) -> String {
let style = night ? "background-color:#3f3f3f" : "background-color:#ffffff"
return "<!DOCTYPE HTML>" +
"<html>" +
"<body style=\"\(style)\"></body>" +
"</html>"
}
func htmlString(forRelatedNews array: [[String: String]]) -> String {
return ""
}
func htmlString(forTags array: [[String: String]]) -> String {
var mutableString = "<ul id=\"tags_ul\">"
for i in 0...array.count - 1 {
mutableString.append("<li class=\"\(1)\" tagId=\"\(1)\" name=\"\(1)\" >\(1)</li>")
}
mutableString.append("</ul>")
return mutableString
}
func htmlString(forComments array: [[String: String]]) -> String {
return ""
}
}
| mit | ad9c69c538f625277103129764611c41 | 27.365591 | 121 | 0.59856 | 4.463621 | false | false | false | false |
bparish628/iFarm-Health | iOS/iFarm-Health/Pods/Charts/Source/Charts/Formatters/DefaultAxisValueFormatter.swift | 4 | 2365 | //
// DefaultAxisValueFormatter.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
@objc(ChartDefaultAxisValueFormatter)
open class DefaultAxisValueFormatter: NSObject, IAxisValueFormatter
{
public typealias Block = (
_ value: Double,
_ axis: AxisBase?) -> String
@objc open var block: Block?
@objc open var hasAutoDecimals: Bool = false
fileprivate var _formatter: NumberFormatter?
@objc open var formatter: NumberFormatter?
{
get { return _formatter }
set
{
hasAutoDecimals = false
_formatter = newValue
}
}
fileprivate var _decimals: Int?
open var decimals: Int?
{
get { return _decimals }
set
{
_decimals = newValue
if let digits = newValue
{
self.formatter?.minimumFractionDigits = digits
self.formatter?.maximumFractionDigits = digits
self.formatter?.usesGroupingSeparator = true
}
}
}
public override init()
{
super.init()
self.formatter = NumberFormatter()
hasAutoDecimals = true
}
@objc public init(formatter: NumberFormatter)
{
super.init()
self.formatter = formatter
}
@objc public init(decimals: Int)
{
super.init()
self.formatter = NumberFormatter()
self.formatter?.usesGroupingSeparator = true
self.decimals = decimals
hasAutoDecimals = true
}
@objc public init(block: @escaping Block)
{
super.init()
self.block = block
}
@objc public static func with(block: @escaping Block) -> DefaultAxisValueFormatter?
{
return DefaultAxisValueFormatter(block: block)
}
open func stringForValue(_ value: Double,
axis: AxisBase?) -> String
{
if block != nil
{
return block!(value, axis)
}
else
{
return formatter?.string(from: NSNumber(floatLiteral: value)) ?? ""
}
}
}
| apache-2.0 | 2baa49adca6695535408b5121db57856 | 21.961165 | 87 | 0.552643 | 5.163755 | false | false | false | false |
gyro-n/PaymentsIos | GyronPayments/Classes/Models/BankAccount.swift | 1 | 4783 | //
// BankAccount.swift
// GyronPayments
//
// Created by Ye David on 10/31/16.
// Copyright © 2016 gyron. All rights reserved.
//
import Foundation
/**
The BankAccountType contains a list of different types of bank accounts (checking, savings)
*/
public enum BankAccountType: String {
case checking = "checking"
case savings = "savings"
}
/**
The BankAccount class stores the information about the bank account for the merchant.
Bank account resources are eligible bank accounts that are to receive a transfer at the end of a transfer period. You can create, edit, and delete bank accounts via the merchant console.
You can create up to 10 bank accounts, but only one can be set to primary. The primary bank account is the one that will be transfered to at the end of the next pay cycle.
A bank account starts in the new state, and then when a transfer has been made to it, it becomes verified. If a transfer is unable to be made, it will be change to the unable_to_verify state and the user will be contacted. If a transfer has been made to the account before, but subsequently rejected, it will be set to errored.
*/
open class BankAccount: BaseModel {
/**
The unique identifier for the bank account
*/
public var id: String
/**
The account holder's name
*/
public var holderName: String
/**
The name of the bank
*/
public var bankName: String
/**
The name of the bank's branch
*/
public var branchName: String?
/**
The country of the bank account
*/
public var country: String
/**
The address of the bank account
*/
public var bankAddress: String?
/**
The currency the bank account handles.
*/
public var currency: String
/**
The routing number for the bank account.
*/
public var routingNumber: String?
/**
The SWIFT code for the bank account
*/
public var swiftCode: String?
/**
The ifsc Code for the bank account
*/
public var ifscCode: String?
/**
The routing code for the bank account.
*/
public var routingCode: String?
/**
The last 4 digits of the bank account.
*/
public var lastFour: String
/**
Whether or not the bank account is active.
*/
public var active: Bool
/**
One of new, verified, unable_to_verify, or errored.
*/
public var status: String
/**
The date the bank account was created.
*/
public var createdOn: String
/**
The date the bank account was updated.
*/
public var updatedOn: String
/**
Whether the bank account is the primary account or not.
*/
public var primary: Bool
/**
The account number, obfuscated except the last 4 digits.
*/
public var accountNumber: String?
/**
The type of the bank account. One of (checking, savings)
*/
public var accountType: BankAccountType
/**
Initializes the BankAccount object
*/
override init() {
id = ""
holderName = ""
bankName = ""
branchName = nil
country = ""
bankAddress = nil
currency = ""
routingNumber = nil
swiftCode = nil
ifscCode = nil
routingCode = nil
lastFour = ""
active = false
status = ""
createdOn = ""
updatedOn = ""
primary = true
accountNumber = nil
accountType = BankAccountType.savings
}
/**
Maps the values from a hash map object into the BankAccount.
@param map the hash map containing the data
*/
override open func mapFromObject(map: ResponseData) {
id = map["id"] as? String ?? ""
holderName = map["holder_name"] as? String ?? ""
bankName = map["bank_name"] as? String ?? ""
branchName = map["branch_name"] as? String
country = map["country"] as? String ?? ""
bankAddress = map["bank_address"] as? String
currency = map["currency"] as? String ?? ""
routingNumber = map["routing_number"] as? String
swiftCode = map["swift_code"] as? String
ifscCode = map["ifsc_code"] as? String
routingCode = map["routing_code"] as? String
lastFour = map["last_four"] as? String ?? ""
active = map["active"] as? Bool ?? false
status = map["status"] as? String ?? ""
createdOn = map["created_on"] as? String ?? ""
updatedOn = map["updated_on"] as? String ?? ""
primary = map["primary"] as? Bool ?? false
accountNumber = map["account_number"] as? String
accountType = BankAccountType(rawValue: map["account_type"] as? String ?? BankAccountType.savings.rawValue)!
}
}
| mit | 8c0a1fba7fe798166ed9594e49b20dfa | 29.458599 | 328 | 0.61376 | 4.485929 | false | false | false | false |
tectijuana/iOS | VargasJuan/Demo-MVC/Demo MVC/ViewController.swift | 2 | 4272 | //
// ViewController.swift
// Demo MVC
//
// Created by isc on 11/25/16.
// Copyright © 2016 isc. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var votesButton: UIButton!
@IBOutlet weak var usersTableView: UITableView!
private var users = [User]()
private var selectedUser: Int?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
votesButton.layer.cornerRadius = votesButton.bounds.size.width/2;
votesButton.layer.borderWidth = 0
users = DBUtil.instance.getUsers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func newButtonClicked() {
firstNameTextField.text = ""
lastNameTextField.text = ""
emailTextField.text = ""
votesButton.setTitle("0", for: .normal)
}
@IBAction func addButtonClicked() {
let first_name = firstNameTextField.text ?? ""
let last_name = lastNameTextField.text ?? ""
let email = emailTextField.text ?? ""
if let id = DBUtil.instance.addUser(ufirst_name: first_name, ulast_name: last_name, uemail: email) {
let user = User(id: id, first_name: first_name, last_name: last_name, email: email, votes: 0)
users.append(user)
usersTableView.insertRows(at: [IndexPath(row: users.count-1, section: 0)], with: .fade)
usersTableView.selectRow(at: IndexPath(row: users.count-1, section: 0), animated: true, scrollPosition: .none)
}
}
@IBAction func updateButtonClicked() {
if selectedUser != nil {
let id = users[selectedUser!].id!
print("Selected user id: \(id)")
let user = User(
id: id,
first_name: firstNameTextField.text ?? "",
last_name: lastNameTextField.text ?? "",
email: emailTextField.text ?? "",
votes: Int64(votesButton.title(for: .normal)!)!)
if DBUtil.instance.updateUser(uid: id, newUser: user) {
users.remove(at: selectedUser!)
users.insert(user, at: selectedUser!)
usersTableView.reloadData()
}
} else {
print("No item selected")
}
}
@IBAction func deleteButtonClicked() {
if selectedUser != nil && selectedUser! < users.count {
if DBUtil.instance.deleteUser(uid: users[selectedUser!].id!) {
users.remove(at: selectedUser!)
usersTableView.deleteRows(at: [IndexPath(row: selectedUser!, section: 0)], with: .fade)
}
} else {
print("No item selected")
}
}
@IBAction func votesButtonClicked() {
let votes = Int64(votesButton.title(for: .normal)!)! + 1
votesButton.setTitle(String(votes), for: .normal)
updateButtonClicked()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
firstNameTextField.text = users[indexPath.row].first_name
lastNameTextField.text = users[indexPath.row].last_name
emailTextField.text = users[indexPath.row].email
votesButton.setTitle(String(users[indexPath.row].votes), for: .normal)
selectedUser = indexPath.row
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UserTableViewCell")!
var label: UILabel
label = cell.viewWithTag(1) as! UILabel
label.text = users[indexPath.row].first_name + " " + users[indexPath.row].last_name
label = cell.viewWithTag(2) as! UILabel
label.text = users[indexPath.row].email
return cell
}
}
| mit | 9df45b339200e05e2421663a4db4dbb0 | 33.723577 | 122 | 0.62538 | 4.577706 | false | false | false | false |
prebid/prebid-mobile-ios | PrebidMobile/AdUnits/Native/NativeEventTracker.swift | 1 | 1847 | /* Copyright 2018-2019 Prebid.org, 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 UIKit
@objc public class NativeEventTracker: NSObject {
var event: EventType
var methods: Array<EventTracking>
var ext: AnyObject?
@objc
public init(event: EventType, methods: Array<EventTracking>) {
self.event = event
self.methods = methods
}
func getEventTracker() -> [AnyHashable: Any] {
var methodsList:[Int] = []
for method:EventTracking in methods {
methodsList.append(method.value)
}
let event = [
"event": self.event.value,
"methods": methodsList
] as [String : Any]
return event
}
}
public class EventType: SingleContainerInt {
@objc
public static let Impression = EventType(1)
@objc
public static let ViewableImpression50 = EventType(2)
@objc
public static let ViewableImpression100 = EventType(3)
@objc
public static let ViewableVideoImpression50 = EventType(4)
@objc
public static let Custom = EventType(500)
}
public class EventTracking: SingleContainerInt {
@objc
public static let Image = EventTracking(1)
@objc
public static let js = EventTracking(2)
@objc
public static let Custom = EventTracking(500)
}
| apache-2.0 | 90bc0244de3afae68693cf83cc7a595f | 24.30137 | 72 | 0.6719 | 4.408115 | false | false | false | false |
andrewcar/hoods | Project/hoods/hoods/Reachability.swift | 2 | 11090 | /*
Copyright (c) 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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 SystemConfiguration
import Foundation
public enum ReachabilityError: Error {
case FailedToCreateWithAddress(sockaddr_in)
case FailedToCreateWithHostname(String)
case UnableToSetCallback
case UnableToSetDispatchQueue
}
@available(*, unavailable, renamed: "Notification.Name.reachabilityChanged")
public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification")
extension Notification.Name {
public static let reachabilityChanged = Notification.Name("reachabilityChanged")
}
func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
guard let info = info else { return }
let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
reachability.reachabilityChanged()
}
public class Reachability {
public typealias NetworkReachable = (Reachability) -> ()
public typealias NetworkUnreachable = (Reachability) -> ()
@available(*, unavailable, renamed: "Conection")
public enum NetworkStatus: CustomStringConvertible {
case notReachable, reachableViaWiFi, reachableViaWWAN
public var description: String {
switch self {
case .reachableViaWWAN: return "Cellular"
case .reachableViaWiFi: return "WiFi"
case .notReachable: return "No Connection"
}
}
}
public enum Connection: CustomStringConvertible {
case none, wifi, cellular
public var description: String {
switch self {
case .cellular: return "Cellular"
case .wifi: return "WiFi"
case .none: return "No Connection"
}
}
}
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUnreachable?
@available(*, deprecated: 4.0, renamed: "allowsCellularConnection")
public let reachableOnWWAN: Bool = true
/// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`)
public var allowsCellularConnection: Bool
// The notification center on which "reachability changed" events are being posted
public var notificationCenter: NotificationCenter = NotificationCenter.default
@available(*, deprecated: 4.0, renamed: "connection.description")
public var currentReachabilityString: String {
return "\(connection)"
}
@available(*, unavailable, renamed: "connection")
public var currentReachabilityStatus: Connection {
return connection
}
public var connection: Connection {
guard isReachableFlagSet else { return .none }
// If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
guard isRunningOnDevice else { return .wifi }
var connection = Connection.none
if !isConnectionRequiredFlagSet {
connection = .wifi
}
if isConnectionOnTrafficOrDemandFlagSet {
if !isInterventionRequiredFlagSet {
connection = .wifi
}
}
if isOnWWANFlagSet {
if !allowsCellularConnection {
connection = .none
} else {
connection = .cellular
}
}
return connection
}
fileprivate var previousFlags: SCNetworkReachabilityFlags?
fileprivate var isRunningOnDevice: Bool = {
#if targetEnvironment(simulator)
return false
#else
return true
#endif
}()
fileprivate var notifierRunning = false
fileprivate let reachabilityRef: SCNetworkReachability
fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability")
required public init(reachabilityRef: SCNetworkReachability) {
allowsCellularConnection = true
self.reachabilityRef = reachabilityRef
}
public convenience init?(hostname: String) {
guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil }
self.init(reachabilityRef: ref)
}
public convenience init?() {
var zeroAddress = sockaddr()
zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
zeroAddress.sa_family = sa_family_t(AF_INET)
guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil }
self.init(reachabilityRef: ref)
}
deinit {
stopNotifier()
}
}
public extension Reachability {
// MARK: - *** Notifier methods ***
func startNotifier() throws {
guard !notifierRunning else { return }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque())
if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
stopNotifier()
throw ReachabilityError.UnableToSetCallback
}
if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
stopNotifier()
throw ReachabilityError.UnableToSetDispatchQueue
}
// Perform an initial check
reachabilitySerialQueue.async {
self.reachabilityChanged()
}
notifierRunning = true
}
func stopNotifier() {
defer { notifierRunning = false }
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
}
// MARK: - *** Connection test methods ***
@available(*, deprecated: 4.0, message: "Please use `connection != .none`")
var isReachable: Bool {
guard isReachableFlagSet else { return false }
if isConnectionRequiredAndTransientFlagSet {
return false
}
if isRunningOnDevice {
if isOnWWANFlagSet && !reachableOnWWAN {
// We don't want to connect when on cellular connection
return false
}
}
return true
}
@available(*, deprecated: 4.0, message: "Please use `connection == .cellular`")
var isReachableViaWWAN: Bool {
// Check we're not on the simulator, we're REACHABLE and check we're on WWAN
return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet
}
@available(*, deprecated: 4.0, message: "Please use `connection == .wifi`")
var isReachableViaWiFi: Bool {
// Check we're reachable
guard isReachableFlagSet else { return false }
// If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
guard isRunningOnDevice else { return true }
// Check we're NOT on WWAN
return !isOnWWANFlagSet
}
var description: String {
let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X"
let R = isReachableFlagSet ? "R" : "-"
let c = isConnectionRequiredFlagSet ? "c" : "-"
let t = isTransientConnectionFlagSet ? "t" : "-"
let i = isInterventionRequiredFlagSet ? "i" : "-"
let C = isConnectionOnTrafficFlagSet ? "C" : "-"
let D = isConnectionOnDemandFlagSet ? "D" : "-"
let l = isLocalAddressFlagSet ? "l" : "-"
let d = isDirectFlagSet ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
}
fileprivate extension Reachability {
func reachabilityChanged() {
guard previousFlags != flags else { return }
let block = connection != .none ? whenReachable : whenUnreachable
DispatchQueue.main.async {
block?(self)
self.notificationCenter.post(name: .reachabilityChanged, object:self)
}
previousFlags = flags
}
var isOnWWANFlagSet: Bool {
#if os(iOS)
return flags.contains(.isWWAN)
#else
return false
#endif
}
var isReachableFlagSet: Bool {
return flags.contains(.reachable)
}
var isConnectionRequiredFlagSet: Bool {
return flags.contains(.connectionRequired)
}
var isInterventionRequiredFlagSet: Bool {
return flags.contains(.interventionRequired)
}
var isConnectionOnTrafficFlagSet: Bool {
return flags.contains(.connectionOnTraffic)
}
var isConnectionOnDemandFlagSet: Bool {
return flags.contains(.connectionOnDemand)
}
var isConnectionOnTrafficOrDemandFlagSet: Bool {
return !flags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
}
var isTransientConnectionFlagSet: Bool {
return flags.contains(.transientConnection)
}
var isLocalAddressFlagSet: Bool {
return flags.contains(.isLocalAddress)
}
var isDirectFlagSet: Bool {
return flags.contains(.isDirect)
}
var isConnectionRequiredAndTransientFlagSet: Bool {
return flags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
}
var flags: SCNetworkReachabilityFlags {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(reachabilityRef, &flags) {
return flags
} else {
return SCNetworkReachabilityFlags()
}
}
}
| mit | 194e840e170a05b4744f2e3f354f2d7e | 33.440994 | 125 | 0.649775 | 5.800209 | false | false | false | false |
orangeince/EtuGitLabBot | Sources/GitlabServant.swift | 1 | 2262 | import PerfectLib
typealias Dict = [String: Any]
class GitlabServant {
static let shared: GitlabServant = GitlabServant()
var feedStore: [Int: FeedPool] = [:]
func didReceived(message: String) {
guard let jsonDict = (try? message.jsonDecode()) as? [String: Any] else {
print("json parse failed!!: \(message)")
return
}
guard let taskType = jsonDict["object_kind"] as? String else {
print("object_kind 解析失败!")
return
}
switch taskType {
case "issue":
handleIssueTask(data: jsonDict)
case "merge_request":
break
case "note":
break
default:
break
}
}
func handleIssueTask(data: [String: Any]) {
guard var issueJson = data["object_attributes"] as? [String: Any] else {
print("object_attributed 解析失败")
return
}
if let user = data["user"] as? Dict {
issueJson["author_name"] = user["name"] as? String
}
if let project = data["project"] as? Dict,
let projectUrl = project["web_url"] as? String,
let issueId = issueJson["iid"] as? Int {
issueJson["web_url"] = projectUrl + "/issues/\(issueId)"
}
guard let issue = Issue(JSON: issueJson) else {
print("issue data 解析失败, object_attrs:\(issueJson)")
return
}
guard let pool = feedStore[issue.assigneeId] else {
//print("has not found the subscriber of the issue: \(issue)")
return
}
pool.issues.append(issue)
}
func activate(subscriber id: Int, filterLabel: String?) {
print("activate success: \(id)")
feedStore[id] = FeedPool()
}
func getFeedFor(subscriber id: Int) -> String {
guard let pool = feedStore[id] else {
return "{}"
}
//print(pool.issues)
guard !pool.issues.isEmpty else {
return "{}"
}
let jsonStrs = pool.issues.map{ $0.jsonStr }
pool.issues.removeAll()
return "[" + jsonStrs.joined(separator: ",") + "]"
}
}
| apache-2.0 | 36fbbf076611f2115161d9e193fe1b8c | 29.243243 | 81 | 0.522788 | 4.32882 | false | false | false | false |
Khrob/swiftracer | project/swiftracer/swiftracer/ViewController.swift | 1 | 1525 | //
// ViewController.swift
// swiftracer
//
// Created by Khrob Edmonds on 6/10/2015.
// Copyright © 2015 khrob. All rights reserved.
//
import Cocoa
class ViewController: NSViewController
{
@IBOutlet weak var image: BackgroundImage!
@IBOutlet weak var xSlider: NSSlider!
@IBOutlet weak var ySlider: NSSlider!
@IBOutlet weak var zSlider: NSSlider!
@IBOutlet weak var distanceSlider: NSSlider!
let width = 400
let height = 300
@IBAction func uiChanged(sender: AnyObject)
{
print ("Redrawing (\(xSlider.doubleValue),\(ySlider.doubleValue),\(zSlider.doubleValue)) \(distanceSlider.doubleValue)")
let rays = makeRays(width, height: height, origin: Vector(x:xSlider.doubleValue, y:ySlider.doubleValue, z:zSlider.doubleValue), distance: distanceSlider.doubleValue, fov: 90.0)
let buffer = simpleScene(Cornell, rays: rays, width: width, height: height)
//print (buffer)
let gradient = imageFromARGB32Bitmap (buffer, width:width, height:height)
image.image = gradient
}
override func viewDidLoad()
{
super.viewDidLoad()
uiChanged(self)
}
}
class TracerWindow : NSWindowController
{
override func windowDidLoad()
{
window?.title = ""
window?.titlebarAppearsTransparent = true
window?.movableByWindowBackground = true
}
}
class BackgroundImage: NSImageView
{
override var mouseDownCanMoveWindow:Bool {
get { return true }
}
}
| apache-2.0 | d16f5b8177a3df739a7da8221a45232b | 25.275862 | 184 | 0.66601 | 4.186813 | false | false | false | false |
Adlai-Holler/ReactiveArray | ReactiveArrayTests/ReactiveArraySpec.swift | 1 | 19029 | //
// ReactiveArraySpec.swift
// ReactiveArraySpec
//
// Created by Guido Marucci Blas on 6/29/15.
// Copyright (c) 2015 Wolox. All rights reserved.
//
import Quick
import Nimble
import ReactiveArray
import ReactiveCocoa
import Box
private func waitForOperation<T>(fromProducer producer: SignalProducer<Operation<T>, NoError>,
#when: () -> (),
onAppend: Box<T> -> () = { fail("Invalid operation type: .Append(\($0))") },
onInsert: (Box<T>, Int) -> () = { fail("Invalid operation type: .Insert(\($0), \($1.value))") },
onDelete: Int -> () = { fail("Invalid operation type: .Delete(\($0))") }) {
waitUntil { done in
producer |> start(next: { operation in
switch operation {
case .Append(let boxedValue):
onAppend(boxedValue)
case .Insert(let boxedValue, let index):
onInsert(boxedValue, index)
case .RemoveElement(let index):
onDelete(index)
}
done()
})
when()
}
}
private func waitForOperation<T>(fromSignal signal: Signal<Operation<T>, NoError>,
#when: () -> (),
onAppend: Box<T> -> () = { fail("Invalid operation type: .Append(\($0))") },
onInsert: (Box<T>, Int) -> () = { fail("Invalid operation type: .Insert(\($0), \($1.value))") },
onDelete: Int -> () = { fail("Invalid operation type: .Delete(\($0))") }) {
let producer = SignalProducer<Operation<T>, NoError> { (observer, disposable) in signal.observe(observer) }
waitForOperation(fromProducer: producer, when: when, onAppend: onAppend, onInsert: onInsert, onDelete: onDelete)
}
private func waitForOperation<T>(fromArray array: ReactiveArray<T>,
#when: () -> (),
onAppend: Box<T> -> () = { fail("Invalid operation type: .Append(\($0))") },
onInsert: (Box<T>, Int) -> () = { fail("Invalid operation type: .Insert(\($0), \($1.value))") },
onDelete: Int -> () = { fail("Invalid operation type: .Delete(\($0))") }) {
waitForOperation(fromSignal: array.signal, when: when, onAppend: onAppend, onInsert: onInsert, onDelete: onDelete)
}
class ReactiveArraySpec: QuickSpec {
override func spec() {
var array: ReactiveArray<Int>!
beforeEach {
array = ReactiveArray(elements: [1,2,3,4])
}
describe("#append") {
it("inserts the given element at the end of the array") {
array.append(5)
expect(array[array.count - 1]).to(equal(5))
}
it("increments the amount of elements in the array by one") {
let countBeforeAppend = array.count
array.append(5)
expect(array.count).to(equal(countBeforeAppend + 1))
}
it("signals an append operation") {
waitForOperation(
fromArray: array,
when: {
array.append(5)
},
onAppend: { boxedValue in
expect(boxedValue.value).to(equal(5))
}
)
}
}
describe("#insert") {
context("when there is a value at the given position") {
it("replaces the old value with the new one") {
array.insert(5, atIndex: 1)
expect(array[1]).to(equal(5))
}
it("signals an insert operation") {
waitForOperation(
fromArray: array,
when: {
array.insert(5, atIndex: 1)
},
onInsert: { (boxedValue, index) in
expect(boxedValue.value).to(equal(5))
expect(index).to(equal(1))
}
)
}
}
// TODO: Fix this case because this raises an exception that cannot
// be caught
// context("when the index is out of bounds") {
//
// it("raises an exception") {
// expect {
// array.insert(5, atIndex: array.count + 10)
// }.to(raiseException(named: "NSInternalInconsistencyException"))
// }
//
// }
}
describe("#removeAtIndex") {
it("removes the element at the given position") {
array.removeAtIndex(1)
expect(array.toArray()).to(equal([1,3,4]))
}
it("signals a delete operation") {
waitForOperation(
fromArray: array,
when: {
array.removeAtIndex(1)
},
onDelete: { index in
expect(index).to(equal(1))
}
)
}
}
describe("#[]") {
it("returns the element at the given position") {
expect(array[2]).to(equal(3))
}
}
describe("#[]=") {
context("when there is a value at the given position") {
it("replaces the old value with the new one") {
array[1] = 5
expect(array[1]).to(equal(5))
}
it("signals an insert operation") {
waitForOperation(
fromArray: array,
when: {
array[1] = 5
},
onInsert: { (boxedValue, index) in
expect(boxedValue.value).to(equal(5))
expect(index).to(equal(1))
}
)
}
}
}
describe("#mirror") {
var mirror: ReactiveArray<Int>!
beforeEach {
mirror = array.mirror { $0 + 10 }
}
it("returns a new reactive array that maps the values of the original array") {
expect(mirror.toArray()).to(equal([11, 12, 13, 14]))
}
context("when a insert is executed on the original array") {
it("signals a mapped insert operation") {
waitForOperation(
fromArray: mirror,
when: {
array[1] = 5
},
onInsert: { (boxedValue, index) in
expect(boxedValue.value).to(equal(15))
expect(index).to(equal(1))
}
)
}
}
context("when an append is executed on the original array") {
it("signals a mapped append operation") {
waitForOperation(
fromArray: mirror,
when: {
array.append(5)
},
onAppend: { boxedValue in
expect(boxedValue.value).to(equal(15))
}
)
}
}
context("when a delete is executed on the original array") {
it("signals a mapped delete operation") {
waitForOperation(
fromArray: mirror,
when: {
array.removeAtIndex(1)
},
onDelete: { index in
expect(index).to(equal(1))
}
)
}
}
}
describe("#producer") {
context("when the array has elements") {
it("signals an append operation for each stored element") {
waitUntil { done in
// This is needed to avoid a compiler error.
// Probably a Swift bug
// TODO: Check is this is still necessary in Swift 2.0
let internalDone = done
array.producer
|> take(array.count)
|> collect
|> start(next: { operations in
let expectedOperations: [Operation<Int>] = map(array) { Operation.Append(value: Box($0)) }
let result = operations == expectedOperations
expect(result).to(beTrue())
internalDone()
})
}
}
}
context("when an append operation is executed in the original array") {
it("forwards the operation") {
let a = ReactiveArray<Int>()
waitForOperation(
fromProducer: a.producer,
when: {
a.append(5)
},
onAppend: { boxedValue in
expect(boxedValue.value).to(equal(5))
}
)
}
}
context("when an insert operation is executed in the original array") {
it("forwards the operation") {
let a = ReactiveArray<Int>(elements: [1])
waitForOperation(
fromProducer: a.producer |> skip(1), // Skips the operation triggered due to the array not being empty
when: {
a.insert(5, atIndex: 0)
},
onInsert: { (boxedValue, index) in
expect(boxedValue.value).to(equal(5))
expect(index).to(equal(0))
}
)
}
}
context("when a delete operation is executed in the original array") {
it("forwards the operation") {
let a = ReactiveArray<Int>(elements: [1])
waitForOperation(
fromProducer: a.producer |> skip(1), // Skips the operation triggered due to the array not being empty
when: {
a.removeAtIndex(0)
},
onDelete: { index in
expect(index).to(equal(0))
}
)
}
}
}
describe("#signal") {
context("when an insert operation is executed") {
it("signals the operations") {
waitForOperation(
fromSignal: array.signal,
when: {
array.insert(5, atIndex: 1)
},
onInsert: { (boxedValue, index) in
expect(boxedValue.value).to(equal(5))
expect(index).to(equal(1))
}
)
}
}
context("when an append operation is executed") {
it("signals the operations") {
waitForOperation(
fromSignal: array.signal,
when: {
array.append(5)
},
onAppend: { boxedValue in
expect(boxedValue.value).to(equal(5))
}
)
}
}
context("when a delete operation is executed") {
it("signals the operations") {
waitForOperation(
fromSignal: array.signal,
when: {
array.removeAtIndex(1)
},
onDelete: { index in
expect(index).to(equal(1))
}
)
}
}
}
describe("observableCount") {
var countBeforeOperation: Int!
var producer: SignalProducer<Int, NoError>!
beforeEach {
countBeforeOperation = array.count
producer = array.observableCount.producer
}
it("returns the initial amount of elements in the array") {
producer.start(next: { count in
expect(count).to(equal(countBeforeOperation))
})
}
context("when an insert operation is executed") {
beforeEach {
producer = producer |> skip(1)
}
it("does not update the count") {
waitUntil { done in
producer
|> take(1)
|> collect
|> start(next: { counts in
expect(counts).to(equal([countBeforeOperation + 1]))
done()
})
array.insert(657, atIndex: 1)
array.append(656)
}
}
}
context("when an append operation is executed") {
beforeEach {
producer = producer |> skip(1)
}
it("updates the count") {
waitUntil { done in
producer |> start(next: { count in
expect(count).to(equal(countBeforeOperation + 1))
done()
})
array.append(656)
}
}
}
context("when a delete operation is executed") {
beforeEach {
producer = producer |> skip(1)
}
it("updates the count") {
waitUntil { done in
producer |> start(next: { count in
expect(count).to(equal(countBeforeOperation - 1))
done()
})
array.removeAtIndex(1)
}
}
}
}
describe("isEmpty") {
context("when the array is empty") {
it("returns true") {
expect(ReactiveArray<Int>().isEmpty).to(beTrue())
}
}
context("when the array is not empty") {
it("returns false") {
expect(array.isEmpty).to(beFalse())
}
}
}
describe("count") {
it("returns the amount of elements in the array") {
expect(array.count).to(equal(4))
}
}
describe("startIndex") {
context("when the array is not empty") {
it("returns the index of the first element") {
expect(array.startIndex).to(equal(0))
}
}
context("when the array is empty") {
beforeEach {
array = ReactiveArray<Int>()
}
it("returns the index of the first element") {
expect(array.startIndex).to(equal(0))
}
}
}
describe("endIndex") {
context("when the array is not empty") {
it("returns the index of the last element plus one") {
expect(array.endIndex).to(equal(array.count))
}
}
context("when the array is empty") {
beforeEach {
array = ReactiveArray<Int>()
}
it("returns zero") {
expect(array.startIndex).to(equal(0))
}
}
}
describe("first") {
it("returns the first element in the array") {
expect(array.first).to(equal(1))
}
}
describe("last") {
it("returns the last element in the array") {
expect(array.last).to(equal(4))
}
context("when the array is empty") {
beforeEach {
array = ReactiveArray<Int>()
}
it("returns .None") {
expect(array.last).to(beNil())
}
}
}
}
}
| mit | 9a60bbb81b25fcf6e2efe0d48978b885 | 31.922145 | 126 | 0.362079 | 6.364214 | false | false | false | false |
Rauleinstein/iSWAD | iSWAD/iSWAD/AppDelegate.swift | 1 | 4484 | //
// AppDelegate.swift
// iSWAD
//
// Created by Raul Alvarez on 16/05/16.
// Copyright © 2016 Raul Alvarez. All rights reserved.
//
import UIKit
import ReachabilitySwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
let defaults = NSUserDefaults.standardUserDefaults()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let defaults = NSUserDefaults.standardUserDefaults()
let reachability: Reachability
do {
reachability = try Reachability.reachabilityForInternetConnection()
} catch {
print("Unable to create Reachability")
return false
}
if !reachability.isReachable() {
defaults.setObject(nil, forKey: Constants.wsKey)
}
if (defaults.stringForKey(Constants.wsKey) == nil || defaults.stringForKey(Constants.wsKey) == "") {
self.window?.rootViewController?.performSegueWithIdentifier("showLogin", sender: self)
} else {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("CoursesView") as! UISplitViewController
let navigationController = vc.viewControllers[vc.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = vc.displayModeButtonItem()
self.window?.rootViewController = vc
let rightNavController = vc.viewControllers.last as! UINavigationController
let detailViewController = rightNavController.topViewController as! CoursesDetailViewController
let leftNavController = vc.viewControllers.first as! UINavigationController
let masterViewController = leftNavController.topViewController as! CoursesMasterViewController
masterViewController.getCourses()
sleep(1)
let firstCourse = masterViewController.coursesList.first
detailViewController.detailItem = firstCourse
detailViewController.configureView()
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
defaults.setBool(false, forKey: Constants.logged)
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? CoursesDetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| apache-2.0 | 11f11de70c7ae94d1c83e562aa293b32 | 45.216495 | 285 | 0.775374 | 5.534568 | false | false | false | false |
milseman/swift | test/DebugInfo/closure.swift | 18 | 793 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
func markUsed<T>(_ t: T) {}
func foldl1<T>(_ list: [T], _ function: (_ a: T, _ b: T) -> T) -> T {
assert(list.count > 1)
var accumulator = list[0]
for i in 1 ..< list.count {
accumulator = function(accumulator, list[i])
}
return accumulator
}
var a = [Int64](repeating: 0, count: 10)
for i in 0..<10 { a[i] = Int64(i) }
// A closure is not an artificial function (the last i32 0).
// CHECK: !DISubprogram({{.*}}linkageName: "_T07closures5Int64VAC_ACtcfU_",{{.*}} line: 20,{{.*}} scopeLine: 20,
// CHECK: !DILocalVariable(name: "$0", arg: 1{{.*}} line: [[@LINE+2]],
// CHECK: !DILocalVariable(name: "$1", arg: 2{{.*}} line: [[@LINE+1]],
var sum:Int64 = foldl1(a, { $0 + $1 })
markUsed(sum)
| apache-2.0 | 57b48950ff6a4aaf1544e605a16585bc | 36.761905 | 112 | 0.572509 | 2.947955 | false | false | false | false |
superk589/CGSSGuide | DereGuide/View/IndicatorTableView.swift | 2 | 1913 | //
// IndicatorTableView.swift
// DereGuide
//
// Created by zzk on 2017/6/3.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
class IndicatorTableView: UITableView {
let indicator = ScrollViewIndicator(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
lazy var debouncer: Debouncer = {
return Debouncer.init(interval: 3, callback: { [weak self] in
if self?.indicator.panGesture.state == .possible {
self?.indicator.hide()
} else {
self?.debouncer.call()
}
})
}()
override var sectionHeaderHeight: CGFloat {
set {
super.sectionHeaderHeight = newValue
indicator.insets.top = newValue
}
get {
return super.sectionHeaderHeight
}
}
override var sectionFooterHeight: CGFloat {
set {
super.sectionFooterHeight = newValue
indicator.insets.bottom = newValue
}
get {
return super.sectionFooterHeight
}
}
override var contentOffset: CGPoint {
set {
super.contentOffset = newValue
debouncer.call()
indicator.adjustFrameInScrollView()
}
get {
return super.contentOffset
}
}
@objc func handlePanGestureInside(_ pan: UIPanGestureRecognizer) {
if pan.state == .began {
indicator.show(to: self)
}
}
override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
showsVerticalScrollIndicator = false
delaysContentTouches = false
panGestureRecognizer.addTarget(self, action: #selector(handlePanGestureInside(_:)))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 45d1084c4bdfc52635f436ef3ca57bdf | 25.555556 | 91 | 0.573222 | 5.044855 | false | false | false | false |
tiggleric/CVCalendar | Pod/Classes/CVDate.swift | 1 | 1089 | //
// CVDate.swift
// CVCalendar
//
// Created by Мак-ПК on 12/31/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
class CVDate: NSObject {
private let date: NSDate?
var year: Int?
var month: Int?
var week: Int?
var day: Int?
init(date: NSDate) {
let calendarManager = CVCalendarManager.sharedManager
self.date = date
self.year = calendarManager.dateRange(date).year
self.month = calendarManager.dateRange(date).month
self.day = calendarManager.dateRange(date).day
super.init()
}
init(day: Int, month: Int, week: Int, year: Int) {
self.year = year
self.month = month
self.week = week
self.day = day
self.date = NSDate()
super.init()
}
func dateDescription() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM"
let month = dateFormatter.stringFromDate(self.date!)
return "\(month), \(self.year!)"
}
}
| mit | eba8511b3fbd56b774d399cf8b3035aa | 22.565217 | 61 | 0.573801 | 4.185328 | false | false | false | false |
mactive/rw-courses-note | SwiftUIGames/TunOffLight/TunOffLight/ContentView.swift | 1 | 2973 | //
// ContentView.swift
// TunOffLight
//
// Created by Qian Meng on 2020/3/17.
// Copyright © 2020 meng. All rights reserved.
//
import SwiftUI
struct Light{
// 开关状态
var status: Bool = Bool.random()
}
struct ContentView: View {
@State var lights = [
[Light(), Light(), Light()],
[Light(), Light(), Light()],
[Light(), Light(), Light()],
]
var body: some View {
VStack{
ForEach(0..<lights.count) { rowIndex in
HStack(spacing: 20) {
ForEach(0..<self.lights[rowIndex].count) { columnIndex in
Circle()
.foregroundColor(self.lights[rowIndex][columnIndex].status ? .yellow : .gray)
.opacity(self.lights[rowIndex][columnIndex].status ? 0.8 : 0.5)
.frame(width: UIScreen.main.bounds.width / 5,
height: UIScreen.main.bounds.width / 5)
.shadow(color: .yellow, radius: self.lights[rowIndex][columnIndex].status ? 10 : 0)
.onTapGesture {
self.updateLightStatus(row: rowIndex, column: columnIndex)
}
}
}
.padding(EdgeInsets(top: 0, leading: 0, bottom: 20, trailing: 0))
}
Button(action: {
print("Delete tapped!")
self.refreshLights()
}) {
HStack {
Image(systemName: "goforward")
.font(.title)
Text("Refresh")
.fontWeight(.semibold)
.font(.title)
}
.padding()
.foregroundColor(.white)
.background(Color.red)
.cornerRadius(40)
}
}
}
func refreshLights() {
lights = [
[Light(), Light(), Light()],
[Light(), Light(), Light()],
[Light(), Light(), Light()],
]
}
// 修改灯的状态
func updateLightStatus(row: Int, column: Int) {
// toggle self
lights[row][column].status.toggle()
// 上
let top = row - 1
if !(top < 0) {
lights[top][column].status.toggle()
}
// 下
let bottom = row + 1
if !(bottom > lights.count - 1) {
lights[bottom][column].status.toggle()
}
// 左
let left = column - 1
if !(left < 0) {
lights[row][left].status.toggle()
}
// 右
let right = column + 1
if !(right > lights[row].count - 1) {
lights[row][right].status.toggle()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| mit | f43c28d3e38e7ef841051eecff506da8 | 27.307692 | 107 | 0.439878 | 4.717949 | false | false | false | false |
Romdeau4/16POOPS | iOS_app/Help's Kitchen/TableInfoViewController.swift | 1 | 1386 | //
// TableInfoViewController.swift
// Help's Kitchen
//
// Created by Stephen Ulmer on 2/23/17.
// Copyright © 2017 Stephen Ulmer. All rights reserved.
//
import UIKit
import Firebase
class TableInfoViewController: UIViewController {
let ref = FIRDatabase.database().reference(fromURL: "https://helps-kitchen.firebaseio.com/")
var table: Table?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Tables"
self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : CustomColor.amber500]
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(handleCancel))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Ready", style: .plain, target: self, action: #selector(handleReady))
// Do any additional setup after loading the view.
}
func handleCancel() {
dismiss(animated: true, completion: nil)
}
func handleReady() {
ref.child("tables").child((table?.key)!).child("tableStatus").setValue("available")
dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | a7718c39e6a8e2b9c3eaaba003894f84 | 30.477273 | 137 | 0.673646 | 4.859649 | false | false | false | false |
zhuhaow/NEKit | src/IPStack/Packet/PacketProtocolParser.swift | 2 | 2207 | import Foundation
protocol TransportProtocolParserProtocol {
var packetData: Data! { get set }
var offset: Int { get set }
var bytesLength: Int { get }
var payload: Data! { get set }
func buildSegment(_ pseudoHeaderChecksum: UInt32)
}
/// Parser to process UDP packet and build packet.
class UDPProtocolParser: TransportProtocolParserProtocol {
/// The source port.
var sourcePort: Port!
/// The destination port.
var destinationPort: Port!
/// The data containing the UDP segment.
var packetData: Data!
/// The offset of the UDP segment in the `packetData`.
var offset: Int = 0
/// The payload to be encapsulated.
var payload: Data!
/// The length of the UDP segment.
var bytesLength: Int {
return payload.count + 8
}
init() {}
init?(packetData: Data, offset: Int) {
guard packetData.count >= offset + 8 else {
return nil
}
self.packetData = packetData
self.offset = offset
sourcePort = Port(bytesInNetworkOrder: (packetData as NSData).bytes.advanced(by: offset))
destinationPort = Port(bytesInNetworkOrder: (packetData as NSData).bytes.advanced(by: offset + 2))
payload = packetData.subdata(in: offset+8..<packetData.count)
}
func buildSegment(_ pseudoHeaderChecksum: UInt32) {
sourcePort.withUnsafeBufferPointer {
self.packetData.replaceSubrange(offset..<offset+2, with: $0)
}
destinationPort.withUnsafeBufferPointer {
self.packetData.replaceSubrange(offset+2..<offset+4, with: $0)
}
var length = NSSwapHostShortToBig(UInt16(bytesLength))
withUnsafeBytes(of: &length) {
packetData.replaceSubrange(offset+4..<offset+6, with: $0)
}
packetData.replaceSubrange(offset+8..<offset+8+payload.count, with: payload)
packetData.resetBytes(in: offset+6..<offset+8)
var checksum = Checksum.computeChecksum(packetData, from: offset, to: nil, withPseudoHeaderChecksum: pseudoHeaderChecksum)
withUnsafeBytes(of: &checksum) {
packetData.replaceSubrange(offset+6..<offset+8, with: $0)
}
}
}
| bsd-3-clause | fb82b77c140f8191374cb972fb859689 | 29.652778 | 130 | 0.651563 | 4.244231 | false | false | false | false |
maml/SVGPlayButton | Example/SVGPlayButton/ViewController.swift | 1 | 2188 | //
// ViewController.swift
// SVGPlayButton
//
// Created by Matthew Loseke on 10/02/2015.
// Copyright (c) 2015 Matthew Loseke. All rights reserved.
//
import UIKit
import SVGPlayButton
class ViewController: UIViewController {
@IBOutlet weak var progressButton: SVGPlayButton!
@IBOutlet weak var resizeSlider: UISlider!
var tickCount: Int = 0
var totalCount: Int = 240
var timer: NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
self.progressButton.willPlay = { self.progressButtonWillPlayHandler() }
self.progressButton.willPause = { self.progressButtonWillPauseHandler() }
self.resizeSlider.addTarget(self, action: "slideDragHandler:", forControlEvents: UIControlEvents.ValueChanged)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
print("!!! MEMORY WARNING !!!")
print("this controller has received a memory warning and should dispose of any resources that can be recreated")
}
func tickHandler() {
self.progressButton.progressStrokeEnd = CGFloat(tickCount) / CGFloat(totalCount)
if self.progressButton.progressStrokeEnd == 1.0 {
tickCount = 0
self.progressButton.resetProgressLayer()
}
tickCount++
}
func progressButtonWillPlayHandler() {
//
// If there is already timer, start it.
// If there is NOT already a timer, create one and then start it.
//
if let timer = self.timer {
timer.fire()
} else {
self.timer = NSTimer.scheduledTimerWithTimeInterval(0.01666, target: self, selector: "tickHandler", userInfo: nil, repeats: true)
}
}
func progressButtonWillPauseHandler() {
if let timer = self.timer {
timer.invalidate()
self.timer = nil
}
}
func slideDragHandler(sender: UISlider) {
let val = CGFloat(sender.value)
progressButton.transform = CGAffineTransformMakeScale(val, val);
progressButton.setNeedsDisplay()
}
}
| mit | 0ed1089f20df5b498a11cb64b2dd3bdd | 28.173333 | 141 | 0.625686 | 4.777293 | false | false | false | false |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/Quick/Sources/Quick/World.swift | 49 | 8278 | import Foundation
/**
A closure that, when evaluated, returns a dictionary of key-value
pairs that can be accessed from within a group of shared examples.
*/
public typealias SharedExampleContext = () -> (NSDictionary)
/**
A closure that is used to define a group of shared examples. This
closure may contain any number of example and example groups.
*/
public typealias SharedExampleClosure = (SharedExampleContext) -> ()
/**
A collection of state Quick builds up in order to work its magic.
World is primarily responsible for maintaining a mapping of QuickSpec
classes to root example groups for those classes.
It also maintains a mapping of shared example names to shared
example closures.
You may configure how Quick behaves by calling the -[World configure:]
method from within an overridden +[QuickConfiguration configure:] method.
*/
final internal class World: NSObject {
/**
The example group that is currently being run.
The DSL requires that this group is correctly set in order to build a
correct hierarchy of example groups and their examples.
*/
internal var currentExampleGroup: ExampleGroup!
/**
The example metadata of the test that is currently being run.
This is useful for using the Quick test metadata (like its name) at
runtime.
*/
internal var currentExampleMetadata: ExampleMetadata?
/**
A flag that indicates whether additional test suites are being run
within this test suite. This is only true within the context of Quick
functional tests.
*/
internal var isRunningAdditionalSuites = false
private var specs: Dictionary<String, ExampleGroup> = [:]
private var sharedExamples: [String: SharedExampleClosure] = [:]
private let configuration = Configuration()
private var isConfigurationFinalized = false
internal var exampleHooks: ExampleHooks {return configuration.exampleHooks }
internal var suiteHooks: SuiteHooks { return configuration.suiteHooks }
// MARK: Singleton Constructor
private override init() {}
static let sharedWorld = World()
// MARK: Public Interface
/**
Exposes the World's Configuration object within the scope of the closure
so that it may be configured. This method must not be called outside of
an overridden +[QuickConfiguration configure:] method.
- parameter closure: A closure that takes a Configuration object that can
be mutated to change Quick's behavior.
*/
internal func configure(closure: QuickConfigurer) {
assert(!isConfigurationFinalized,
"Quick cannot be configured outside of a +[QuickConfiguration configure:] method. You should not call -[World configure:] directly. Instead, subclass QuickConfiguration and override the +[QuickConfiguration configure:] method.")
closure(configuration: configuration)
}
/**
Finalizes the World's configuration.
Any subsequent calls to World.configure() will raise.
*/
internal func finalizeConfiguration() {
isConfigurationFinalized = true
}
/**
Returns an internally constructed root example group for the given
QuickSpec class.
A root example group with the description "root example group" is lazily
initialized for each QuickSpec class. This root example group wraps the
top level of a -[QuickSpec spec] method--it's thanks to this group that
users can define beforeEach and it closures at the top level, like so:
override func spec() {
// These belong to the root example group
beforeEach {}
it("is at the top level") {}
}
- parameter cls: The QuickSpec class for which to retrieve the root example group.
- returns: The root example group for the class.
*/
internal func rootExampleGroupForSpecClass(cls: AnyClass) -> ExampleGroup {
#if _runtime(_ObjC)
let name = NSStringFromClass(cls)
#else
let name = String(cls)
#endif
if let group = specs[name] {
return group
} else {
let group = ExampleGroup(
description: "root example group",
flags: [:],
isInternalRootExampleGroup: true
)
specs[name] = group
return group
}
}
/**
Returns all examples that should be run for a given spec class.
There are two filtering passes that occur when determining which examples should be run.
That is, these examples are the ones that are included by inclusion filters, and are
not excluded by exclusion filters.
- parameter specClass: The QuickSpec subclass for which examples are to be returned.
- returns: A list of examples to be run as test invocations.
*/
internal func examples(specClass: AnyClass) -> [Example] {
// 1. Grab all included examples.
let included = includedExamples
// 2. Grab the intersection of (a) examples for this spec, and (b) included examples.
let spec = rootExampleGroupForSpecClass(specClass).examples.filter { included.contains($0) }
// 3. Remove all excluded examples.
return spec.filter { example in
!self.configuration.exclusionFilters.reduce(false) { $0 || $1(example: example) }
}
}
#if _runtime(_ObjC)
@objc(examplesForSpecClass:)
private func objc_examples(specClass: AnyClass) -> [Example] {
return examples(specClass)
}
#endif
// MARK: Internal
internal func registerSharedExample(name: String, closure: SharedExampleClosure) {
raiseIfSharedExampleAlreadyRegistered(name)
sharedExamples[name] = closure
}
internal func sharedExample(name: String) -> SharedExampleClosure {
raiseIfSharedExampleNotRegistered(name)
return sharedExamples[name]!
}
internal var includedExampleCount: Int {
return includedExamples.count
}
internal var beforesCurrentlyExecuting: Bool {
let suiteBeforesExecuting = suiteHooks.phase == .BeforesExecuting
let exampleBeforesExecuting = exampleHooks.phase == .BeforesExecuting
var groupBeforesExecuting = false
if let runningExampleGroup = currentExampleMetadata?.example.group {
groupBeforesExecuting = runningExampleGroup.phase == .BeforesExecuting
}
return suiteBeforesExecuting || exampleBeforesExecuting || groupBeforesExecuting
}
internal var aftersCurrentlyExecuting: Bool {
let suiteAftersExecuting = suiteHooks.phase == .AftersExecuting
let exampleAftersExecuting = exampleHooks.phase == .AftersExecuting
var groupAftersExecuting = false
if let runningExampleGroup = currentExampleMetadata?.example.group {
groupAftersExecuting = runningExampleGroup.phase == .AftersExecuting
}
return suiteAftersExecuting || exampleAftersExecuting || groupAftersExecuting
}
private var allExamples: [Example] {
var all: [Example] = []
for (_, group) in specs {
group.walkDownExamples { all.append($0) }
}
return all
}
private var includedExamples: [Example] {
let all = allExamples
let included = all.filter { example in
return self.configuration.inclusionFilters.reduce(false) { $0 || $1(example: example) }
}
if included.isEmpty && configuration.runAllWhenEverythingFiltered {
return all
} else {
return included
}
}
private func raiseIfSharedExampleAlreadyRegistered(name: String) {
if sharedExamples[name] != nil {
raiseError("A shared example named '\(name)' has already been registered.")
}
}
private func raiseIfSharedExampleNotRegistered(name: String) {
if sharedExamples[name] == nil {
raiseError("No shared example named '\(name)' has been registered. Registered shared examples: '\(Array(sharedExamples.keys))'")
}
}
}
| apache-2.0 | c81818d0e8cf563ec5d0f10eab265364 | 36.457014 | 243 | 0.664653 | 5.279337 | false | true | false | false |
samuelclay/NewsBlur | clients/ios/Classes/FeedsViewController.swift | 1 | 5290 | //
// FeedsViewController.swift
// NewsBlur
//
// Created by David Sinclair on 2020-08-27.
// Copyright © 2020 NewsBlur. All rights reserved.
//
import UIKit
import StoreKit
///Sidebar listing all of the feeds.
class FeedsViewController: FeedsObjCViewController {
struct Keys {
static let reviewDate = "datePromptedForReview"
static let reviewVersion = "versionPromptedForReview"
}
var appearCount = 0
lazy var appVersion: String = {
let infoDictionaryKey = kCFBundleVersionKey as String
guard let currentVersion = Bundle.main.object(forInfoDictionaryKey: infoDictionaryKey) as? String else {
fatalError("Expected to find a bundle version in the info dictionary")
}
return currentVersion
}()
var datePromptedForReview: Date {
get {
guard let date = UserDefaults.standard.object(forKey: Keys.reviewDate) as? Date else {
let date = Date()
UserDefaults.standard.set(date, forKey: Keys.reviewDate)
return date
}
return date
}
set {
UserDefaults.standard.set(newValue, forKey: Keys.reviewDate)
}
}
var versionPromptedForReview: String {
get {
return UserDefaults.standard.string(forKey: Keys.reviewVersion) ?? ""
}
set {
UserDefaults.standard.set(newValue, forKey: Keys.reviewVersion)
}
}
@objc func addSubfolderFeeds() {
for folderName in appDelegate.dictFoldersArray {
if let folderName = folderName as? String {
addSubfolderFeeds(for: folderName)
}
}
}
private func addSubfolderFeeds(for folderTitle: String) {
guard let parentTitle = self.parentTitle(for: folderTitle) else {
return
}
guard let childFeeds = appDelegate.dictFolders[folderTitle] as? [AnyObject],
let parentFeeds = appDelegate.dictFolders[parentTitle] as? [AnyObject] else {
return
}
let existingSubfolders = appDelegate.dictSubfolders[parentTitle] as? [AnyObject] ?? []
appDelegate.dictFolders[parentTitle] = parentFeeds + childFeeds
appDelegate.dictSubfolders[parentTitle] = existingSubfolders + childFeeds
addSubfolderFeeds(for: parentTitle)
}
@objc(parentTitleForFolderTitle:) func parentTitle(for folderTitle: String) -> String? {
guard let range = folderTitle.range(of: " ▸ ", options: .backwards) else {
return nil
}
return String(folderTitle[..<range.lowerBound])
}
@objc(parentTitlesForFolderTitle:) func parentTitles(for folderTitle: String) -> [String] {
var parentTitles = [String]()
guard let parentTitle = parentTitle(for: folderTitle) else {
return []
}
parentTitles.append(parentTitle)
parentTitles += self.parentTitles(for: parentTitle)
return parentTitles
}
var loadWorkItem: DispatchWorkItem?
@objc func loadNotificationStory() {
loadWorkItem?.cancel()
let workItem = DispatchWorkItem { [weak self] in
guard let self else {
return
}
self.appDelegate.backgroundLoadNotificationStory()
}
loadWorkItem = workItem
DispatchQueue.main.asyncAfter(deadline: .now() + (isOffline ? .seconds(1) : .milliseconds(100)), execute: workItem)
}
var reloadWorkItem: DispatchWorkItem?
@objc func deferredUpdateFeedTitlesTable() {
reloadWorkItem?.cancel()
let workItem = DispatchWorkItem { [weak self] in
guard let self else {
return
}
self.updateFeedTitlesTable()
self.refreshHeaderCounts()
}
reloadWorkItem = workItem
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: workItem)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
appearCount += 1
let month: TimeInterval = 60 * 60 * 24 * 30
let promptedDate = datePromptedForReview
let currentVersion = appVersion
let promptedVersion = versionPromptedForReview
// We only get a few prompts per year, so only ask for a review if gone back to the Feeds list several times, it's been at least a month since the last prompt, and it's a different version.
if appearCount >= 5, -promptedDate.timeIntervalSinceNow > month, currentVersion != promptedVersion, let scene = view.window?.windowScene {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [navigationController] in
if navigationController?.topViewController is FeedsViewController {
SKStoreReviewController.requestReview(in: scene)
self.datePromptedForReview = Date()
self.versionPromptedForReview = currentVersion
}
}
}
}
}
| mit | 408ffb971beaea495ed191148d925618 | 32.462025 | 197 | 0.60053 | 5.13301 | false | false | false | false |
wowiwj/Yeep | Yeep/Yeep/ViewControllers/Login/LoginVerifyMobileViewController.swift | 1 | 8161 | //
// LoginVerifyMobileViewController.swift
// Yeep
//
// Created by wangju on 16/7/20.
// Copyright © 2016年 wangju. All rights reserved.
//
import UIKit
import Ruler
class LoginVerifyMobileViewController: UIViewController {
var mobile: String!
var areaCode: String!
@IBOutlet private weak var verifyMobileNumberPromptLabel: UILabel!
@IBOutlet private weak var verifyMobileNumberPromptLabelTopConstraint: NSLayoutConstraint!
@IBOutlet private weak var phoneNumberLabel: UILabel!
@IBOutlet private weak var verifyCodeTextField: BorderTextField!
@IBOutlet private weak var verifyCodeTextFieldTopConstraint: NSLayoutConstraint!
@IBOutlet private weak var callMePromptLabel: UILabel!
@IBOutlet private weak var callMeButton: UIButton!
@IBOutlet private weak var callMeButtonTopConstraint: NSLayoutConstraint!
private lazy var nextButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: NSLocalizedString("Next", comment: ""), style: .Plain, target: self, action: #selector(LoginVerifyMobileViewController.next(_:)))
return button
}()
private lazy var callMeTimer: NSTimer = {
let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(LoginVerifyMobileViewController.tryCallMe(_:)), userInfo: nil, repeats: true)
return timer
}()
private var haveAppropriateInput = false {
willSet {
nextButton.enabled = newValue
if newValue {
login()
}
}
}
private var callMeInSeconds = YeepConfig.callMeInSeconds()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.yeepViewBackgroundColor()
navigationItem.titleView = NavigationTitleLabel(title: NSLocalizedString("Login", comment: ""))
navigationItem.rightBarButtonItem = nextButton
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginVerifyMobileViewController.activeAgain(_:)), name: AppDelegate.Notification.applicationDidBecomeActive, object: nil)
verifyMobileNumberPromptLabel.text = NSLocalizedString("Input verification code sent to", comment: "")
phoneNumberLabel.text = "+" + areaCode + " " + mobile
verifyCodeTextField.placeholder = " "
verifyCodeTextField.backgroundColor = UIColor.whiteColor()
verifyCodeTextField.textColor = UIColor.yeepInputTextColor()
verifyCodeTextField.delegate = self
verifyCodeTextField.addTarget(self, action: #selector(LoginVerifyMobileViewController.textFieldDidChange(_:)), forControlEvents: .EditingChanged)
callMePromptLabel.text = NSLocalizedString("Didn't get it?", comment: "")
callMeButton.setTitle(NSLocalizedString("Call me", comment: ""), forState: .Normal)
verifyMobileNumberPromptLabelTopConstraint.constant = Ruler.iPhoneVertical(30, 50, 60, 60).value
verifyCodeTextFieldTopConstraint.constant = Ruler.iPhoneVertical(30, 40, 50, 50).value
callMeButtonTopConstraint.constant = Ruler.iPhoneVertical(10, 20, 40, 40).value
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
nextButton.enabled = false
callMeButton.enabled = false
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
verifyCodeTextField.becomeFirstResponder()
callMeTimer.fire()
}
// MARK: - 用户事件的监听
@objc private func activeAgain(notification: NSNotification) {
verifyCodeTextField.becomeFirstResponder()
}
@objc private func next(sender: UIBarButtonItem) {
login()
}
private func login() {
view.endEditing(true)
guard let verifyCode = verifyCodeTextField.text else {
return
}
YepHUD.showActivityIndicator()
loginByMobile(mobile, withAreaCode: areaCode, verifyCode: verifyCode, failureHandler: {[unowned self] (reason, errorMessage) in
if let errorMessage = errorMessage {
dispatch_async(dispatch_get_main_queue()) {
self.nextButton.enabled = false
}
YepHUD.hideActivityIndicator()
YeepAlert.alertSorry(message: errorMessage, inViewController: self, withDismissAction: {
dispatch_async(dispatch_get_main_queue()) {
self.verifyCodeTextField.becomeFirstResponder()
}
})
}
}) { loginUser in
YepHUD.hideActivityIndicator()
dispatch_async(dispatch_get_main_queue(), {
saveTokenAndUserInfoOfLoginUser(loginUser)
syncMyInfoAndDoFurtherAction {
}
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
appDelegate.startMainStory()
}
})
}
}
@IBAction private func callMe(sender: UIButton) {
callMeTimer.invalidate()
UIView.performWithoutAnimation {
self.callMeButton.setTitle(NSLocalizedString("Calling", comment: ""), forState: .Normal)
self.callMeButton.layoutIfNeeded()
}
delay(5) {
UIView.performWithoutAnimation {
self.callMeButton.setTitle(NSLocalizedString("Call me", comment: ""), forState: .Normal)
self.callMeButton.layoutIfNeeded()
}
}
sendVerifyCodeOfMobile(mobile, withAreaCode: areaCode, useMethod: .Call, failureHandler: { [weak self] reason, errorMessage in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
if let errorMessage = errorMessage {
YeepAlert.alertSorry(message: errorMessage, inViewController: self)
dispatch_async(dispatch_get_main_queue()) {
UIView.performWithoutAnimation {
self?.callMeButton.setTitle(NSLocalizedString("Call me", comment: ""), forState: .Normal)
self?.callMeButton.layoutIfNeeded()
}
}
}
}, completion: { success in
print("resendVoiceVerifyCode \(success)")
})
}
@objc private func tryCallMe(timer: NSTimer) {
if !haveAppropriateInput {
if callMeInSeconds > 1 {
let callMeInSecondsString = NSLocalizedString("Call me", comment: "") + " (\(callMeInSeconds))"
UIView.performWithoutAnimation {
self.callMeButton.setTitle(callMeInSecondsString, forState: .Normal)
self.callMeButton.layoutIfNeeded()
}
} else {
UIView.performWithoutAnimation {
self.callMeButton.setTitle(NSLocalizedString("Call me", comment: ""), forState: .Normal)
self.callMeButton.layoutIfNeeded()
}
callMeButton.enabled = true
}
}
if (callMeInSeconds > 1) {
callMeInSeconds -= 1
}
}
@objc private func textFieldDidChange(textField: UITextField) {
guard let text = textField.text else {
return
}
haveAppropriateInput = (text.characters.count == YeepConfig.verifyCodeLength())
}
}
extension LoginVerifyMobileViewController: UITextFieldDelegate {
}
| mit | 3c717ecfc2782e5053de2af3974fa5a0 | 34.255411 | 204 | 0.595408 | 5.812991 | false | false | false | false |
ManuelAurora/RxQuickbooksService | Example/Pods/OAuthSwift/Sources/OAuthSwiftURLHandlerType.swift | 2 | 5532 | //
// OAuthSwiftURLHandlerType.swift
// OAuthSwift
//
// Created by phimage on 11/05/15.
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(watchOS)
import WatchKit
#elseif os(OSX)
import AppKit
#endif
@objc public protocol OAuthSwiftURLHandlerType {
func handle(_ url: URL)
}
// MARK: Open externally
open class OAuthSwiftOpenURLExternally: OAuthSwiftURLHandlerType {
public static var sharedInstance: OAuthSwiftOpenURLExternally = OAuthSwiftOpenURLExternally()
@objc open func handle(_ url: URL) {
#if os(iOS) || os(tvOS)
#if !OAUTH_APP_EXTENSIONS
UIApplication.shared.openURL(url)
#endif
#elseif os(watchOS)
// WATCHOS: not implemented
#elseif os(OSX)
NSWorkspace.shared().open(url)
#endif
}
}
// MARK: Open SFSafariViewController
#if os(iOS)
import SafariServices
@available(iOS 9.0, *)
open class SafariURLHandler: NSObject, OAuthSwiftURLHandlerType, SFSafariViewControllerDelegate {
public typealias UITransion = (_ controller: SFSafariViewController, _ handler: SafariURLHandler) -> Void
open let oauthSwift: OAuthSwift
open var present: UITransion
open var dismiss: UITransion
// retains observers
var observers = [String: NSObjectProtocol]()
open var factory: (_ URL: URL) -> SFSafariViewController = {URL in
return SFSafariViewController(url: URL)
}
// delegates
open weak var delegate: SFSafariViewControllerDelegate?
// configure default presentation and dismissal code
open var animated: Bool = true
open var presentCompletion: (() -> Void)?
open var dismissCompletion: (() -> Void)?
open var delay: UInt32? = 1
// init
public init(viewController: UIViewController, oauthSwift: OAuthSwift) {
self.oauthSwift = oauthSwift
self.present = { controller, handler in
viewController.present(controller, animated: handler.animated, completion: handler.presentCompletion)
}
self.dismiss = { controller, handler in
viewController.dismiss(animated: handler.animated, completion: handler.dismissCompletion)
}
}
public init(present: @escaping UITransion, dismiss: @escaping UITransion, oauthSwift: OAuthSwift) {
self.oauthSwift = oauthSwift
self.present = present
self.dismiss = dismiss
}
@objc open func handle(_ url: URL) {
let controller = factory(url)
controller.delegate = self
// present controller in main thread
OAuthSwift.main { [weak self] in
guard let this = self else {
return
}
if let delay = this.delay { // sometimes safari show a blank view..
sleep(delay)
}
this.present(controller, this)
}
let key = UUID().uuidString
observers[key] = OAuthSwift.notificationCenter.addObserver(
forName: NSNotification.Name.OAuthSwiftHandleCallbackURL,
object: nil,
queue: OperationQueue.main,
using: { [weak self] _ in
guard let this = self else {
return
}
if let observer = this.observers[key] {
OAuthSwift.notificationCenter.removeObserver(observer)
this.observers.removeValue(forKey: key)
}
OAuthSwift.main {
this.dismiss(controller, this)
}
}
)
}
// Clear internal observers on authentification flow
open func clearObservers() {
clearLocalObservers()
self.oauthSwift.removeCallbackNotificationObserver()
}
open func clearLocalObservers() {
for (_, observer) in observers {
OAuthSwift.notificationCenter.removeObserver(observer)
}
observers.removeAll()
}
// SFSafariViewControllerDelegate
public func safariViewController(_ controller: SFSafariViewController, activityItemsFor URL: Foundation.URL, title: String?) -> [UIActivity] {
return self.delegate?.safariViewController?(controller, activityItemsFor: URL, title: title) ?? []
}
public func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
// "Done" pressed
self.clearObservers()
self.delegate?.safariViewControllerDidFinish?(controller)
}
public func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
self.delegate?.safariViewController?(controller, didCompleteInitialLoad: didLoadSuccessfully)
}
}
#endif
// MARK: Open url using NSExtensionContext
open class ExtensionContextURLHandler: OAuthSwiftURLHandlerType {
fileprivate var extensionContext: NSExtensionContext
public init(extensionContext: NSExtensionContext) {
self.extensionContext = extensionContext
}
@objc open func handle(_ url: URL) {
extensionContext.open(url, completionHandler: nil)
}
}
| mit | 72313f6b18a3cc51e32ed89bbb7942d8 | 32.125749 | 150 | 0.609544 | 5.526474 | false | false | false | false |
michelf/sim-daltonism | Mac App/AppDelegate.swift | 1 | 2694 |
// Copyright 2005-2017 Michel Fortin
//
// 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 Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var filterWindowController: NSWindowController!
@IBOutlet var aboutItem: NSMenuItem!
func applicationWillFinishLaunching(_ notification: Notification) {
SimDaltonismFilter.registerDefaults()
}
func applicationDidFinishLaunching(_ notification: Notification) {
FilterWindowManager.shared.showFirstWindow()
ReviewPrompt.promptForReview(afterDelay: 2.3, minimumNumberOfLaunches: 10, minimumDaysSinceFirstLaunch: 6, minimumDaysSinceLastPrompt: 365)
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag {
FilterWindowManager.shared.showFirstWindow()
}
return false
}
@IBAction func createNewFilterWindow(_ sender: Any) {
FilterWindowManager.shared.createNewWindow().showWindow(nil)
}
@IBAction func adoptSpeedSetting(_ sender: NSMenuItem) {
guard let speed = RefreshSpeed(rawValue: sender.tag) else { return }
refreshSpeedDefault = speed
}
@IBAction func adoptViewAreaSetting(_ sender: NSMenuItem) {
guard let area = ViewArea(rawValue: sender.tag) else { return }
viewAreaDefault = area
}
@objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
switch menuItem.action! {
case #selector(adoptSpeedSetting(_:)):
menuItem.state = refreshSpeedDefault.rawValue == menuItem.tag ? .on : .off
return true
case #selector(adoptViewAreaSetting(_:)):
menuItem.state = viewAreaDefault.rawValue == menuItem.tag ? .on : .off
return true
default:
return self.responds(to: menuItem.action)
}
}
@IBAction func sendFeedback(_ sender: AnyObject) {
let mailtoURL = URL(string: "mailto:" + NSLocalizedString("[email protected]", tableName: "URLs", comment: "Sim Daltonism feedback email"))!
NSWorkspace.shared.open(mailtoURL)
}
@IBAction func openWebsite(_ sender: AnyObject) {
let websiteURL = URL(string: NSLocalizedString("https://michelf.ca/projects/sim-daltonism/", tableName: "URLs", comment: "Sim Daltonism website URL"))!
NSWorkspace.shared.open(websiteURL)
}
}
| apache-2.0 | 044c59b16f103e8f896b6c6e71f5b77c | 33.538462 | 153 | 0.755754 | 3.898698 | false | false | false | false |
imitationgame/pokemonpassport | pokepass/Model/Main/Transition/MMainTransitionPush.swift | 1 | 3231 | import UIKit
class MMainTransitionPush:MMainTransition
{
private let kAnimationDuration:TimeInterval = 0.5
let pushed:String
init(pushed:String)
{
self.pushed = pushed
super.init(animationDuration:kAnimationDuration)
}
override func positionBefore()
{
let width:CGFloat = current!.view.bounds.maxX
let barHeight:CGFloat = parent.kBarHeight
let shadow:VMainShadow = VMainShadow()
parent.layoutTopTemporal = NSLayoutConstraint(
item:next.view,
attribute:NSLayoutAttribute.top,
relatedBy:NSLayoutRelation.equal,
toItem:parent.view,
attribute:NSLayoutAttribute.top,
multiplier:1,
constant:barHeight)
parent.layoutBottomTemporal = NSLayoutConstraint(
item:next.view,
attribute:NSLayoutAttribute.bottom,
relatedBy:NSLayoutRelation.equal,
toItem:parent.view,
attribute:NSLayoutAttribute.bottom,
multiplier:1,
constant:0)
parent.layoutLeftTemporal = NSLayoutConstraint(
item:next.view,
attribute:NSLayoutAttribute.left,
relatedBy:NSLayoutRelation.equal,
toItem:parent.view,
attribute:NSLayoutAttribute.left,
multiplier:1,
constant:width)
parent.layoutRightTemporal = NSLayoutConstraint(
item:next.view,
attribute:NSLayoutAttribute.right,
relatedBy:NSLayoutRelation.equal,
toItem:parent.view,
attribute:NSLayoutAttribute.right,
multiplier:1,
constant:width)
parent.view.addConstraint(parent.layoutLeftTemporal!)
parent.view.addConstraint(parent.layoutRightTemporal!)
parent.view.addConstraint(parent.layoutTopTemporal!)
parent.view.addConstraint(parent.layoutBottomTemporal!)
parent.shadow = shadow
current?.view.addSubview(shadow)
let views:[String:AnyObject] = [
"shadow":shadow]
let metrics:[String:AnyObject] = [:]
current?.view.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[shadow]-0-|",
options:[],
metrics:metrics,
views:views))
current?.view.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[shadow]-0-|",
options:[],
metrics:metrics,
views:views))
}
override func animationBefore()
{
parent.view.layoutIfNeeded()
}
override func positionAfter()
{
let width:CGFloat = current!.view.bounds.maxX / -2.0
parent.layoutLeft!.constant = width
parent.layoutRight!.constant = width
parent.layoutLeftTemporal!.constant = 0
parent.layoutRightTemporal!.constant = 0
parent.bar?.pushed(name:pushed)
}
override func animationAfter()
{
parent.view.layoutIfNeeded()
parent.shadow?.alpha = 1
}
override func completed()
{
parent.previous = parent.current
}
}
| mit | 8569e52e66888bbb510b5559b3f947b4 | 30.368932 | 68 | 0.603219 | 5.236629 | false | false | false | false |
matsuda/MuddlerKit | MuddlerKit/UIViewController+Keyboard.swift | 1 | 6092 | //
// UIViewController+Keyboard.swift
// MuddlerKit
//
// Created by Kosuke Matsuda on 2016/12/29.
// Copyright © 2016年 Kosuke Matsuda. All rights reserved.
//
import UIKit
// MARK: - AssociatedKeys
private struct AssociatedKeys {
static var keyboardObservableScrollViewContentInset: UInt8 = 0
}
// MARK: - UIViewController
extension UIViewController {
private var keyboardObservableScrollViewContentInset: UIEdgeInsets {
if let value = objc_getAssociatedObject(self, &AssociatedKeys.keyboardObservableScrollViewContentInset) as? NSValue {
return value.uiEdgeInsetsValue
} else {
let value = keyboardObservableScrollView.contentInset
objc_setAssociatedObject(
self, &AssociatedKeys.keyboardObservableScrollViewContentInset,
NSValue(uiEdgeInsets: value), objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC
)
return value
}
}
public var keyboardObservableScrollView: UIScrollView {
fatalError("Should override \(#function)")
}
public func addObserverForKeyboardNotifications() {
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(keyboardWillShow(notification:)),
name: Notification.Name.UIKeyboardWillShow, object: nil)
nc.addObserver(self, selector: #selector(keyboardDidShow(notification:)),
name: Notification.Name.UIKeyboardDidShow, object: nil)
nc.addObserver(self, selector: #selector(keyboardWillHide(notification:)),
name: Notification.Name.UIKeyboardWillHide, object: nil)
nc.addObserver(self, selector: #selector(keyboardDidHide(notification:)),
name: Notification.Name.UIKeyboardDidHide, object: nil)
nc.addObserver(self, selector: #selector(keyboardWillChangeFrame(notification:)),
name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
nc.addObserver(self, selector: #selector(keyboardDidChangeFrame(notification:)),
name: Notification.Name.UIKeyboardDidChangeFrame, object: nil)
}
public func removeObserverForKeyboardNotifications() {
let nc = NotificationCenter.default
nc.removeObserver(self, name: Notification.Name.UIKeyboardWillShow, object: nil)
nc.removeObserver(self, name: Notification.Name.UIKeyboardDidShow, object: nil)
nc.removeObserver(self, name: Notification.Name.UIKeyboardWillHide, object: nil)
nc.removeObserver(self, name: Notification.Name.UIKeyboardDidHide, object: nil)
nc.removeObserver(self, name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
nc.removeObserver(self, name: Notification.Name.UIKeyboardDidChangeFrame, object: nil)
}
public func keyboardWillShow(notification: Notification) {
if let userInfo = notification.userInfo {
let window = UIApplication.shared.keyWindow
let keyboardEndFrameInScreen = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let keyboardEndFrameInWindow = window?.convert(keyboardEndFrameInScreen!, from: nil)
let keyboardEndFrameInView = view.convert(keyboardEndFrameInWindow!, from: nil)
let heightCoveredWithKeyboard = keyboardObservableScrollView.frame.maxY - keyboardEndFrameInView.minY
var insets = keyboardObservableScrollViewContentInset
insets.bottom = heightCoveredWithKeyboard
keyboardObservableScrollView.scrollConsideredKeyboard(insets: insets, givenUserInfo: userInfo)
if let responder = keyboardObservableScrollView.mk.firstResponder as? UIView {
let responderFrameInScrollView = responder.convert(responder.bounds,
to: keyboardObservableScrollView)
let keyboardEndFrameInScrollView = view.convert(keyboardEndFrameInView, to: keyboardObservableScrollView)
if responderFrameInScrollView.maxY > keyboardEndFrameInScrollView.minY {
keyboardObservableScrollView.scrollRectToVisible(responderFrameInScrollView, animated: true)
}
}
}
}
public func keyboardDidShow(notification: NSNotification) {
}
public func keyboardWillHide(notification: NSNotification) {
let insets = keyboardObservableScrollViewContentInset
keyboardObservableScrollView.scrollConsideredKeyboard(insets: insets, givenUserInfo: notification.userInfo)
}
public func keyboardDidHide(notification: NSNotification) {
}
public func keyboardWillChangeFrame(notification: NSNotification) {
}
public func keyboardDidChangeFrame(notification: NSNotification) {
}
}
// MARK: - UIScrollView
extension UIScrollView {
func scrollConsideredKeyboard(insets:UIEdgeInsets, givenUserInfo userInfo: [AnyHashable : Any]?) {
if let userInfo = userInfo {
let duration: TimeInterval
if let value = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber {
duration = value.doubleValue
} else {
duration = 0.25
}
let animationCurve: Int
if let value = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
animationCurve = value.intValue
} else {
animationCurve = UIViewAnimationCurve.easeInOut.rawValue
}
let animationOptions: UIViewAnimationOptions = UIViewAnimationOptions(rawValue: UInt(animationCurve << 16))
UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: {
self.contentInset = insets
self.scrollIndicatorInsets = insets
}, completion: { (finished) in
// completion
})
} else {
contentInset = insets
scrollIndicatorInsets = insets
}
}
}
| mit | 8f88834840bb71200f477a2f754f9cc2 | 44.103704 | 125 | 0.680243 | 5.934698 | false | false | false | false |
contentful/tvful | Code/ViewController.swift | 1 | 2815 | //
// ViewController.swift
// tvful
//
// Created by Boris Bügling on 10/09/15.
// Copyright © 2015 Boris Bügling. All rights reserved.
//
import ContentfulDeliveryAPI
import UIKit
class ImageCell: UICollectionViewCell {
static let identifier = NSStringFromClass(ImageCell.self)
let imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
imageView.contentMode = .ScaleAspectFit
imageView.frame = bounds
contentView.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("not implemented")
}
func loadAsset(asset: CDAAsset) {
let scale = UIScreen.mainScreen().scale
imageView.cda_setImageWithAsset(asset, size: CGSize(width: frame.size.width * scale, height: frame.size.height * scale))
}
}
class ViewController: UICollectionViewController {
static let AccessToken = "51910a9d4752a24728c44a8dc4422291305eed4c20000003b73d4a47475f1740"
static let SpaceId = "1qptv5yuwnfh"
let client = CDAClient(spaceKey: SpaceId, accessToken: AccessToken)
var assets: [CDAAsset] = []
override func viewDidLoad() {
super.viewDidLoad()
let flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = CGSize(width: 300, height: 300)
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
collectionView?.collectionViewLayout = flowLayout
collectionView?.registerClass(ImageCell.self, forCellWithReuseIdentifier: ImageCell.identifier)
client.fetchEntriesMatching(["content_type": "1xYw5JsIecuGE68mmGMg20"], success: { (_, entries) in
self.assets = entries.items.flatMap() { (entry) in
(entry.fields["photo"] as? CDAAsset)
}
self.collectionView?.reloadData()
}) { (_, error) in
print(error)
}
}
override func collectionView(collectionView: UICollectionView, canFocusItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ImageCell.identifier, forIndexPath: indexPath) as! ImageCell
cell.loadAsset(assets[indexPath.row])
//cell.performSelector("_whyIsThisViewNotFocusable")
return cell
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return assets.count
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
}
| mit | 1b29c1bee29a0eaa3fb7be5191e1ac9a | 33.716049 | 139 | 0.696657 | 4.766102 | false | false | false | false |
AlesTsurko/DNMKit | DNM_iOS/DNM_iOS/ButtonSwitchPanelWithMasterButtonSwitch.swift | 1 | 5692 | //
// ButtonSwitchPanelWithMasterButtonSwitch.swift
// denm_view
//
// Created by James Bean on 9/26/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
// DEPRECATE
/*
public class ButtonSwitchPanelWithMasterButtonSwitch: ButtonSwitchPanelWithID {
public var masterButtonSwitch: ButtonSwitchMaster!
public override init(
left: CGFloat,
top: CGFloat,
id: String,
target: AnyObject? = nil,
titles: [String] = []
)
{
super.init(left: left, top: top, id: id, target: target, titles: titles)
build()
}
public override init(frame: CGRect) { super.init(frame: frame) }
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
public override func build() {
addMasterButtonSwitchWithID()
commitButtonSwitches()
addTargetsToButtonSwitches()
layout()
setFrame()
setInitialStatesByTextByID()
}
public func commitButtonSwitches() {
for buttonSwitch in buttonSwitches { addSubview(buttonSwitch) }
}
public func addTargetsToButtonSwitches() {
for buttonSwitch in buttonSwitches {
buttonSwitch.addTarget(self,
action: "stateHasChangedFromSender:", forControlEvents: .TouchUpInside
)
}
}
public override func addButtonSwitchWithTitle(title: String) {
let buttonSwitch = ButtonSwitch(width: 110, height: 33, text: title, id: title) // id superfluous
buttonSwitchByID[buttonSwitch.text] = buttonSwitch
addButtonSwitch(buttonSwitch)
}
private func addMasterButtonSwitchWithID() {
masterButtonSwitch = ButtonSwitchMaster(width: 80, height: 33, text: id, id: "performer") // HACK
masterButtonSwitch.addTarget(self,
action: "stateChangedFromMasterButton:", forControlEvents: UIControlEvents.TouchUpInside
)
insertButtonSwitch(masterButtonSwitch, atIndex: 0)
}
public func stateChangedFromMasterButton(masterButton: ButtonSwitch) {
print("state has changed from masterButton: text: \(masterButton.text); id: \(masterButton.id); masterButton.isOn: \(masterButton.isOn)")
if masterButton.isOn {
for (id, buttonSwitch) in buttonSwitchByID {
if let rememberedState = rememberedStatesByText[buttonSwitch.text] {
if rememberedState {
buttonSwitch.switchOn()
statesByText[buttonSwitch.id] = true
}
else {
buttonSwitch.switchOff()
statesByText[buttonSwitch.id] = false
}
}
}
}
else {
setRememberedStates()
for buttonSwitch in buttonSwitches {
buttonSwitch.switchOff()
statesByText[buttonSwitch.id] = false
} // "mute"
}
//statesByText["performer"] = masterButton.isOn // HACK
print("statesByText: id \(id): \(statesByText)")
}
public override func stateHasChangedFromSender(sender: ButtonSwitch) {
print("state has changed from normal button: text: \(sender.text); id: \(sender.id); isOn: \(sender.isOn)")
statesByText[sender.id] = sender.isOn
print("statesByText: id: \(id): \(statesByText)")
// set value with state by text
// -- shown, hidden
if let superview = superview {
if let componentSelector = superview as? ComponentSelector {
componentSelector.stateHasChangedFromSender(self)
}
}
}
public func muteAllSwitches() {
// call this once "muting" exists
}
public override func layout() {
for (b, buttonSwitch) in buttonSwitches.enumerate() {
buttonSwitch.layer.position.y = pad + 0.5 * buttonSwitch.frame.height
if b == 0 {
buttonSwitch.layer.position.x = pad + 0.5 * buttonSwitch.frame.width
}
else {
let buttonSwitch_left = pad + buttonSwitches[b-1].frame.maxX
buttonSwitch.layer.position.x = buttonSwitch_left + 0.5 * buttonSwitch.frame.width
}
}
}
public func layout_flowLeft() {
for (b, buttonSwitch) in buttonSwitches.enumerate() {
buttonSwitch.layer.position.y = pad + 0.5 * buttonSwitch.frame.height
if b == 0 {
buttonSwitch.layer.position.x = pad + 0.5 * buttonSwitch.frame.width
}
else {
let buttonSwitch_left = pad + buttonSwitches[b-1].frame.maxX
buttonSwitch.layer.position.x = buttonSwitch_left + 0.5 * buttonSwitch.frame.width
}
}
}
public func layout_flowRight() {
for (b, buttonSwitch) in buttonSwitches.reverse().enumerate() {
buttonSwitch.layer.position.y = pad + 0.5 * buttonSwitch.frame.height
if b == 0 {
buttonSwitch.layer.position.x = pad + 0.5 * buttonSwitch.frame.width
}
else {
let buttonSwitch_left = pad + buttonSwitches[b-1].frame.maxX
buttonSwitch.layer.position.x = buttonSwitch_left + 0.5 * buttonSwitch.frame.width
}
}
}
/*
public override func build() {
addMasterButtonSwitchWithID()
layout()
setFrame()
setInitialStatesByTextByID()
}
*/
}
*/ | gpl-2.0 | b2bf0d4c697d76ffa4e209e5d91b75dd | 32.680473 | 145 | 0.577403 | 4.750417 | false | false | false | false |
easyui/SwiftMan | SwiftMan/Extension/Foundation/URL/URL+Man.swift | 1 | 3650 | //
// NSURL+Man.swift
// SwiftMan
//
// Created by yangjun on 16/5/4.
// Copyright © 2016年 yangjun. All rights reserved.
//
#if canImport(Foundation)
import Foundation
//#if canImport(UIKit) && canImport(AVFoundation)
//import UIKit
//import AVFoundation
//#endif
extension URL {
public var m_queryParameters: [String: String]? {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true), let queryItems = components.queryItems else {
return nil
}
var parameters = [String: String]()
for item in queryItems {
parameters[item.name] = item.value
}
return parameters
}
/// SwifterMan: URL with appending query parameters.
///
/// let url = URL(string: "https://google.com")!
/// let param = ["q": "Swifter Swift"]
/// url.appendingQueryParameters(params) -> "https://google.com?q=Swifter%20Swift"
///
/// - Parameter parameters: parameters dictionary.
/// - Returns: URL with appending given query parameters.
func appendingQueryParameters(_ parameters: [String: String]) -> URL {
var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true)!
var items = urlComponents.queryItems ?? []
items += parameters.map({ URLQueryItem(name: $0, value: $1) })
urlComponents.queryItems = items
return urlComponents.url!
}
/// SwifterMan: Append query parameters to URL.
///
/// var url = URL(string: "https://google.com")!
/// let param = ["q": "Swifter Swift"]
/// url.appendQueryParameters(params)
/// print(url) // prints "https://google.com?q=Swifter%20Swift"
///
/// - Parameter parameters: parameters dictionary.
mutating func appendQueryParameters(_ parameters: [String: String]) {
self = appendingQueryParameters(parameters)
}
/// SwifterMan: Get value of a query key.
///
/// var url = URL(string: "https://google.com?code=12345")!
/// queryValue(for: "code") -> "12345"
///
/// - Parameter key: The key of a query value.
func queryValue(for key: String) -> String? {
return URLComponents(string: absoluteString)?
.queryItems?
.first(where: { $0.name == key })?
.value
}
/*
#if os(iOS) || os(tvOS)
/// SwifterMan: Generate a thumbnail image from given url. Returns nil if no thumbnail could be created. This function may take some time to complete. It's recommended to dispatch the call if the thumbnail is not generated from a local resource.
///
/// var url = URL(string: "https://video.golem.de/files/1/1/20637/wrkw0718-sd.mp4")!
/// var thumbnail = url.thumbnail()
/// thumbnail = url.thumbnail(fromTime: 5)
///
/// DisptachQueue.main.async {
/// someImageView.image = url.thumbnail()
/// }
///
/// - Parameter time: Seconds into the video where the image should be generated.
/// - Returns: The UIImage result of the AVAssetImageGenerator
func thumbnail(fromTime time: Float64 = 0) -> UIImage? {
let imageGenerator = AVAssetImageGenerator(asset: AVAsset(url: self))
let time = CMTimeMakeWithSeconds(time, preferredTimescale: 1)
var actualTime = CMTimeMake(value: 0, timescale: 0)
guard let cgImage = try? imageGenerator.copyCGImage(at: time, actualTime: &actualTime) else {
return nil
}
return UIImage(cgImage: cgImage)
}
#endif
*/
}
#endif
| mit | 790a652ff465b72eae0b2daec7740aa5 | 34.754902 | 250 | 0.6068 | 4.36244 | false | false | false | false |
Bizzi-Body/ParseTutorialPart8---CompleteSolution | ParseTutorial/ViewController.swift | 1 | 7208 | //
// ViewController.swift
// ParseTutorial
//
// Created by Ian Bradbury on 23/06/2015.
// Copyright (c) 2015 bizzi-body. All rights reserved.
//
import UIKit
var countries = [PFObject]()
class CollectionView: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate {
@IBAction func addCountry(sender: AnyObject) {
performSegueWithIdentifier("CollectionViewToDetailView", sender: nil)
}
// Connection to the search bar
@IBOutlet weak var searchBar: UISearchBar!
// Connection to the collection view
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Wire up search bar delegate so that we can react to button selections
searchBar.delegate = self
// Resize size of collection view items in grid so that we achieve 3 boxes across
let cellWidth = ((UIScreen.mainScreen().bounds.width) - 32 - 30 ) / 3
let cellLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
cellLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)
}
/*
==========================================================================================
Ensure data within the collection view is updated when ever it is displayed
==========================================================================================
*/
// Load data into the collectionView when the view appears
override func viewDidAppear(animated: Bool) {
loadCollectionViewData()
}
/*
==========================================================================================
Fetch data from the Parse platform
==========================================================================================
*/
func loadCollectionViewData() {
// Build a parse query object
var query = PFQuery(className:"Countries")
// Check to see if there is a search term
if searchBar.text != "" {
query.whereKey("searchText", containsString: searchBar.text.lowercaseString)
}
// Fetch data from the parse platform
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
// The find succeeded now rocess the found objects into the countries array
if error == nil {
// Clear existing country data
countries.removeAll(keepCapacity: true)
// Add country objects to our array
if let objects = objects as? [PFObject] {
countries = Array(objects.generate())
}
// reload our data into the collection view
self.collectionView.reloadData()
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
}
/*
==========================================================================================
UICollectionView protocol required methods
==========================================================================================
*/
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return countries.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell
// Display the country name
if let value = countries[indexPath.row]["nameEnglish"] as? String {
cell.cellTitle.text = value
}
// Display "initial" flag image
var initialThumbnail = UIImage(named: "question")
cell.cellImage.image = initialThumbnail
// Fetch final flag image - if it exists
if let value = countries[indexPath.row]["flag"] as? PFFile {
let finalImage = countries[indexPath.row]["flag"] as? PFFile
finalImage!.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
cell.cellImage.image = UIImage(data:imageData)
}
}
}
}
return cell
}
/*
==========================================================================================
Segue methods
==========================================================================================
*/
// Process collectionView cell selection
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let currentObject = countries[indexPath.row]
performSegueWithIdentifier("CollectionViewToDetailView", sender: currentObject)
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// If a cell has been selected within the colleciton view - set currentObjact to selected
var currentObject : PFObject?
if let country = sender as? PFObject{
currentObject = sender as? PFObject
} else {
// No cell selected in collectionView - must be a new country record being created
currentObject = PFObject(className:"Countries")
}
// Get a handle on the next story board controller and set the currentObject ready for the viewDidLoad method
var detailScene = segue.destinationViewController as! DetailViewController
detailScene.currentObject = (currentObject)
}
/*
==========================================================================================
Process Search Bar interaction
==========================================================================================
*/
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Reload of table data
self.loadCollectionViewData()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Reload of table data
self.loadCollectionViewData()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// Clear any search criteria
searchBar.text = ""
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Reload of table data
self.loadCollectionViewData()
}
/*
==========================================================================================
Process memory issues
To be completed
==========================================================================================
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 8fe64bc5cbda9574734c83caf034d58a | 31.763636 | 127 | 0.591287 | 5.51492 | false | false | false | false |
futurist/cutecmd-mac | cutecmd-mac/AutoCompleteTextField.swift | 1 | 8048 | //
// AutoCompleteTextField.swift
// AutoCompleteTextFieldDemo
//
// Created by fancymax on 15/12/12.
// Copyright © 2015年 fancy. All rights reserved.
//
import Cocoa
@objc protocol AutoCompleteTableViewDelegate:NSObjectProtocol{
func textView(_ textView: NSTextView, completions words: [String], forPartialWordRange charRange: NSRange, indexOfSelectedItem index: UnsafeMutablePointer<Int>?) -> [String]
@objc optional func didSelectItem(_ selectedItem: String)
}
class AutoCompleteTableRowView:NSTableRowView{
override func drawSelection(in dirtyRect: NSRect) {
if self.selectionHighlightStyle != .none{
let selectionRect = NSInsetRect(self.bounds, 0.5, 0.5)
NSColor.selectedMenuItemColor.setStroke()
NSColor.selectedMenuItemColor.setFill()
let selectionPath = NSBezierPath(roundedRect: selectionRect, xRadius: 0.0, yRadius: 0.0)
selectionPath.fill()
selectionPath.stroke()
}
}
override var interiorBackgroundStyle:NSBackgroundStyle{
get{
if self.isSelected {
return NSBackgroundStyle.dark
}
else{
return NSBackgroundStyle.light
}
}
}
}
class AutoCompleteTextField:NSTextView{
weak var tableViewDelegate:AutoCompleteTableViewDelegate?
var popOverWidth:CGFloat = 200
let popOverPadding:CGFloat = 0.0
let maxResults = 10
var autoCompletePopover:NSPopover?
weak var autoCompleteTableView:NSTableView?
var matches:[String]?
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override init(frame frameRect: NSRect, textContainer container: NSTextContainer?) {
super.init(frame: frameRect, textContainer: container)
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
popOverWidth = frameRect.size.width
let column1 = NSTableColumn(identifier: "text")
column1.isEditable = false
column1.width = popOverWidth - 2 * popOverPadding
let tableView = NSTableView(frame: NSZeroRect)
tableView.selectionHighlightStyle = NSTableViewSelectionHighlightStyle.regular
tableView.backgroundColor = NSColor.clear
tableView.rowSizeStyle = NSTableViewRowSizeStyle.small
tableView.intercellSpacing = NSMakeSize(10.0, 0.0)
tableView.headerView = nil
tableView.refusesFirstResponder = true
tableView.target = self
tableView.doubleAction = #selector(AutoCompleteTextField.insert(_:))
tableView.addTableColumn(column1)
tableView.delegate = self
tableView.dataSource = self
self.autoCompleteTableView = tableView
let tableSrollView = NSScrollView(frame: NSZeroRect)
tableSrollView.drawsBackground = false
tableSrollView.documentView = tableView
tableSrollView.hasVerticalScroller = true
// see issue #1, popover throws when contentView's height=0, CoreGraphics bug?
let contentView:NSView = NSView(frame: NSRect.init(x: 0, y: 0, width: popOverWidth, height: 1))
contentView.addSubview(tableSrollView)
let contentViewController = NSViewController()
contentViewController.view = contentView
self.autoCompletePopover = NSPopover()
self.autoCompletePopover?.appearance = NSAppearance(named: NSAppearanceNameVibrantLight)
self.autoCompletePopover?.animates = false
self.autoCompletePopover?.contentViewController = contentViewController
self.autoCompletePopover?.delegate = self
self.matches = [String]()
}
func insert(_ sender:AnyObject){
let selectedRow = self.autoCompleteTableView!.selectedRow
let matchCount = self.matches!.count
if selectedRow >= 0 && selectedRow < matchCount{
self.string = self.matches![selectedRow]
if self.tableViewDelegate!.responds(to: #selector(AutoCompleteTableViewDelegate.didSelectItem(_:))){
self.tableViewDelegate!.didSelectItem!(self.string!)
}
}
self.autoCompletePopover?.close()
}
override func complete(_ sender: Any?) {
let lengthOfWord = self.string!.characters.count
let subStringRange = NSMakeRange(0, lengthOfWord)
//This happens when we just started a new word or if we have already typed the entire word
if subStringRange.length == 0 || lengthOfWord == 0 {
self.autoCompletePopover?.close()
return
}
var index = 0
self.matches = self.getCompletionArray(subStringRange, indexOfSelectedItem: &index)
if self.matches!.count > 0 {
self.autoCompleteTableView?.reloadData()
self.autoCompleteTableView?.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false)
self.autoCompleteTableView?.scrollRowToVisible(index)
let rect = self.visibleRect
self.autoCompletePopover?.show(relativeTo: rect, of: self, preferredEdge: NSRectEdge.maxY)
}
else{
self.autoCompletePopover?.close()
}
}
func getCompletionArray(_ charRange: NSRange, indexOfSelectedItem index: UnsafeMutablePointer<Int>?) ->[String]{
if self.tableViewDelegate!.responds(
to: #selector(AutoCompleteTableViewDelegate.textView(_:completions:forPartialWordRange:indexOfSelectedItem:))){
return self.tableViewDelegate!.textView(self, completions: [], forPartialWordRange: charRange, indexOfSelectedItem: index)
}
return []
}
}
// MARK: - NSPopoverDelegate
extension AutoCompleteTextField: NSPopoverDelegate{
// caclulate contentSize only before it will show, to make it more stable
func popoverWillShow(_ notification: Notification) {
let numberOfRows = min(self.autoCompleteTableView!.numberOfRows, maxResults)
let height = (self.autoCompleteTableView!.rowHeight + self.autoCompleteTableView!.intercellSpacing.height) * CGFloat(numberOfRows) + 2 * 0.0
let frame = NSMakeRect(0, 0, popOverWidth, height)
self.autoCompleteTableView?.enclosingScrollView?.frame = NSInsetRect(frame, popOverPadding, popOverPadding)
self.autoCompletePopover?.contentSize = NSMakeSize(NSWidth(frame), NSHeight(frame))
}
}
// MARK: - NSTableViewDelegate
extension AutoCompleteTextField:NSTableViewDelegate{
func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
return AutoCompleteTableRowView()
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
var cellView = tableView.make(withIdentifier: "MyView", owner: self) as? NSTableCellView
if cellView == nil{
cellView = NSTableCellView(frame: NSZeroRect)
let textField = NSTextField(frame: NSZeroRect)
textField.isBezeled = false
textField.drawsBackground = false
textField.isEditable = false
textField.isSelectable = false
cellView!.addSubview(textField)
cellView!.textField = textField
cellView!.identifier = "MyView"
}
let attrs = [NSForegroundColorAttributeName:NSColor.black,NSFontAttributeName:NSFont.systemFont(ofSize: 13)]
let mutableAttriStr = NSMutableAttributedString(string: self.matches![row], attributes: attrs)
cellView!.textField!.attributedStringValue = mutableAttriStr
return cellView
}
}
// MARK: - NSTableViewDataSource
extension AutoCompleteTextField:NSTableViewDataSource{
func numberOfRows(in tableView: NSTableView) -> Int {
if self.matches == nil{
return 0
}
return self.matches!.count
}
}
| mit | 524a5ade79a7dae0bcb0dc69f7e746ea | 37.864734 | 177 | 0.667371 | 5.306728 | false | false | false | false |
urbn/URBNConvenience | Example/TVConvenience/ViewController.swift | 1 | 1855 | //
// ViewController.swift
// TVConvenience
//
// Created by Evan Dutcher on 10/27/16.
// Copyright © 2016 jgrandelli. All rights reserved.
//
import UIKit
import URBNConvenience
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let redView = UIView()
let blueView = UIView()
let greenView = UIView()
let imageView = UIImageView()
blueView.backgroundColor = .blue
redView.backgroundColor = .red
greenView.backgroundColor = .green
view.addSubviewsWithNoConstraints(redView)
view.addSubviewsWithNoConstraints(blueView)
view.addSubviewsWithNoConstraints(greenView)
let views = ["redView": redView, "blueView": blueView, "greenView": greenView]
activateVFL(
format: "V:|-[blueView(==redView)][greenView(==redView)][redView]-|",
options: [.alignAllLeft, .alignAllRight],
views: views
)
activateVFL(
format: "H:|-[redView]-|",
views: views
)
imageView.image = "core image supports qr codes".qrImage(foregroundColor: .purple, backgroundColor: .green, size: CGSize(width: 100.0, height: 100.0))
greenView.addSubviewsWithNoConstraints(imageView)
NSLayoutConstraint(item: greenView, attribute: .centerX, relatedBy: .equal, toItem: imageView, attribute: .centerX, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: greenView, attribute: .centerY, relatedBy: .equal, toItem: imageView, attribute: .centerY, multiplier: 1.0, constant: 0.0).isActive = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 573c0d1b1e846360244f3b05e7c3a2e3 | 32.709091 | 171 | 0.639159 | 4.828125 | false | false | false | false |
orta/eidolon | Kiosk/App/Models/Artwork.swift | 1 | 1611 | import Foundation
class Artwork: JSONAble {
let id: String
let dateString: String
dynamic let title: String
dynamic let name: String
dynamic let blurb: String
dynamic let price: String
dynamic let date: String
dynamic var artists: [Artist]?
dynamic var culturalMarker: String?
dynamic var images: [Image]?
init(id: String, dateString: String, title: String, name: String, blurb: String, price: String, date: String) {
self.id = id
self.dateString = dateString
self.title = title
self.name = name
self.blurb = blurb
self.price = price
self.date = date
}
override class func fromJSON(json: [String: AnyObject]) -> JSONAble {
let json = JSON(object: json)
let id = json["id"].stringValue
let name = json["name"].stringValue
let title = json["title"].stringValue
let dateString = json["date"].stringValue
let blurb = json["blurb"].stringValue
let price = json["price"].stringValue
let date = json["date"].stringValue
let artwork = Artwork(id: id, dateString: dateString, title: title, name: name, blurb: blurb, price: price, date: date)
if let artistDictionary = json["artist"].object as? [String: AnyObject] {
artwork.artists = [Artist.fromJSON(artistDictionary) as Artist]
}
if let imageDicts = json["images"].object as? Array<Dictionary<String, AnyObject>> {
artwork.images = imageDicts.map({ return Image.fromJSON($0) as Image })
}
return artwork
}
}
| mit | 2362c8dd11240dfdc187dd001beb918e | 29.980769 | 127 | 0.625078 | 4.438017 | false | true | false | false |
Togira/EnsemblesTesting | EnsemblesTesting/AppDelegate.swift | 1 | 4580 | //
// AppDelegate.swift
// EnsemblesTesting
//
// Created by Bliss Chapman on 7/17/16.
// Copyright © 2016 Bliss Chapman. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "EnsemblesTesting")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 19eb8c8450163a51fb5779ec89c74a1b | 48.236559 | 285 | 0.685084 | 5.759748 | false | false | false | false |
ekreative/testbuild-rocks-ios | AppsV2/AVRequestHelper.swift | 1 | 4896 | //
// AVRequestHelper.swift
// AppsV2
//
// Created by Device Ekreative on 6/27/15.
// Copyright (c) 2015 Sergei Polishchuk. All rights reserved.
//
import Foundation
import UIKit
class AVRequestHelper: NSObject {
class func getObjectAtPath(path:String ,parameters:[NSObject : AnyObject]?, success: (operation: RKObjectRequestOperation!, mappingResult: RKMappingResult!) -> Void, failure:(operation: RKObjectRequestOperation!, error: NSError!) -> Void) -> Void
{
RKObjectManager.sharedManager().getObjectsAtPath(path, parameters: parameters, success: {(operation: RKObjectRequestOperation!, mappingResult: RKMappingResult!) -> Void in
success(operation: operation, mappingResult: mappingResult)
}, failure: {(operation: RKObjectRequestOperation!, error: NSError!) -> Void in
if(operation.HTTPRequestOperation.response.statusCode == 403){
AVUser.logout()
}
else{
failure(operation: operation, error: error)
}
})
}
class func getObjectAPathWithRoute(routeName:String, object:[NSObject : AnyObject]?, parameters:[NSObject : AnyObject]?, success: (operation: RKObjectRequestOperation!, mappingResult: RKMappingResult!) -> Void, failure:(operation: RKObjectRequestOperation!, error: NSError!) -> Void) -> Void{
RKObjectManager.sharedManager().getObjectsAtPathForRouteNamed(routeName, object: object, parameters: parameters, success: { (operation: RKObjectRequestOperation!, mappingResult: RKMappingResult!) -> Void in
success(operation: operation, mappingResult: mappingResult)
}, failure: {(operation: RKObjectRequestOperation!, error: NSError!) -> Void in
if(operation.HTTPRequestOperation.response.statusCode == 403){
AVUser.logout()
}
else{
failure(operation: operation, error: error)
}
})
}
class func postObject(object: AnyObject!, path:String, parameters:[NSObject : AnyObject]?, success: (operation: RKObjectRequestOperation!, mappingResult: RKMappingResult!) -> Void, failure:(operation: RKObjectRequestOperation!, error: NSError!) -> Void) -> Void
{
RKObjectManager.sharedManager().postObject(object, path: path, parameters: parameters, success: {(operation: RKObjectRequestOperation!, mappingResult: RKMappingResult!) -> Void in
success(operation: operation, mappingResult: mappingResult)
}, failure: {(operation: RKObjectRequestOperation!, error: NSError!) -> Void in
if(operation.HTTPRequestOperation.response.statusCode == 403){
AVUser.logout()
}
else{
failure(operation: operation, error: error)
}
})
}
class func login(login:String, pass:String, success: (operation: RKObjectRequestOperation!, mappingResult: RKMappingResult!) -> Void, failure:(operation: RKObjectRequestOperation!, error: NSError!) -> Void) -> Void{
let parameters = NSMutableDictionary()
parameters.setValue(login, forKey: "username")
parameters.setValue(pass, forKey: "password")
let postParam = NSMutableDictionary()
postParam.setValue(parameters, forKey: "login")
AVRequestHelper.postObject(nil, path: "login", parameters: postParam as [NSObject : AnyObject], success: { (operation, mappingResult) -> Void in
success(operation: operation, mappingResult: mappingResult)
}) { (operation, error) -> Void in
failure(operation: operation, error: error)
}
}
class func getProjectList(success: (operation: RKObjectRequestOperation!, mappingResult: RKMappingResult!) -> Void, failure:(operation: RKObjectRequestOperation!, error: NSError!) -> Void) -> Void{
AVRequestHelper.getObjectAtPath("api/projects.json", parameters: nil, success: { (operation, mappingResult) -> Void in
success(operation: operation, mappingResult: mappingResult)
}) { (operation, error) -> Void in
failure(operation: operation, error: error)
}
}
class func getApps(projectId:Int, success: (operation: RKObjectRequestOperation!, mappingResult: RKMappingResult!) -> Void, failure:(operation: RKObjectRequestOperation!, error: NSError!) -> Void) -> Void{
AVRequestHelper.getObjectAPathWithRoute("api/builds/:id/ios", object: ["id":"\(projectId)"], parameters: nil, success: { (operation, mappingResult) -> Void in
success(operation: operation, mappingResult: mappingResult)
}) { (operation, error) -> Void in
failure(operation: operation, error: error)
}
}
} | mit | a8e6322f8cf48503badee27459ee8256 | 51.095745 | 296 | 0.648284 | 4.965517 | false | false | false | false |
xmartlabs/Swift-Project-Template | Project-iOS/XLProjectName/XLProjectName/Models/RepositoryModel.swift | 1 | 2121 | //
// RepositoryModel.swift
// XLProjectName
//
// Created by XLAuthorName ( XLAuthorWebsite )
// Copyright © 2016 XLOrganizationName. All rights reserved.
//
import Foundation
import SwiftDate
final class Repository {
var id: Int = Int.min
var name: String = ""
var desc: String?
var company: String?
var language: String?
var openIssues: Int = .min
var stargazersCount: Int = .min
var forksCount: Int = .min
var urlString: String = ""
var createdAt: Date = Date()
// do not save this properties, notice that it is returned by ignoredProperties method
var tempId: String = ""
convenience public init(from decoder: Decoder) throws {
self.init()
enum CodingKeys: String, CodingKey {
case id // primary key
case name
case desc = "description"
case language
case openIssues = "open_issues_count"
case stargazersCount = "stargazers_count"
case forksCount = "forks_count"
case urlString = "url"
case createdAt = "created_at"
case owner
}
enum OwnerKeys: String, CodingKey {
case company = "login"
}
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(.id)
name = try container.decode(.name)
desc = try container.decodeIfPresent(.desc)
language = try container.decodeIfPresent(.language)
openIssues = try container.decode(.openIssues)
stargazersCount = try container.decode(.stargazersCount)
forksCount = try container.decode(.forksCount)
urlString = try container.decode(.urlString)
createdAt = try container.decode(.createdAt)
let nestedContainer = try container.nestedContainer(keyedBy: OwnerKeys.self, forKey: .owner)
company = try nestedContainer.decodeIfPresent(.company)
}
// computed properties
var url: NSURL {
return NSURL(string: self.urlString)!
}
}
extension Repository: Decodable {}
| mit | a79ea38bdc7a7c78e602957efa0aa45b | 29.724638 | 100 | 0.625 | 4.774775 | false | false | false | false |
ello/ello-ios | Specs/Utilities/InteractionVisibilitySpec.swift | 1 | 1448 | ////
/// InteractionVisibilitySpec.swift
//
@testable import Ello
import Quick
import Nimble
class InteractionVisibilitySpec: QuickSpec {
override func spec() {
describe("InteractionVisibility") {
let expectations:
[(InteractionVisibility, isVisible: Bool, isEnabled: Bool, isSelected: Bool)] = [
(.enabled, isVisible: true, isEnabled: true, isSelected: false),
(.selectedAndEnabled, isVisible: true, isEnabled: true, isSelected: true),
(.selectedAndDisabled, isVisible: true, isEnabled: false, isSelected: true),
(.disabled, isVisible: true, isEnabled: false, isSelected: false),
(.hidden, isVisible: false, isEnabled: false, isSelected: false),
]
for (visibility, expectedVisible, expectedEnabled, expectedSelected) in expectations {
it("\(visibility) should have isVisible == \(expectedVisible)") {
expect(visibility.isVisible) == expectedVisible
}
it("\(visibility) should have isEnabled == \(expectedEnabled)") {
expect(visibility.isEnabled) == expectedEnabled
}
it("\(visibility) should have isSelected == \(expectedSelected)") {
expect(visibility.isSelected) == expectedSelected
}
}
}
}
}
| mit | 3c898eca5719b8730ecb4adfd2a956b5 | 41.588235 | 98 | 0.573895 | 5.612403 | false | false | false | false |
A-Kod/vkrypt | Pods/SwiftyVK/Library/Sources/LongPoll/LongPollTask.swift | 2 | 3650 | import Foundation
protocol LongPollTask: OperationConvertible {}
final class LongPollTaskImpl: Operation, LongPollTask {
private weak var session: Session?
private let server: String
private var startTs: String
private let lpKey: String
private let delayOnError: TimeInterval
private let onResponse: ([JSON]) -> ()
private let onError: (LongPollTaskError) -> ()
private var currentTask: Task?
private let semaphore = DispatchSemaphore(value: 0)
private let repeatQueue = DispatchQueue.global(qos: .utility)
init(
session: Session?,
delayOnError: TimeInterval,
data: LongPollTaskData
) {
self.session = session
self.server = data.server
self.lpKey = data.lpKey
self.startTs = data.startTs
self.delayOnError = delayOnError
self.onResponse = data.onResponse
self.onError = data.onError
}
override func main() {
update(ts: startTs)
semaphore.wait()
}
private func update(ts: String) {
guard !isCancelled, let session = session else { return }
currentTask = Request(type: .url("https://\(server)?act=a_check&key=\(lpKey)&ts=\(ts)&wait=25&mode=106"))
.toMethod()
.configure(with: Config(attemptsMaxLimit: 1, attemptTimeout: 30, handleErrors: false))
.onSuccess { [weak self] data in
guard let strongSelf = self, !strongSelf.isCancelled else { return }
guard let response = try? JSON(data: data) else {
strongSelf.semaphore.signal()
return
}
if let errorCode = response.int("failed") {
strongSelf.handleError(code: errorCode, response: response)
}
else {
let newTs = response.forcedString("ts")
let updates: [Any] = response.array("updates") ?? []
strongSelf.onResponse(updates.map { JSON(value: $0) })
strongSelf.repeatQueue.async {
strongSelf.update(ts: newTs)
}
}
}
.onError { [weak self] _ in
guard let strongSelf = self, !strongSelf.isCancelled else { return }
Thread.sleep(forTimeInterval: strongSelf.delayOnError)
guard !strongSelf.isCancelled else { return }
strongSelf.update(ts: ts)
}
.send(in: session)
}
func handleError(code: Int, response: JSON) {
switch code {
case 1:
guard let newTs = response.string("ts") else {
onError(.unknown)
semaphore.signal()
return
}
onError(.historyMayBeLost)
repeatQueue.async { [weak self] in
self?.update(ts: newTs)
}
case 2, 3:
onError(.connectionInfoLost)
semaphore.signal()
default:
onError(.unknown)
semaphore.signal()
}
}
override func cancel() {
super.cancel()
currentTask?.cancel()
semaphore.signal()
}
}
struct LongPollTaskData {
let server: String
let startTs: String
let lpKey: String
let onResponse: ([JSON]) -> ()
let onError: (LongPollTaskError) -> ()
}
enum LongPollTaskError {
case unknown
case historyMayBeLost
case connectionInfoLost
}
| apache-2.0 | ba890f386416593bd1c9c2bccd4cf6ba | 30.465517 | 113 | 0.536986 | 4.912517 | false | false | false | false |
alobanov/ALFormBuilder | Sources/RxFormBuilder/Components/cells/ALFBPhoneViewCell.swift | 1 | 10329 | //
// FormPhoneViewCellTableViewCell.swift
// Puls
//
// Created by Aleksey Lobanov on 24/07/2017.
// Copyright © 2017 Aleksey Lobanov. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
open class ALFBPhoneViewCell: UITableViewCell, RxCellReloadeble, UITextFieldDelegate {
enum PhonePart: Int {
case baseCode = 0, cityCode = 1, phone = 2
var index: Int {
return self.rawValue
}
var count: Int {
switch self {
case .baseCode: return 1
case .cityCode: return 2
case .phone: return 3
}
}
}
let bag = DisposeBag()
@IBOutlet weak var baseCodeLabel: UILabel!
@IBOutlet weak var cityCodeField: UITextField!
@IBOutlet weak var phoneField: UITextField!
@IBOutlet weak var topPlaceholderLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var validateBtn: UIButton!
@IBOutlet weak var cleareBtn: UIButton!
@IBOutlet weak var errorHighlightView: UIView!
private var storedModel: RowFromPhoneCompositeOutput!
private var alreadyInitialized = false
fileprivate var validationState: BehaviorSubject<ALFB.ValidationState>!
fileprivate var didChangeValidation: DidChangeValidation!
open override func awakeFromNib() {
super.awakeFromNib()
// base configuration
validateBtn.setImage(ALFBStyle.imageOfTfAlertIconStar, for: UIControlState())
cleareBtn.setImage(ALFBStyle.imageOfCloseBtn(customColor: ALFBStyle.fbGray), for: UIControlState())
validateBtn.isHidden = true
cleareBtn.isHidden = true
clipsToBounds = true
errorHighlightView.alpha = 0
errorHighlightView.isUserInteractionEnabled = false
cityCodeField.tag = PhonePart.cityCode.rawValue
phoneField.tag = PhonePart.phone.rawValue
self.didChangeValidation = { [weak self] _ in
if let state = self?.storedModel.validation.state {
self?.validationState.onNext(state)
}
}
self.layoutIfNeeded()
}
public func reload(with model: RxCellModelDatasoursable) {
// check visuzlization model
guard let vm = model as? RowFromPhoneCompositeOutput else {
return
}
cityCodeField.accessibilityIdentifier = "code_\(vm.identifier)"
cityCodeField.isAccessibilityElement = true
phoneField.accessibilityIdentifier = "phone_\(vm.identifier)"
phoneField.isAccessibilityElement = true
cleareBtn.accessibilityIdentifier = "clear_\(vm.identifier)"
cleareBtn.isAccessibilityElement = true
validateBtn.accessibilityIdentifier = "validate_\(vm.identifier)"
validateBtn.isAccessibilityElement = true
storedModel = vm
// Configurate text field
// keybord type
cityCodeField.keyboardType = vm.visualisation.keyboardType?.value ?? .default
phoneField.keyboardType = vm.visualisation.keyboardType?.value ?? .default
// Additional placeholder above the input text
topPlaceholderLabel.text = vm.visualisation.placeholderText
cityCodeField.placeholder = "Код"
phoneField.placeholder = "Номер"
// Can editable
cityCodeField.isUserInteractionEnabled = !vm.visible.isDisabled
cityCodeField.textColor = cityCodeField.isUserInteractionEnabled
? UIColor.black
: UIColor.lightGray
self.backgroundColor = cityCodeField.isUserInteractionEnabled
? UIColor.white
: UIColor.lightGray
let value = vm.value.transformForDisplay() ?? ""
// Set value
baseCodeLabel.text = "+\(phonePartFrom(text: value, byType: .baseCode))"
cityCodeField.text = phonePartFrom(text: value, byType: .cityCode)
phoneField.text = phonePartFrom(text: value, byType: .phone)
topPlaceholderLabel.textColor = self.storedModel.validation.state.color
// addidional description information field under the text field
descriptionLabel.text = vm.visualisation.detailsText
//
// Configure buttons and components
//
cleareBtn.isHidden = true
validateBtn.isHidden = !vm.validation.state.isVisibleValidationUI
if !validateBtn.isHidden {
validateBtn.isHidden = !vm.visible.isMandatory
}
if let s = self.storedModel as? FormItemCompositeProtocol {
self.storedModel.didChangeValidation[s.identifier] = didChangeValidation
}
// Configurate next only one
if !alreadyInitialized {
self.configureRx()
cityCodeField.delegate = self
phoneField.delegate = self
accessoryType = UITableViewCellAccessoryType.none
alreadyInitialized = true
}
}
private func phonePartFrom(text: String, byType: PhonePart) -> String {
let phoneNumberParts = text.components(separatedBy: " ")
return (phoneNumberParts.count>=byType.count) ? phoneNumberParts[byType.index] : ""
}
private func phoneParts() -> [String] {
let value = self.storedModel.value.transformForDisplay() ?? ""
return [phonePartFrom(text: value, byType: .baseCode),
phonePartFrom(text: value, byType: .cityCode),
phonePartFrom(text: value, byType: .phone)]
}
private func storePhonePart(text: String, byType: PhonePart) {
var phoneArr = phoneParts()
phoneArr[byType.rawValue] = text
let value = phoneArr.joined(separator: " ")
storedModel.update(value: ALStringValue(value: value))
}
// MARK: - UITextFieldDelegate
public func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let maxLength = (textField.tag == 1) ? 5 : 9
return textField.filtred(self.storedModel.visualisation.keyboardOptions.options,
string: string,
range: range,
maxLeng: maxLength)
}
// MARK: - Additional helpers
open func showValidationWarning(text: String) {
// need override
}
private func highlightField() {
UIView.animate(withDuration: 0.4, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
self.errorHighlightView.alpha = 0.3
}, completion: { _ in
UIView.animate(withDuration: 0.4, animations: {
self.errorHighlightView.alpha = 0
})
})
}
func configureRx() {
self.validationState = BehaviorSubject<ALFB.ValidationState>(value: self.storedModel.validation.state)
// События начала ввода
let startEditingCity = cityCodeField.rx.controlEvent(.editingDidBegin).asDriver()
let startEditingPhone = phoneField.rx.controlEvent(.editingDidBegin).asDriver()
// Сосотояние валидации полей при вводе
// let validationCityCode =
cityCodeField.rx.text.asDriver().skip(1)
.filter { [weak self] text -> Bool in
let value = self?.storedModel.value.transformForDisplay() ?? ""
return (text != self?.phonePartFrom(text: value, byType: .cityCode))
}
.drive(onNext: { [weak self] text in
return self?.storePhonePart(text: text ?? "", byType: .cityCode)
}).disposed(by: bag)
//.startWith(storedModel.validation.state)
//let validationPhone =
phoneField.rx.text.asDriver().skip(1)
.filter { [weak self] text -> Bool in
let value = self?.storedModel.value.transformForDisplay() ?? ""
return (text != self?.phonePartFrom(text: value,
byType: .phone))
}
.drive(onNext: { [weak self] text in
self?.storePhonePart(text: text ?? "", byType: .phone)
}).disposed(by: bag)
//.startWith(storedModel.validation.state)
// События конца ввода
let endEditingCity = cityCodeField.rx.controlEvent(.editingDidEnd).asObservable()
.withLatestFrom(validationState)
let endEditingPhone = phoneField.rx.controlEvent(.editingDidEnd).asObservable()
.withLatestFrom(validationState)
// При активном фокусе полей показываем кнопку "отчистить"
Driver.merge([startEditingCity, startEditingPhone])
.do(onNext: { [weak self] _ in
self?.storedModel.base.changeisEditingNow(true)
self?.cleareBtn.isHidden = false
self?.validateBtn.isHidden = true
})
.drive()
.disposed(by: bag)
// Проверяем последнее значение валидации и подсвечиваем верхний залоголов
validationState
.scan(ALFB.ValidationState.valid) { [weak self] (_, newState) -> ALFB.ValidationState? in
self?.topPlaceholderLabel.textColor = newState.color
return newState
}.subscribe()
.disposed(by: bag)
// После потери фокуса показываем состояние валидации
Observable.merge([endEditingCity, endEditingPhone]).subscribe(onNext: { [weak self] valid in
self?.storedModel.base.changeisEditingNow(false)
self?.validateBtn.isHidden = valid.isValidWithTyping
self?.cleareBtn.isHidden = true
let isMandatory = self?.storedModel.visible.isMandatory ?? false
if !isMandatory {
self?.validateBtn.isHidden = !isMandatory
}
if !valid.isValidWithTyping {
if valid.message != "" {
self?.showValidationWarning(text: valid.message)
}
}
}).disposed(by: bag)
// Отчистка полей
cleareBtn.rx.tap.subscribe(onNext: {[weak self] _ in
self?.cityCodeField.text = ""
self?.phoneField.text = ""
// Посылаем событие о том что мы поменяли текс программно
self?.cityCodeField.sendActions(for: UIControlEvents.valueChanged)
self?.phoneField.sendActions(for: UIControlEvents.valueChanged)
}).disposed(by: bag)
// При нажатии на звездочку показываем ссощение об ошибке
validateBtn.rx.tap.subscribe(onNext: {[unowned self] _ in
if self.storedModel.validation.state.message != "" {
self.showValidationWarning(text: self.storedModel.validation.state.message)
self.highlightField()
}
}).disposed(by: bag)
}
}
| mit | 26da7ac60fb6179bd7a7adc44d2f456a | 33.690972 | 107 | 0.677109 | 4.317632 | false | false | false | false |
tlax/looper | looper/Model/Camera/Filter/Item/MCameraFilterItemCoolBlue.swift | 1 | 1895 | import UIKit
class MCameraFilterItemCoolBlue:MCameraFilterItem
{
init()
{
let title:String = NSLocalizedString("MCameraFilterItemCoolBlue_title", comment:"")
let viewTitle:String = NSLocalizedString("MCameraFilterItemCoolBlue_viewTitle", comment:"")
let image:UIImage = #imageLiteral(resourceName: "assetFilterCoolBlue")
super.init(title:title, viewTitle:viewTitle, image:image)
}
override func selected(filterSelectedItem:MCameraFilterSelectorItem, controller:CCameraFilterSelector)
{
guard
let itemRecord:MCameraFilterSelectorItemRecord = filterSelectedItem as? MCameraFilterSelectorItemRecord
else
{
return
}
let record:MCameraRecord = itemRecord.record
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.filter(record:record, controller:controller)
}
}
//MARK: private
private func filter(record:MCameraRecord, controller:CCameraFilterSelector)
{
let filteredRecord:MCameraRecord
if let coolBlue:MCameraFilterProcessorCoolBlue = MCameraFilterProcessorCoolBlue()
{
filteredRecord = coolBlue.cool(record:record)
}
else
{
filteredRecord = record
}
let waterMarked:MCameraRecord = waterMark(original:filteredRecord)
DispatchQueue.main.async
{ [weak controller] in
let controllerCompress:CCameraCompress = CCameraCompress(
model:waterMarked)
controller?.parentController.push(
controller:controllerCompress,
horizontal:
CParent.TransitionHorizontal.fromRight)
}
}
}
| mit | 1366d517c4e69145e4e6552acd179cbe | 29.564516 | 115 | 0.617942 | 5.524781 | false | false | false | false |
giggle-engineer/DOFavoriteButton | DOFavoriteButton/DOFavoriteButton.swift | 2 | 18113 | //
// DOFavoriteButton.swift
// DOFavoriteButton
//
// Created by Daiki Okumura on 2015/07/09.
// Copyright (c) 2015 Daiki Okumura. All rights reserved.
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
import AppKit
@IBDesignable
public class DOFavoriteButton: NSButton {
@IBInspectable override public var image: NSImage! {
didSet {
let frame = self.frame
let imageFrame = CGRectMake(frame.size.width / 2 - frame.size.width / 4, frame.size.height / 2 - frame.size.height / 4, frame.size.width / 2, frame.size.height / 2)
createLayers(image: image, imageFrame: imageFrame)
}
}
private var imageShape: CAShapeLayer!
@IBInspectable public var imageColorOn: NSColor! = NSColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
if (selected) {
imageShape.fillColor = imageColorOn.CGColor
}
}
}
@IBInspectable public var imageColorOff: NSColor! = NSColor(red: 136/255, green: 153/255, blue: 166/255, alpha: 1.0) {
didSet {
if (!selected) {
imageShape.fillColor = imageColorOff.CGColor
}
}
}
private var circleShape: CAShapeLayer!
private var circleMask: CAShapeLayer!
@IBInspectable public var circleColor: NSColor! = NSColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
circleShape.fillColor = circleColor.CGColor
}
}
private var lines: [CAShapeLayer]! = []
@IBInspectable public var lineColor: NSColor! = NSColor(red: 250/255, green: 120/255, blue: 68/255, alpha: 1.0) {
didSet {
for i in 0 ..< 5 {
lines[i].strokeColor = lineColor.CGColor
}
}
}
private let circleTransform = CAKeyframeAnimation(keyPath: "transform")
private let circleMaskTransform = CAKeyframeAnimation(keyPath: "transform")
private let lineStrokeStart = CAKeyframeAnimation(keyPath: "strokeStart")
private let lineStrokeEnd = CAKeyframeAnimation(keyPath: "strokeEnd")
private let lineOpacity = CAKeyframeAnimation(keyPath: "opacity")
private let imageTransform = CAKeyframeAnimation(keyPath: "transform")
@IBInspectable public var duration: Double = 1.0 {
didSet {
circleTransform.duration = 0.333 * duration // 0.0333 * 10
circleMaskTransform.duration = 0.333 * duration // 0.0333 * 10
lineStrokeStart.duration = 0.6 * duration //0.0333 * 18
lineStrokeEnd.duration = 0.6 * duration //0.0333 * 18
lineOpacity.duration = 1.0 * duration //0.0333 * 30
imageTransform.duration = 1.0 * duration //0.0333 * 30
}
}
@IBInspectable public var selected : Bool {
didSet {
if (selected != oldValue) {
if selected {
imageShape.fillColor = imageColorOn.CGColor
} else {
deselect()
}
}
}
}
public var alreadyCreatedLayer : Bool = false
public convenience init() {
self.init(frame: CGRectZero)
}
public override convenience init(frame: CGRect) {
let image = NSImage(named: "star")
self.init(frame: frame, image: image)
}
public convenience init(frame: CGRect, image: NSImage!) {
let imageFrame = CGRectMake(frame.size.width / 2 - frame.size.width / 4, frame.size.height / 2 - frame.size.height / 4, frame.size.width / 2, frame.size.height / 2)
self.init(frame: frame, image: image, imageFrame: imageFrame)
}
public init(frame: CGRect, image: NSImage!, imageFrame: CGRect) {
self.selected = false
super.init(frame: frame)
self.image = image
}
public required init?(coder aDecoder: NSCoder) {
self.selected = false
super.init(coder: aDecoder)
}
public override func drawRect(dirtyRect: NSRect) {
// do nothing, we got this :D
}
private func createLayers(image image: NSImage!, imageFrame: CGRect) {
self.layer = CALayer()
self.wantsLayer = true
let imgCenterPoint = CGPointMake(imageFrame.origin.x + imageFrame.width / 2, imageFrame.origin.y + imageFrame.height / 2)
let lineFrame = CGRectMake(imageFrame.origin.x - imageFrame.width / 4, imageFrame.origin.y - imageFrame.height / 4 , imageFrame.width * 1.5, imageFrame.height * 1.5)
//===============
// circle layer
//===============
circleShape = CAShapeLayer()
circleShape.bounds = imageFrame
circleShape.position = imgCenterPoint
circleShape.path = NSBezierPath(ovalInRect: imageFrame).CGPath
circleShape.fillColor = circleColor.CGColor
circleShape.transform = CATransform3DMakeScale(0.0, 0.0, 1.0)
self.layer!.addSublayer(circleShape)
circleMask = CAShapeLayer()
circleMask.bounds = imageFrame
circleMask.position = imgCenterPoint
circleMask.fillRule = kCAFillRuleEvenOdd
circleShape.mask = circleMask
let maskPath = NSBezierPath(rect: imageFrame)
maskPath.addArcWithCenter(imgCenterPoint, radius: 0.1, startAngle: CGFloat(0.0), endAngle: CGFloat(M_PI * 2), clockwise: true)
circleMask.path = maskPath.CGPath
//===============
// line layer
//===============
for i in 0 ..< 5 {
let line = CAShapeLayer()
line.bounds = lineFrame
line.position = imgCenterPoint
line.masksToBounds = true
line.actions = ["strokeStart": NSNull(), "strokeEnd": NSNull()]
line.strokeColor = lineColor.CGColor
line.lineWidth = 1.25
line.miterLimit = 1.25
line.path = {
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, lineFrame.origin.x + lineFrame.width / 2, lineFrame.origin.y + lineFrame.height / 2)
CGPathAddLineToPoint(path, nil, lineFrame.origin.x + lineFrame.width / 2, lineFrame.origin.y)
return path
}()
line.lineCap = kCALineCapRound
line.lineJoin = kCALineJoinRound
line.strokeStart = 0.0
line.strokeEnd = 0.0
line.opacity = 0.0
line.transform = CATransform3DMakeRotation(CGFloat(M_PI) / 5 * (CGFloat(i) * 2 + 1), 0.0, 0.0, 1.0)
self.layer!.addSublayer(line)
lines.append(line)
}
//===============
// image layer
//===============
imageShape = CAShapeLayer()
imageShape.bounds = imageFrame
imageShape.position = imgCenterPoint
imageShape.path = NSBezierPath(rect: imageFrame).CGPath
imageShape.fillColor = imageColorOff.CGColor
imageShape.actions = ["fillColor": NSNull()]
self.layer!.addSublayer(imageShape)
let imageData = image.TIFFRepresentation
let source = CGImageSourceCreateWithData(imageData!, nil)
let maskRef = CGImageSourceCreateImageAtIndex(source!, 0, nil)
let imageMask = CALayer()
imageMask.contents = maskRef
imageMask.bounds = imageFrame
imageMask.position = imgCenterPoint
imageShape.mask = imageMask
//==============================
// circle transform animation
//==============================
circleTransform.duration = 0.333 // 0.0333 * 10
circleTransform.values = [
NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/10
NSValue(CATransform3D: CATransform3DMakeScale(0.5, 0.5, 1.0)), // 1/10
NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), // 2/10
NSValue(CATransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 3/10
NSValue(CATransform3D: CATransform3DMakeScale(1.3, 1.3, 1.0)), // 4/10
NSValue(CATransform3D: CATransform3DMakeScale(1.37, 1.37, 1.0)), // 5/10
NSValue(CATransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)), // 6/10
NSValue(CATransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)) // 10/10
]
circleTransform.keyTimes = [
0.0, // 0/10
0.1, // 1/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
1.0 // 10/10
]
circleMaskTransform.duration = 0.333 // 0.0333 * 10
circleMaskTransform.values = [
NSValue(CATransform3D: CATransform3DIdentity), // 0/10
NSValue(CATransform3D: CATransform3DIdentity), // 2/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 1.25, imageFrame.height * 1.25, 1.0)), // 3/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 2.688, imageFrame.height * 2.688, 1.0)), // 4/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 3.923, imageFrame.height * 3.923, 1.0)), // 5/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 4.375, imageFrame.height * 4.375, 1.0)), // 6/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 4.731, imageFrame.height * 4.731, 1.0)), // 7/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)), // 9/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)) // 10/10
]
circleMaskTransform.keyTimes = [
0.0, // 0/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
0.7, // 7/10
0.9, // 9/10
1.0 // 10/10
]
//==============================
// line stroke animation
//==============================
lineStrokeStart.duration = 0.6 //0.0333 * 18
lineStrokeStart.values = [
0.0, // 0/18
0.0, // 1/18
0.18, // 2/18
0.2, // 3/18
0.26, // 4/18
0.32, // 5/18
0.4, // 6/18
0.6, // 7/18
0.71, // 8/18
0.89, // 17/18
0.92 // 18/18
]
lineStrokeStart.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.333, // 6/18
0.389, // 7/18
0.444, // 8/18
0.944, // 17/18
1.0, // 18/18
]
lineStrokeEnd.duration = 0.6 //0.0333 * 18
lineStrokeEnd.values = [
0.0, // 0/18
0.0, // 1/18
0.32, // 2/18
0.48, // 3/18
0.64, // 4/18
0.68, // 5/18
0.92, // 17/18
0.92 // 18/18
]
lineStrokeEnd.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.944, // 17/18
1.0, // 18/18
]
lineOpacity.duration = 1.0 //0.0333 * 30
lineOpacity.values = [
1.0, // 0/30
1.0, // 12/30
0.0 // 17/30
]
lineOpacity.keyTimes = [
0.0, // 0/30
0.4, // 12/30
0.567 // 17/30
]
//==============================
// image transform animation
//==============================
imageTransform.duration = 1.0 //0.0333 * 30
imageTransform.values = [
NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/30
NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 3/30
NSValue(CATransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 9/30
NSValue(CATransform3D: CATransform3DMakeScale(1.25, 1.25, 1.0)), // 10/30
NSValue(CATransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 11/30
NSValue(CATransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 14/30
NSValue(CATransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 15/30
NSValue(CATransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 16/30
NSValue(CATransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 17/30
NSValue(CATransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 20/30
NSValue(CATransform3D: CATransform3DMakeScale(1.025, 1.025, 1.0)), // 21/30
NSValue(CATransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 22/30
NSValue(CATransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 25/30
NSValue(CATransform3D: CATransform3DMakeScale(0.95, 0.95, 1.0)), // 26/30
NSValue(CATransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 27/30
NSValue(CATransform3D: CATransform3DMakeScale(0.99, 0.99, 1.0)), // 29/30
NSValue(CATransform3D: CATransform3DIdentity) // 30/30
]
imageTransform.keyTimes = [
0.0, // 0/30
0.1, // 3/30
0.3, // 9/30
0.333, // 10/30
0.367, // 11/30
0.467, // 14/30
0.5, // 15/30
0.533, // 16/30
0.567, // 17/30
0.667, // 20/30
0.7, // 21/30
0.733, // 22/30
0.833, // 25/30
0.867, // 26/30
0.9, // 27/30
0.967, // 29/30
1.0 // 30/30
]
}
public override func mouseDown(theEvent: NSEvent) {
self.layer?.opacity = 0.4
super.mouseDown(theEvent)
self.mouseUp(theEvent)
}
public override func mouseUp(theEvent: NSEvent) {
super.mouseUp(theEvent)
// we can't simply use NSEvent's locationInWindow here because it's stale by the time we mouse up
let mouseLocation = NSEvent.mouseLocation()
let rectFromScreen = self.window?.convertRectFromScreen(NSRect(x: mouseLocation.x, y: mouseLocation.y, width: 0, height: 0))
let windowLocation = NSPoint(x: rectFromScreen!.origin.x, y: rectFromScreen!.origin.y)
let locationInView = self.convertPoint(windowLocation, fromView: nil)
self.layer?.opacity = 1.0
if self.mouse(locationInView, inRect: self.bounds) {
if self.selected {
self.deselect()
} else {
self.select()
}
}
}
public func select() {
selected = true
imageShape.fillColor = imageColorOn.CGColor
CATransaction.begin()
circleShape.addAnimation(circleTransform, forKey: "transform")
circleMask.addAnimation(circleMaskTransform, forKey: "transform")
imageShape.addAnimation(imageTransform, forKey: "transform")
for i in 0 ..< 5 {
lines[i].addAnimation(lineStrokeStart, forKey: "strokeStart")
lines[i].addAnimation(lineStrokeEnd, forKey: "strokeEnd")
lines[i].addAnimation(lineOpacity, forKey: "opacity")
}
CATransaction.commit()
}
public func deselect() {
selected = false
imageShape.fillColor = imageColorOff.CGColor
// remove all animations
circleShape.removeAllAnimations()
circleMask.removeAllAnimations()
imageShape.removeAllAnimations()
lines[0].removeAllAnimations()
lines[1].removeAllAnimations()
lines[2].removeAllAnimations()
lines[3].removeAllAnimations()
lines[4].removeAllAnimations()
}
}
// Extensions to help bridge some missing features from AppKit
extension NSBezierPath
{
var CGPath : CGPathRef! {
if self.elementCount == 0 {
return nil
}
let path = CGPathCreateMutable()
var didClosePath = false
for i in 0..<self.elementCount {
var points = [NSPoint](count: 3, repeatedValue: NSZeroPoint)
switch self.elementAtIndex(i, associatedPoints: &points) {
case .MoveToBezierPathElement:CGPathMoveToPoint(path, nil, points[0].x, points[0].y)
case .LineToBezierPathElement:CGPathAddLineToPoint(path, nil, points[0].x, points[0].y)
case .CurveToBezierPathElement:CGPathAddCurveToPoint(path, nil, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y)
case .ClosePathBezierPathElement:CGPathCloseSubpath(path)
didClosePath = true
}
}
if !didClosePath {
CGPathCloseSubpath(path)
}
return CGPathCreateCopy(path)!
}
func addArcWithCenter(center: NSPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) {
let startAngleRadian = ((startAngle) * (180.0 / CGFloat(M_PI)))
let endAngleRadian = ((endAngle) * (180.0 / CGFloat(M_PI)))
self.appendBezierPathWithArcWithCenter(center, radius: radius, startAngle: startAngleRadian, endAngle: endAngleRadian, clockwise: !clockwise)
}
}
| mit | 506be5f728096d6137fe605a9d2f5263 | 39.161863 | 176 | 0.537625 | 4.008188 | false | false | false | false |
Basadev/MakeSchoolNotes | MakeSchoolNotes/Views/NoteTableViewCell.swift | 1 | 902 | //
// NoteTableViewCell.swift
// MakeSchoolNotes
//
// Created by Martin Walsh on 29/05/2015.
// Copyright (c) 2015 MakeSchool. All rights reserved.
//
import Foundation
import UIKit
class NoteTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
// initialize the date formatter only once, using a static computed property
static var dateFormatter: NSDateFormatter = {
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
var note: Note? {
didSet {
if let note = note, titleLabel = titleLabel, dateLabel = dateLabel {
self.titleLabel.text = note.title
self.dateLabel.text = NoteTableViewCell.dateFormatter.stringFromDate(note.modificationDate)
}
}
}
}
| mit | 4ffaec22d4e303217271ff17a997c584 | 26.333333 | 107 | 0.641907 | 4.797872 | false | false | false | false |
elpsk/InstaSwift | Filterer/ViewController.swift | 1 | 13634 | //
// ViewController.swift
// Filterer
//
// Created by alberto pasca on 09/02/16.
// Copyright © 2015 Coursera. All rights reserved.
//
import UIKit
enum Filters:Int
{
case None = 0
case Red = 1
case Green = 2
case Blue = 3
case Yellow = 4
case Purple = 5
case Orange = 6
case Nigth = 7
case Invert = 8
case Sepia = 9
case Gray = 10
}
class ViewController: UIViewController,
UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDataSource, UICollectionViewDelegate
{
//
// Interface Builder components
//
@IBOutlet var imageView : UIImageView!
@IBOutlet var imageViewFiltered : UIImageView!
@IBOutlet var secondaryMenu : UICollectionView!
@IBOutlet var thirdMenu : UIView!
@IBOutlet var bottomMenu : UIView!
@IBOutlet var infoView : UIView!
@IBOutlet var newButton : UIButton!
@IBOutlet var shareButton : UIButton!
@IBOutlet var filterButton : UIButton!
@IBOutlet var editButton : UIButton!
@IBOutlet var compareButton : UIButton!
@IBOutlet var editSlider : UISlider!
var selectedFilter : Filter!
//
// List of filters for UICollectionView preview
//
var filtersPreview: [Filter] =
[
Filter(defaultValue: 0, filterType: Filters.None),
Filter(defaultValue: 255, filterType: Filters.Red),
Filter(defaultValue: 255, filterType: Filters.Green),
Filter(defaultValue: 255, filterType: Filters.Blue),
Filter(defaultValue: 255, filterType: Filters.Yellow),
Filter(defaultValue: 255, filterType: Filters.Purple),
Filter(defaultValue: 255, filterType: Filters.Orange),
Filter(defaultValue: 255, filterType: Filters.Nigth),
Filter(defaultValue: 255, filterType: Filters.Invert),
Filter(defaultValue: 0, filterType: Filters.Sepia),
Filter(defaultValue: 255, filterType: Filters.Gray)
]
// +---------------------------------------------------------------------------+
//MARK: - View lifecycle
// +---------------------------------------------------------------------------+
override func viewDidLoad() {
super.viewDidLoad()
self.selectedFilter = Filter(defaultValue: 0, filterType: .None)
secondaryMenu.delegate = self
secondaryMenu.dataSource = self
secondaryMenu.registerNib(UINib(nibName: "FilterCell", bundle: nil), forCellWithReuseIdentifier: "fcell")
secondaryMenu.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5)
infoView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.2)
thirdMenu.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5)
secondaryMenu.translatesAutoresizingMaskIntoConstraints = false
thirdMenu.translatesAutoresizingMaskIntoConstraints = false
infoView.translatesAutoresizingMaskIntoConstraints = false
refreshLayout()
}
// +---------------------------------------------------------------------------+
//MARK: - Touch
// +---------------------------------------------------------------------------+
//
// toggle image
//
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if ( self.selectedFilter.filterType == .None || !newButton.enabled ) { return }
showInfoView()
showOriginal()
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if ( self.selectedFilter.filterType == .None || !newButton.enabled ) { return }
hideInfoView()
showFiltered()
}
// +---------------------------------------------------------------------------+
//MARK: - Protected
// +---------------------------------------------------------------------------+
func showCamera() {
let cameraPicker = UIImagePickerController()
cameraPicker.delegate = self
cameraPicker.sourceType = .Camera
presentViewController(cameraPicker, animated: true, completion: nil)
}
func showAlbum() {
let cameraPicker = UIImagePickerController()
cameraPicker.delegate = self
cameraPicker.sourceType = .PhotoLibrary
presentViewController(cameraPicker, animated: true, completion: nil)
}
//
// toggle Filters VIEW
//
func showSecondaryMenu() {
editButton.selected = false
hideEditMenu()
view.addSubview(secondaryMenu)
secondaryMenu.reloadData()
let bottomConstraint = secondaryMenu.bottomAnchor.constraintEqualToAnchor(bottomMenu.topAnchor)
let leftConstraint = secondaryMenu.leftAnchor.constraintEqualToAnchor(view.leftAnchor)
let rightConstraint = secondaryMenu.rightAnchor.constraintEqualToAnchor(view.rightAnchor)
let heightConstraint = secondaryMenu.heightAnchor.constraintEqualToConstant(50)
NSLayoutConstraint.activateConstraints([bottomConstraint, leftConstraint, rightConstraint, heightConstraint])
view.layoutIfNeeded()
self.secondaryMenu.alpha = 0
UIView.animateWithDuration(0.4) {
self.secondaryMenu.alpha = 1.0
}
}
func hideSecondaryMenu() {
UIView.animateWithDuration(0.4, animations: {
self.secondaryMenu.alpha = 0
}) { completed in
if completed == true {
self.secondaryMenu.removeFromSuperview()
}
}
}
//
// toggle INFO VIEW ("Original" label)
//
func showInfoView() {
view.addSubview(infoView)
let xConstraint = infoView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor)
let yConstraint = infoView.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 30)
let leftConstraint = infoView.leftAnchor.constraintEqualToAnchor(view.leftAnchor)
let rightConstraint = infoView.rightAnchor.constraintEqualToAnchor(view.rightAnchor)
let heightConstraint = infoView.heightAnchor.constraintEqualToConstant(44)
NSLayoutConstraint.activateConstraints([xConstraint, yConstraint, leftConstraint, rightConstraint, heightConstraint])
view.layoutIfNeeded()
self.infoView.alpha = 0
UIView.animateWithDuration(0.4) {
self.infoView.alpha = 1.0
}
}
func hideInfoView() {
UIView.animateWithDuration(0.4, animations: {
self.infoView.alpha = 0
}) { completed in
if completed == true {
self.infoView.removeFromSuperview()
}
}
}
//
// toggle Slider VIEW, "intensity"
//
func showEditMenu() {
filterButton.selected = false
hideSecondaryMenu()
view.addSubview(thirdMenu)
let bottomConstraint = thirdMenu.bottomAnchor.constraintEqualToAnchor(bottomMenu.topAnchor)
let leftConstraint = thirdMenu.leftAnchor.constraintEqualToAnchor(view.leftAnchor)
let rightConstraint = thirdMenu.rightAnchor.constraintEqualToAnchor(view.rightAnchor)
let heightConstraint = thirdMenu.heightAnchor.constraintEqualToConstant(100)
NSLayoutConstraint.activateConstraints([bottomConstraint, leftConstraint, rightConstraint, heightConstraint])
view.layoutIfNeeded()
self.thirdMenu.alpha = 0
UIView.animateWithDuration(0.4) {
self.thirdMenu.alpha = 1.0
}
}
func hideEditMenu() {
UIView.animateWithDuration(0.4, animations: {
self.thirdMenu.alpha = 0
}) { completed in
if completed == true {
self.thirdMenu.removeFromSuperview()
}
}
}
//
// toggle Original/Filtered image
//
func showOriginal() {
UIView.animateWithDuration(0.25) { () -> Void in
self.imageView.alpha = 1
self.imageViewFiltered.alpha = 0
}
}
func showFiltered() {
UIView.animateWithDuration(0.25) { () -> Void in
self.imageView.alpha = 0
self.imageViewFiltered.alpha = 1
}
}
//
// update layout, buttons
//
func refreshLayout() {
self.compareButton.enabled = self.selectedFilter.filterType != .None
self.editButton.enabled = self.selectedFilter.filterType != .None
if ( self.selectedFilter.filterType != .None ) {
hideEditMenu()
}
}
// +---------------------------------------------------------------------------+
//MARK: - Actions
// +---------------------------------------------------------------------------+
@IBAction func onShare(sender: AnyObject) {
let activityController = UIActivityViewController(activityItems: ["InstaSwift __ Check out our really cool app!", imageViewFiltered.image!], applicationActivities: nil)
presentViewController(activityController, animated: true, completion: nil)
}
@IBAction func onNewPhoto(sender: AnyObject) {
let actionSheet = UIAlertController(title: "New Photo", message: nil, preferredStyle: .ActionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .Default, handler: { action in
self.showCamera()
}))
actionSheet.addAction(UIAlertAction(title: "Album", style: .Default, handler: { action in
self.showAlbum()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
self.presentViewController(actionSheet, animated: true, completion: nil)
}
//
// Button "Filter" pressed
//
@IBAction func onFilter(sender: UIButton) {
if (sender.selected) {
hideSecondaryMenu()
sender.selected = false
} else {
showSecondaryMenu()
sender.selected = true
}
}
//
// Button "Edit" pressed
//
@IBAction func onEdit(sender: UIButton) {
if (sender.selected) {
hideEditMenu()
sender.selected = false
} else {
showEditMenu()
editSlider.setValue(Float(self.selectedFilter.value), animated: true)
sender.selected = true
}
}
//
// Button "Compare" pressed
//
@IBAction func onCompare(sender: UIButton) {
if self.selectedFilter.filterType == .None { return }
if ( compareButton.titleLabel?.text == "Compare" ) {
showInfoView()
showOriginal()
compareButton.setTitle("Back", forState: .Normal)
newButton.enabled = false
shareButton.enabled = false
editButton.enabled = false
filterButton.enabled = false
filterButton.selected = false
editButton.selected = false
hideEditMenu()
hideSecondaryMenu()
} else {
hideInfoView()
showFiltered()
compareButton.setTitle("Compare", forState: .Normal)
newButton.enabled = true
shareButton.enabled = true
editButton.enabled = true
filterButton.enabled = true
}
}
//
// Slider change value
//
@IBAction func onEditChange(sender: UISlider) {
self.selectedFilter.value = Int(sender.value)
imageViewFiltered.image = Filter.applyFilter(imageView.image, filter: self.selectedFilter)
showFiltered()
}
// +---------------------------------------------------------------------------+
//MARK: - Picker delegate
// +---------------------------------------------------------------------------+
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
dismissViewControllerAnimated(true, completion: nil)
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.image = image
imageViewFiltered.image = image
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
// +---------------------------------------------------------------------------+
//MARK: - Collectionview delegete/datasource
// +---------------------------------------------------------------------------+
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filtersPreview.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("fcell", forIndexPath: indexPath) as! FilterCell
let filter = filtersPreview[indexPath.row]
filter.value = filtersPreview[indexPath.row].value
cell.imageView.image = Filter.applyFilter(UIImage(named: "sample"), filter: filter)
showFiltered()
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let filter = filtersPreview[indexPath.row]
self.selectedFilter = filter
imageViewFiltered.image = Filter.applyFilter(imageView.image, filter: filter)
showFiltered()
refreshLayout()
}
}
| mit | 9c423d8c1146c1958f147b83d279d7e8 | 31.614833 | 176 | 0.591066 | 5.528386 | false | false | false | false |
xusader/firefox-ios | Client/Frontend/Widgets/SnackBar.swift | 3 | 8059 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Snap
/**
A specialized version of UIButton for use in SnackBars. These are displayed evenly spaced in the bottom of the bar. The main convenience of these is that you can pass in a callback in the constructor (although these also style themselves appropriately).
``SnackButton(title: "OK", { _ in println("OK") })``
*/
class SnackButton : UIButton {
let callback: (bar: SnackBar) -> Void
private var bar: SnackBar!
/**
An image to show as the background when a button is pressed. This is currently a 1x1 pixel blue color
*/
lazy var highlightImg: UIImage = {
let size = CGSize(width: 1, height: 1)
return UIImage.createWithColor(size, color: AppConstants.HighlightColor)
}()
init(title: String, callback: (bar: SnackBar) -> Void) {
self.callback = callback
super.init(frame: CGRectZero)
setTitle(title, forState: .Normal)
titleLabel?.font = AppConstants.DefaultMediumFont
setBackgroundImage(highlightImg, forState: .Highlighted)
setTitleColor(AppConstants.HighlightText, forState: .Highlighted)
addTarget(self, action: "onClick", forControlEvents: .TouchUpInside)
}
override init(frame: CGRect) {
self.callback = { bar in }
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func onClick() {
callback(bar: bar)
}
}
/**
Presents some information to the user. Can optionally include some buttons and an image. Usage:
``let bar = SnackBar(text: "This is some text in the snackbar.",
img: UIImage(named: "bookmark"),
buttons: [
SnackButton(title: "OK", { _ in println("OK") }),
SnackButton(title: "Cancel", { _ in println("Cancel") }),
SnackButton(title: "Maybe", { _ in println("Maybe") })]
)``
*/
class SnackBar: UIView {
let imageView: UIImageView
let textView: UITextView
let backgroundView: UIView
let buttonsView: Toolbar
private var buttons = [SnackButton]()
convenience init(text: String, img: UIImage?, buttons: [SnackButton]?) {
var attributes = [NSObject: AnyObject]()
attributes[NSFontAttributeName] = AppConstants.DefaultMediumFont
attributes[NSBackgroundColorAttributeName] = UIColor.clearColor()
let attrText = NSAttributedString(string: text, attributes: attributes)
self.init(attrText: attrText, img: img, buttons: buttons)
}
init(attrText: NSAttributedString, img: UIImage?, buttons: [SnackButton]?) {
imageView = UIImageView()
textView = UITextView()
buttonsView = Toolbar()
backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight))
super.init(frame: CGRectZero)
imageView.image = img
textView.attributedText = attrText
if let buttons = buttons {
for button in buttons {
addButton(button)
}
}
setup()
}
private override init(frame: CGRect) {
imageView = UIImageView()
textView = UITextView()
buttonsView = Toolbar()
backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight))
super.init(frame: frame)
}
private func setup() {
textView.backgroundColor = nil
addSubview(backgroundView)
addSubview(imageView)
addSubview(textView)
addSubview(buttonsView)
self.backgroundColor = UIColor.clearColor()
buttonsView.drawTopBorder = true
buttonsView.drawBottomBorder = true
buttonsView.drawSeperators = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
Called to check if the snackbar should be removed or not. By default, Snackbars persist forever. Override this class or use a class like CountdownSnackbar if you want things expire
:returns: true if the snackbar should be kept alive
*/
func shouldPersist(browser: Browser) -> Bool {
return true
}
override func updateConstraints() {
super.updateConstraints()
backgroundView.snp_remakeConstraints { make in
make.edges.equalTo(self)
return
}
if let img = imageView.image {
imageView.snp_remakeConstraints({ make in
make.left.equalTo(self).offset(AppConstants.DefaultPadding)
make.top.equalTo(self).offset(AppConstants.DefaultPadding)
make.width.equalTo(img.size.width)
make.height.equalTo(img.size.height)
})
} else {
imageView.snp_remakeConstraints({ make in
make.width.equalTo(0)
make.height.equalTo(0)
make.top.left.equalTo(self).offset(AppConstants.DefaultPadding)
})
}
let labelSize = self.textView.sizeThatFits(CGSizeMake(self.frame.width, CGFloat(MAXFLOAT)))
textView.textContainerInset = UIEdgeInsetsZero
textView.snp_remakeConstraints({ make in
make.top.equalTo(self.imageView.snp_top).offset(-5)
make.left.equalTo(self.imageView.snp_right)
make.height.equalTo(labelSize.height)
make.trailing.equalTo(self)
})
buttonsView.snp_remakeConstraints({ make in
make.bottom.equalTo(self)
make.left.right.equalTo(self)
if self.buttonsView.subviews.count > 0 {
make.height.equalTo(AppConstants.ToolbarHeight)
} else {
make.height.equalTo(0)
}
})
self.snp_makeConstraints({ make in
var h = labelSize.height
if let img = self.imageView.image {
h = AppConstants.DefaultPadding + max(img.size.height, labelSize.height)
}
let constraint = make.height.equalTo(h)
if (self.buttonsView.subviews.count > 0) {
constraint.offset(AppConstants.ToolbarHeight)
}
})
}
/**
Helper for animating the Snackbar showing on screen
*/
func show() {
alpha = 1
transform = CGAffineTransformIdentity
}
/**
Helper for animating the Snackbar leaving the screen
*/
func hide() {
alpha = 0
var h = frame.height
if h == 0 {
h = AppConstants.ToolbarHeight
}
transform = CGAffineTransformMakeTranslation(0, h)
}
private func addButton(snackButton: SnackButton) {
snackButton.bar = self
buttonsView.addButtons(snackButton)
buttonsView.setNeedsUpdateConstraints()
}
}
/**
A special version of a snackbar that persists for maxCount page loads. Defaults to waiting for 2 loads (i.e. will persist over one page load, which is useful for things like saving passwords.
*/
class CountdownSnackBar: SnackBar {
private var maxCount: Int? = nil
private var count = 0
private var prevURL: NSURL? = nil
init(maxCount: Int = 2, attrText: NSAttributedString, img: UIImage?, buttons: [SnackButton]?) {
self.maxCount = maxCount
super.init(attrText: attrText, img: img, buttons: buttons)
}
override init(frame: CGRect) {
if maxCount == nil {
maxCount = 2
}
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func shouldPersist(browser: Browser) -> Bool {
if browser.url != prevURL {
prevURL = browser.url
count++
return count < maxCount
}
return super.shouldPersist(browser)
}
}
| mpl-2.0 | 218b989c130adb83525cdab5e4cf5ab9 | 31.236 | 253 | 0.629358 | 4.765819 | false | false | false | false |
jingchc/Mr-Ride-iOS | Mr-Ride-iOS/LogInViewController.swift | 1 | 6416 | //
// LogInViewController.swift
// Mr-Ride-iOS
//
// Created by 莊晶涵 on 2016/6/6.
// Copyright © 2016年 AppWorks School Jing. All rights reserved.
//
import UIKit
class LogInViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var appName: UILabel!
@IBOutlet weak var backgroundImage: UIImageView!
@IBOutlet weak var heightView: UIView!
@IBOutlet weak var heightTitle: UILabel!
@IBOutlet weak var heightScale: UILabel!
@IBOutlet weak var userHeight: UITextField!
@IBOutlet weak var weightView: UIView!
@IBOutlet weak var weightTitle: UILabel!
@IBOutlet weak var weightScale: UILabel!
@IBOutlet weak var userWeight: UITextField!
@IBOutlet weak var logInButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setUp()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
checkHaveLogInOrNot()
}
// check have logged in or not
private func checkHaveLogInOrNot() {
if UserInfoManager.sharedManager.isLoggedIn {
let swRevealViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SWRevealViewController") as! SWRevealViewController
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window?.rootViewController = swRevealViewController
self.presentViewController(swRevealViewController, animated: true, completion: nil)
}
}
@IBAction func logInFB(sender: UIButton) {
// check height& weight: value, correct type, save to userdefault
if userHeight.text != nil {
guard let userHeight = getDoubleType(userHeight.text!) else { return }
NSUserDefaults.standardUserDefaults().setDouble(userHeight, forKey: NSUserDefaultKey.Height)
}else {
print("no height data")
// todo: alarm
return
}
if userWeight.text != nil {
guard let userWeight = getDoubleType(userWeight.text!) else { return }
NSUserDefaults.standardUserDefaults().setDouble(userWeight, forKey: NSUserDefaultKey.Weight)
}else {
print("no weight data")
// todo: alarm - can't be empty
return
}
// log in facebook
UserInfoManager.sharedManager.LogInWithFacebook(
fromViewController: self,
success: { user in
if let swRevealViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SWRevealViewController") as? SWRevealViewController {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window?.rootViewController = swRevealViewController
self.presentViewController(swRevealViewController, animated: true, completion: nil)
}
},
failure: { error in
// todo: alert
}
)
}
private func getDoubleType(text: String) -> Double? {
guard let doubleTypeText = Double(text) else {
// todo: alarm - type double
userHeight.text = nil
userWeight.text = nil
return nil
}
return doubleTypeText
}
private func setUp() {
// back ground
self.view.backgroundColor = UIColor.mrLightblueColor()
let backgroundGradientlayer = CAGradientLayer()
backgroundGradientlayer.frame.size = backgroundImage.frame.size
backgroundGradientlayer.colors = [UIColor.mrLightblueColor().CGColor, UIColor.pineGreen50Color().CGColor]
backgroundImage.layer.addSublayer(backgroundGradientlayer)
// App name
self.appName.textColor = UIColor.mrWhiteColor()
self.appName.font = UIFont.textStyle21Font()
self.appName.shadowOffset.height = 2
self.appName.shadowColor = UIColor.mrBlack25Color()
self.appName.text = "Mr. Ride"
// height & weight
self.heightView.layer.cornerRadius = 4
self.heightView.clipsToBounds = true
self.heightTitle.textColor = UIColor.mrDarkSlateBlueColor()
self.heightTitle.font = UIFont.textStyle22Font()
self.heightTitle.text = "Height"
self.heightScale.textColor = UIColor.mrDarkSlateBlueColor()
self.heightScale.font = UIFont.textStyle23Font()
self.heightScale.text = "cm"
self.weightView.layer.cornerRadius = 4
self.weightView.clipsToBounds = true
self.weightTitle.textColor = UIColor.mrDarkSlateBlueColor()
self.weightTitle.font = UIFont.textStyle22Font()
self.weightTitle.text = "Weight"
self.weightScale.textColor = UIColor.mrDarkSlateBlueColor()
self.weightScale.font = UIFont.textStyle23Font()
self.weightScale.text = "kg"
// user info
self.userHeight.delegate = self
self.userHeight.textColor = UIColor.mrDarkSlateBlueColor()
self.userHeight.font = UIFont.textStyle24Font()
self.userWeight.delegate = self
self.userWeight.textColor = UIColor.mrDarkSlateBlueColor()
self.userWeight.font = UIFont.textStyle24Font()
// logIn Button appearence
self.logInButton.layer.cornerRadius = 30
self.logInButton.setTitle(" Log In", forState: .Normal)
self.logInButton.setTitleShadowColor(UIColor.mrBlack25Color(), forState: .Normal)
self.logInButton.setTitleColor(UIColor.mrLightblueColor(), forState: .Normal)
self.logInButton.titleLabel?.font = UIFont.asiTextStyle16Font()
self.logInButton.titleLabel?.shadowOffset.height = -1
}
// set status bar color
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
// hide keyboard
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
}
| apache-2.0 | ffe0064d11b83d768d1d1d6ab5ddbf76 | 35.821839 | 159 | 0.637116 | 5.208943 | false | false | false | false |
siddug/headout-video-discovery | headout/Pods/Spring/Spring/DesignableTextField.swift | 10 | 3702 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
@IBDesignable public class DesignableTextField: SpringTextField {
@IBInspectable public var placeholderColor: UIColor = UIColor.clear {
didSet {
attributedPlaceholder = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: placeholderColor])
layoutSubviews()
}
}
@IBInspectable public var sidePadding: CGFloat = 0 {
didSet {
let padding = UIView(frame: CGRect(x: 0, y: 0, width: sidePadding, height: sidePadding))
leftViewMode = UITextFieldViewMode.always
leftView = padding
rightViewMode = UITextFieldViewMode.always
rightView = padding
}
}
@IBInspectable public var leftPadding: CGFloat = 0 {
didSet {
let padding = UIView(frame: CGRect(x: 0, y: 0, width: leftPadding, height: 0))
leftViewMode = UITextFieldViewMode.always
leftView = padding
}
}
@IBInspectable public var rightPadding: CGFloat = 0 {
didSet {
let padding = UIView(frame: CGRect(x: 0, y: 0, width: rightPadding, height: 0))
rightViewMode = UITextFieldViewMode.always
rightView = padding
}
}
@IBInspectable public var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable public var lineHeight: CGFloat = 1.5 {
didSet {
let font = UIFont(name: self.font!.fontName, size: self.font!.pointSize)
let text = self.text
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineHeight
let attributedString = NSMutableAttributedString(string: text!)
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
}
| mit | a8c4a33ae279d98cdfcc86aa3c4f7030 | 36.393939 | 143 | 0.646677 | 5.420205 | false | false | false | false |
LongPF/FaceTube | FaceTube/Record/FTCaptureViewController.swift | 1 | 2432 | //
// FTCaptureViewController.swift
// FaceTube
//
// Created by 龙鹏飞 on 2017/4/18.
// Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved.
//
import UIKit
class FTCaptureViewController: FTViewController {
/// 预览view
var previewView: FTPreviewView!
/// camer
var camera: FTCamera!
/// overlayView上面放着事件按钮
var overlayView: FTCameraOverlayView!
//MARK: ************************ life cycle ************************
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let eaglContext = FTContextManager.shared.eaglContext
self.previewView = FTPreviewView.init(frame: self.view.bounds, context: eaglContext!)
self.previewView.coreImageContext = FTContextManager.shared.ciContext
self.view.addSubview(self.previewView)
self.camera = FTCamera()
self.camera.imageTarget = self.previewView
self.overlayView = FTCameraOverlayView.init(camera: self.camera)
self.overlayView.frame = self.view.bounds
self.overlayView.delegate = self
self.view.addSubview(self.overlayView)
var error: NSError? = nil
if self.camera.setupSession(&error){
self.camera.startSession()
}else{
print(error?.localizedDescription ?? "setupSession error")
}
}
override func viewWillAppear(_ animated: Bool) {
UIApplication.shared.setStatusBarHidden(true, with: .none)
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let tabbarController = tabBarController as? FTTabbarContrller{
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.5, execute: {
tabbarController.showTabBar(show: false, aniamtie: true)
})
}
}
override var prefersStatusBarHidden: Bool{
return true;
}
}
extension FTCaptureViewController: FTCameraOverlayViewProtocol
{
func close2back() {
if let tabbarController = tabBarController as? FTTabbarContrller{
tabbarController.showTabBar(show: true, aniamtie: false)
}
tabBarController?.selectedIndex = 0
}
}
| mit | ad65ad994ae1fb81b84def93c99cd845 | 29.807692 | 93 | 0.633375 | 4.730315 | false | false | false | false |
lorentey/swift | test/SILGen/super.swift | 6 | 11036 |
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule %S/../Inputs/resilient_class.swift
// Note: we build fixed_layout_class without -enable-library-evolution, since with
// -enable-library-evolution even @_fixed_layout classes have resilient metadata, and
// we want to test the fragile access pattern here.
// RUN: %target-swift-frontend -emit-module -I %t -o %t %S/../Inputs/fixed_layout_class.swift
// RUN: %target-swift-emit-silgen -module-name super -parse-as-library -I %t %s | %FileCheck %s
import resilient_class
import fixed_layout_class
public class Parent {
public final var finalProperty: String {
return "Parent.finalProperty"
}
public var property: String {
return "Parent.property"
}
public final class var finalClassProperty: String {
return "Parent.finalProperty"
}
public class var classProperty: String {
return "Parent.property"
}
public func methodOnlyInParent() {}
public final func finalMethodOnlyInParent() {}
public func method() {}
public final class func finalClassMethodOnlyInParent() {}
public class func classMethod() {}
}
public class Child : Parent {
// CHECK-LABEL: sil [ossa] @$s5super5ChildC8propertySSvg : $@convention(method) (@guaranteed Child) -> @owned String {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $Child):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CAST_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent
// CHECK: [[CAST_SELF_BORROW:%[0-9]+]] = begin_borrow [[CAST_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$s5super6ParentC8propertySSvg : $@convention(method) (@guaranteed Parent) -> @owned String
// CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CAST_SELF_BORROW]])
// CHECK: end_borrow [[CAST_SELF_BORROW]]
// CHECK: destroy_value [[CAST_SELF_COPY]]
// CHECK: return [[RESULT]]
public override var property: String {
return super.property
}
// CHECK-LABEL: sil [ossa] @$s5super5ChildC13otherPropertySSvg : $@convention(method) (@guaranteed Child) -> @owned String {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $Child):
// CHECK: [[COPIED_SELF:%.*]] = copy_value [[SELF]]
// CHECK: [[CAST_SELF_COPY:%[0-9]+]] = upcast [[COPIED_SELF]] : $Child to $Parent
// CHECK: [[CAST_SELF_BORROW:%[0-9]+]] = begin_borrow [[CAST_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$s5super6ParentC13finalPropertySSvg
// CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CAST_SELF_BORROW]])
// CHECK: end_borrow [[CAST_SELF_BORROW]]
// CHECK: destroy_value [[CAST_SELF_COPY]]
// CHECK: return [[RESULT]]
public var otherProperty: String {
return super.finalProperty
}
}
public class Grandchild : Child {
// CHECK-LABEL: sil [ossa] @$s5super10GrandchildC06onlyInB0yyF
public func onlyInGrandchild() {
// CHECK: function_ref @$s5super6ParentC012methodOnlyInB0yyF : $@convention(method) (@guaranteed Parent) -> ()
super.methodOnlyInParent()
// CHECK: function_ref @$s5super6ParentC017finalMethodOnlyInB0yyF
super.finalMethodOnlyInParent()
}
// CHECK-LABEL: sil [ossa] @$s5super10GrandchildC6methodyyF
public override func method() {
// CHECK: function_ref @$s5super6ParentC6methodyyF : $@convention(method) (@guaranteed Parent) -> ()
super.method()
}
}
public class GreatGrandchild : Grandchild {
// CHECK-LABEL: sil [ossa] @$s5super15GreatGrandchildC6methodyyF
public override func method() {
// CHECK: function_ref @$s5super10GrandchildC6methodyyF : $@convention(method) (@guaranteed Grandchild) -> ()
super.method()
}
}
public class ChildToResilientParent : ResilientOutsideParent {
// CHECK-LABEL: sil [ossa] @$s5super22ChildToResilientParentC6methodyyF : $@convention(method) (@guaranteed ChildToResilientParent) -> ()
public override func method() {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $ChildToResilientParent):
// CHECK: [[COPY_SELF:%.*]] = copy_value [[SELF]]
// CHECK: [[UPCAST_SELF:%.*]] = upcast [[COPY_SELF]]
// CHECK: [[BORROW_UPCAST_SELF:%.*]] = begin_borrow [[UPCAST_SELF]]
// CHECK: [[CAST_BORROW_BACK_TO_BASE:%.*]] = unchecked_ref_cast [[BORROW_UPCAST_SELF]]
// CHECK: [[FUNC:%.*]] = super_method [[CAST_BORROW_BACK_TO_BASE]] : $ChildToResilientParent, #ResilientOutsideParent.method!1 : (ResilientOutsideParent) -> () -> (), $@convention(method) (@guaranteed ResilientOutsideParent) -> ()
// CHECK: end_borrow [[BORROW_UPCAST_SELF]]
// CHECK: apply [[FUNC]]([[UPCAST_SELF]])
super.method()
}
// CHECK: } // end sil function '$s5super22ChildToResilientParentC6methodyyF'
// CHECK-LABEL: sil [ossa] @$s5super22ChildToResilientParentC11classMethodyyFZ : $@convention(method) (@thick ChildToResilientParent.Type) -> ()
public override class func classMethod() {
// CHECK: bb0([[METASELF:%.*]] : $@thick ChildToResilientParent.Type):
// CHECK: [[UPCAST_METASELF:%.*]] = upcast [[METASELF]]
// CHECK: [[FUNC:%.*]] = super_method [[SELF]] : $@thick ChildToResilientParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideParent.Type) -> ()
// CHECK: apply [[FUNC]]([[UPCAST_METASELF]])
super.classMethod()
}
// CHECK: } // end sil function '$s5super22ChildToResilientParentC11classMethodyyFZ'
// CHECK-LABEL: sil [ossa] @$s5super22ChildToResilientParentC11returnsSelfACXDyFZ : $@convention(method) (@thick ChildToResilientParent.Type) -> @owned ChildToResilientParent
public class func returnsSelf() -> Self {
// CHECK: bb0([[METASELF:%.*]] : $@thick ChildToResilientParent.Type):
// CHECK: [[CAST_METASELF:%.*]] = unchecked_trivial_bit_cast [[METASELF]] : $@thick ChildToResilientParent.Type to $@thick @dynamic_self ChildToResilientParent.Type
// CHECK: [[UPCAST_CAST_METASELF:%.*]] = upcast [[CAST_METASELF]] : $@thick @dynamic_self ChildToResilientParent.Type to $@thick ResilientOutsideParent.Type
// CHECK: [[FUNC:%.*]] = super_method [[METASELF]] : $@thick ChildToResilientParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> ()
// CHECK: apply [[FUNC]]([[UPCAST_CAST_METASELF]])
// CHECK: unreachable
_ = 0
super.classMethod()
}
// CHECK: } // end sil function '$s5super22ChildToResilientParentC11returnsSelfACXDyFZ'
}
public class ChildToFixedParent : OutsideParent {
// CHECK-LABEL: sil [ossa] @$s5super18ChildToFixedParentC6methodyyF : $@convention(method) (@guaranteed ChildToFixedParent) -> ()
public override func method() {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $ChildToFixedParent):
// CHECK: [[COPY_SELF:%.*]] = copy_value [[SELF]]
// CHECK: [[UPCAST_COPY_SELF:%.*]] = upcast [[COPY_SELF]]
// CHECK: [[BORROWED_UPCAST_COPY_SELF:%.*]] = begin_borrow [[UPCAST_COPY_SELF]]
// CHECK: [[DOWNCAST_BORROWED_UPCAST_COPY_SELF:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_COPY_SELF]] : $OutsideParent to $ChildToFixedParent
// CHECK: [[FUNC:%.*]] = super_method [[DOWNCAST_BORROWED_UPCAST_COPY_SELF]] : $ChildToFixedParent, #OutsideParent.method!1 : (OutsideParent) -> () -> (), $@convention(method) (@guaranteed OutsideParent) -> ()
// CHECK: end_borrow [[BORROWED_UPCAST_COPY_SELF]]
// CHECK: apply [[FUNC]]([[UPCAST_COPY_SELF]])
super.method()
}
// CHECK: } // end sil function '$s5super18ChildToFixedParentC6methodyyF'
// CHECK-LABEL: sil [ossa] @$s5super18ChildToFixedParentC11classMethodyyFZ : $@convention(method) (@thick ChildToFixedParent.Type) -> ()
public override class func classMethod() {
// CHECK: bb0([[SELF:%.*]] : $@thick ChildToFixedParent.Type):
// CHECK: [[UPCAST_SELF:%.*]] = upcast [[SELF]]
// CHECK: [[FUNC:%.*]] = super_method [[SELF]] : $@thick ChildToFixedParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> (), $@convention(method) (@thick OutsideParent.Type) -> ()
// CHECK: apply [[FUNC]]([[UPCAST_SELF]])
super.classMethod()
}
// CHECK: } // end sil function '$s5super18ChildToFixedParentC11classMethodyyFZ'
// CHECK-LABEL: sil [ossa] @$s5super18ChildToFixedParentC11returnsSelfACXDyFZ : $@convention(method) (@thick ChildToFixedParent.Type) -> @owned ChildToFixedParent
public class func returnsSelf() -> Self {
// CHECK: bb0([[SELF:%.*]] : $@thick ChildToFixedParent.Type):
// CHECK: [[FIRST_CAST:%.*]] = unchecked_trivial_bit_cast [[SELF]]
// CHECK: [[SECOND_CAST:%.*]] = upcast [[FIRST_CAST]]
// CHECK: [[FUNC:%.*]] = super_method [[SELF]] : $@thick ChildToFixedParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> ()
// CHECK: apply [[FUNC]]([[SECOND_CAST]])
// CHECK: unreachable
_ = 0
super.classMethod()
}
// CHECK: } // end sil function '$s5super18ChildToFixedParentC11returnsSelfACXDyFZ'
}
// https://bugs.swift.org/browse/SR-10260 - super.foo() call across a module
// boundary from a subclass that does not override foo().
public class SuperCallToNonOverriddenMethod : OutsideParent {
public func newMethod() {
super.method()
}
}
public extension ResilientOutsideChild {
public func callSuperMethod() {
super.method()
}
public class func callSuperClassMethod() {
super.classMethod()
}
}
public class GenericBase<T> {
public func method() {}
}
public class GenericDerived<T> : GenericBase<T> {
public override func method() {
// CHECK-LABEL: sil private [ossa] @$s5super14GenericDerivedC6methodyyFyyXEfU_ : $@convention(thin) <T> (@guaranteed GenericDerived<T>) -> ()
// CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T>
// CHECK: return
{
super.method()
}()
// CHECK: } // end sil function '$s5super14GenericDerivedC6methodyyFyyXEfU_'
// CHECK-LABEL: sil private [ossa] @$s5super14GenericDerivedC6methodyyF13localFunctionL_yylF : $@convention(thin) <T> (@guaranteed GenericDerived<T>) -> ()
// CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T>
// CHECK: return
// CHECK: } // end sil function '$s5super14GenericDerivedC6methodyyF13localFunctionL_yylF'
func localFunction() {
super.method()
}
localFunction()
// CHECK-LABEL: sil private [ossa] @$s5super14GenericDerivedC6methodyyF15genericFunctionL_yyqd__r__lF : $@convention(thin) <T><U> (@in_guaranteed U, @guaranteed GenericDerived<T>) -> ()
// CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T>
// CHECK: return
func genericFunction<U>(_: U) {
super.method()
}
// CHECK: } // end sil function '$s5super14GenericDerivedC6methodyyF15genericFunctionL_yyqd__r__lF'
genericFunction(0)
}
}
| apache-2.0 | 7c180f9f98fcaeec0034dd8555786122 | 48.267857 | 238 | 0.66419 | 3.728378 | false | false | false | false |
jankase/JKJSON | JKJSON/Dictionary+Optional.swift | 1 | 808 | //
// Created by Jan Kase on 04/01/16.
// Copyright (c) 2016 Jan Kase. All rights reserved.
//
import Foundation
public extension Dictionary {
public mutating func setOptionalObject(theObject: Value?, forKey theKey: Key) {
if let aObject = theObject {
self[theKey] = aObject
}
}
}
public extension Optional where Wrapped: DictionaryLiteralConvertible, Wrapped.Key: Hashable {
public mutating func setOptionalObject(theObject: Wrapped.Value?, forKey theKey: Wrapped.Key) {
if let aObject = theObject {
if self == nil {
self = [:]
}
if var anDictionary = self as? Dictionary<Wrapped.Key, Wrapped.Value> {
anDictionary[theKey] = aObject
if let aWrapped = anDictionary as? Wrapped {
self = aWrapped
}
}
}
}
}
| mit | 69811412bcca3b416442565d4a5d4087 | 22.764706 | 97 | 0.648515 | 3.941463 | false | false | false | false |
ontouchstart/swift3-playground | single/今天是个好天气.playgroundbook/Contents/Chapters/今天是个好天气.playgroundchapter/Pages/今天是个好天气.playgroundpage/Contents.swift | 1 | 458 | /*:
# 今天是个好天气
Based on [gist](https://gist.github.com/Koze/6036c1dbda277ba2c6daf77d552537c2)
*/
import UIKit
import AVFoundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let string = "今天是个好天气"
let synthesizer = AVSpeechSynthesizer()
let voice = AVSpeechSynthesisVoice(language: "zh-CN")
let utterance = AVSpeechUtterance(string: string)
utterance.voice = voice
synthesizer.speak(utterance)
| mit | 7f7501c052b0e84bd0ee00b0b7fe45cb | 27.666667 | 78 | 0.811628 | 3.613445 | false | false | false | false |
phakphumi/Chula-Expo-iOS-Application | Chula Expo 2017/Chula Expo 2017/CoreData/StageActivity+CoreDataClass.swift | 1 | 6349 | //
// StageActivity+CoreDataClass.swift
//
//
// Created by Pakpoom on 2/24/2560 BE.
//
//
import Foundation
import CoreData
@objc(StageActivity)
public class StageActivity: NSManagedObject {
class func getNumberOfStage(inManageobejectcontext context: NSManagedObjectContext) {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "StageActivity")
do {
let results = try context.fetch(request) as? [StageActivity]
print("stage")
print(results?.count)
} catch {
print("Couldn't fetch results")
}
}
class func fetchStageActivities(inManageobjectcontext context: NSManagedObjectContext) {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "StageActivity")
do {
let results = try context.fetch(request) as? [StageActivity]
for result in results! {
print(result.toActivity)
}
} catch {
print("Couldn't fetch results")
}
}
class func makeRelation(activityId: String, inManageObjectContext context: NSManagedObjectContext) -> Bool? {
let stageRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "StageActivity")
stageRequest.predicate = NSPredicate(format: "activityId = %@", activityId)
if let stageResult = (try? context.fetch(stageRequest))?.first as? StageActivity {
// found this event in the database, return it ...
// print("Found \(stageResult.activityId!) in StageActivity")
let activityRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ActivityData")
activityRequest.predicate = NSPredicate(format: "activityId = %@", activityId)
if let activityResult = (try? context.fetch(activityRequest))?.first as? ActivityData
{
stageResult.toActivity = activityResult
// print("already make relationship btw stage and activity")
return true
}
}
print("fail to make relationship btw stage and activity")
return false
}
class func addData(activityId: String, activityData: ActivityData, stage: Int, inManageobjectcontext context: NSManagedObjectContext, completion: ((StageActivity?) -> Void)?) {
let stageRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "StageActivity")
stageRequest.predicate = NSPredicate(format: "activityId = %@", activityId)
if let result = (try? context.fetch(stageRequest))?.first as? StageActivity {
// found this event in the database, return it ...
// print("Found \(result.activityId!) in StageActivity")
completion?(result)
} else {
if let stageData = NSEntityDescription.insertNewObject(forEntityName: "StageActivity", into: context) as? StageActivity
{
stageData.activityId = activityId
stageData.stage = Int16(stage)
stageData.startDate = activityData.start
stageData.startDate = activityData.end
stageData.toActivity = activityData
completion?(stageData)
} else {
completion?(nil)
}
}
}
class func fetchNowOnStageID(manageObjectContext context: NSManagedObjectContext) -> [ActivityData?] {
var fetchResult = [ActivityData?]()
fetchResult = [nil,nil,nil]
let request1 = NSFetchRequest<NSFetchRequestResult>(entityName: "StageActivity")
let request2 = NSFetchRequest<NSFetchRequestResult>(entityName: "StageActivity")
let request3 = NSFetchRequest<NSFetchRequestResult>(entityName: "StageActivity")
let nowDate = Date()
request1.predicate = NSPredicate(format: "toActivity.end >= %@ AND toActivity.start <= %@ AND stage == 1", nowDate as NSDate, nowDate as NSDate)
request2.predicate = NSPredicate(format: "toActivity.end >= %@ AND toActivity.start <= %@ AND stage == 2", nowDate as NSDate, nowDate as NSDate)
request3.predicate = NSPredicate(format: "toActivity.end >= %@ AND toActivity.start <= %@ AND stage == 3", nowDate as NSDate, nowDate as NSDate)
var result1 = [Any]()
var result2 = [Any]()
var result3 = [Any]()
do {
result1 = try context.fetch(request1)
result2 = try context.fetch(request2)
result3 = try context.fetch(request3)
} catch {
print("Couldn't fetch results")
}
for item in result1{
if let stageAct = item as? StageActivity{
if nowDate.isInRangeOf(start: stageAct.toActivity?.start, end: stageAct.toActivity?.end){
fetchResult[0] = stageAct.toActivity
break
}
}
}
for item in result2{
if let stageAct = item as? StageActivity{
if nowDate.isInRangeOf(start: stageAct.toActivity?.start, end: stageAct.toActivity?.end){
fetchResult[1] = stageAct.toActivity
break
}
}
}
for item in result3{
if let stageAct = item as? StageActivity{
if nowDate.isInRangeOf(start: stageAct.toActivity?.start, end: stageAct.toActivity?.end){
fetchResult[2] = stageAct.toActivity
break
}
}
}
return fetchResult
}
}
| mit | 8813e747b2a0b987be4f97b2c448d4d7 | 32.592593 | 180 | 0.533785 | 5.689068 | false | false | false | false |
isgustavo/AnimatedMoviesMakeMeCry | iOS/Animated Movies Make Me Cry/Pods/Firebase/Samples/database/DatabaseExampleSwift/SignInViewController.swift | 9 | 5320 | //
// Copyright (c) 2015 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 UIKit
import Firebase
@objc(SignInViewController)
class SignInViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
var ref:FIRDatabaseReference!
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
override func viewDidAppear(animated: Bool) {
if FIRAuth.auth()?.currentUser != nil {
self.performSegueWithIdentifier("signIn", sender: nil)
}
ref = FIRDatabase.database().reference()
}
@IBAction func didTapEmailLogin(sender: AnyObject) {
if let email = self.emailField.text, password = self.passwordField.text {
showSpinner({
FIRAuth.auth()?.signInWithEmail(email, password: password) { (user, error) in
self.hideSpinner({
if let error = error {
self.showMessagePrompt(error.localizedDescription)
return
} else if let user = user {
self.ref.child("users").child(user.uid).observeSingleEventOfType(.Value, withBlock: { snapshot in
if (!snapshot.exists()) {
self.showTextInputPromptWithMessage("Username:") { (userPressedOK, username) in
if let username = username {
self.showSpinner({
let changeRequest = FIRAuth.auth()?.currentUser?.profileChangeRequest()
changeRequest?.displayName = username
changeRequest?.commitChangesWithCompletion() { (error) in
self.hideSpinner({
if let error = error {
self.showMessagePrompt(error.localizedDescription)
return
}
self.ref.child("users").child(FIRAuth.auth()!.currentUser!.uid).setValue(["username": username])
self.performSegueWithIdentifier("signIn", sender: nil)
})
}
})
} else {
self.showMessagePrompt("username can't be empty")
}
}
} else {
self.performSegueWithIdentifier("signIn", sender: nil)
}
})
}
})
}
})
} else {
self.showMessagePrompt("email/password can't be empty")
}
}
@IBAction func didTapSignUp(sender: AnyObject) {
showTextInputPromptWithMessage("Email:") { (userPressedOK, email) in
if let email = email {
self.showTextInputPromptWithMessage("Password:") { (userPressedOK, password) in
if let password = password {
self.showTextInputPromptWithMessage("Username:") { (userPressedOK, username) in
if let username = username {
self.showSpinner({
FIRAuth.auth()?.createUserWithEmail(email, password: password) { (user, error) in
self.hideSpinner({
if let error = error {
self.showMessagePrompt(error.localizedDescription)
return
}
self.showSpinner({
let changeRequest = FIRAuth.auth()?.currentUser?.profileChangeRequest()
changeRequest?.displayName = username
changeRequest?.commitChangesWithCompletion() { (error) in
self.hideSpinner({
if let error = error {
self.showMessagePrompt(error.localizedDescription)
return
}
// [START basic_write]
self.ref.child("users").child(user!.uid).setValue(["username": username])
// [END basic_write]
self.performSegueWithIdentifier("signIn", sender: nil)
})
}
})
})
}
})
} else {
self.showMessagePrompt("username can't be empty")
}
}
} else {
self.showMessagePrompt("password can't be empty")
}
}
} else {
self.showMessagePrompt("email can't be empty")
}
}
}
// MARK: - UITextFieldDelegate protocol methods
func textFieldShouldReturn(textField: UITextField) -> Bool {
didTapEmailLogin([])
return true
}
}
| apache-2.0 | 53d989ebb57e5ae6f96250f04f5beab9 | 38.117647 | 124 | 0.536466 | 5.570681 | false | false | false | false |
slavapestov/swift | test/1_stdlib/Runtime.swift | 1 | 42348 | // RUN: rm -rf %t && mkdir %t
//
// RUN: %target-build-swift -parse-stdlib -module-name a %s -o %t.out
// RUN: %target-run %t.out
// REQUIRES: executable_test
import Swift
import StdlibUnittest
import SwiftShims
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
#if _runtime(_ObjC)
import ObjectiveC
#endif
var swiftObjectCanaryCount = 0
class SwiftObjectCanary {
init() {
swiftObjectCanaryCount += 1
}
deinit {
swiftObjectCanaryCount -= 1
}
}
struct SwiftObjectCanaryStruct {
var ref = SwiftObjectCanary()
}
var Runtime = TestSuite("Runtime")
Runtime.test("_canBeClass") {
expectEqual(1, _canBeClass(SwiftObjectCanary.self))
expectEqual(0, _canBeClass(SwiftObjectCanaryStruct.self))
typealias SwiftClosure = () -> ()
expectEqual(0, _canBeClass(SwiftClosure.self))
}
//===----------------------------------------------------------------------===//
// The protocol should be defined in the standard library, otherwise the cast
// does not work.
typealias P1 = BooleanType
typealias P2 = CustomStringConvertible
protocol Q1 {}
// A small struct that can be stored inline in an opaque buffer.
struct StructConformsToP1 : BooleanType, Q1 {
var boolValue: Bool {
return true
}
}
// A small struct that can be stored inline in an opaque buffer.
struct Struct2ConformsToP1<T : BooleanType> : BooleanType, Q1 {
init(_ value: T) {
self.value = value
}
var boolValue: Bool {
return value.boolValue
}
var value: T
}
// A large struct that cannot be stored inline in an opaque buffer.
struct Struct3ConformsToP2 : CustomStringConvertible, Q1 {
var a: UInt64 = 10
var b: UInt64 = 20
var c: UInt64 = 30
var d: UInt64 = 40
var description: String {
// Don't rely on string interpolation, it uses the casts that we are trying
// to test.
var result = ""
result += _uint64ToString(a) + " "
result += _uint64ToString(b) + " "
result += _uint64ToString(c) + " "
result += _uint64ToString(d)
return result
}
}
// A large struct that cannot be stored inline in an opaque buffer.
struct Struct4ConformsToP2<T : CustomStringConvertible> : CustomStringConvertible, Q1 {
var value: T
var e: UInt64 = 50
var f: UInt64 = 60
var g: UInt64 = 70
var h: UInt64 = 80
init(_ value: T) {
self.value = value
}
var description: String {
// Don't rely on string interpolation, it uses the casts that we are trying
// to test.
var result = value.description + " "
result += _uint64ToString(e) + " "
result += _uint64ToString(f) + " "
result += _uint64ToString(g) + " "
result += _uint64ToString(h)
return result
}
}
struct StructDoesNotConformToP1 : Q1 {}
class ClassConformsToP1 : BooleanType, Q1 {
var boolValue: Bool {
return true
}
}
class Class2ConformsToP1<T : BooleanType> : BooleanType, Q1 {
init(_ value: T) {
self.value = [ value ]
}
var boolValue: Bool {
return value[0].boolValue
}
// FIXME: should be "var value: T", but we don't support it now.
var value: Array<T>
}
class ClassDoesNotConformToP1 : Q1 {}
Runtime.test("dynamicCasting with as") {
var someP1Value = StructConformsToP1()
var someP1Value2 = Struct2ConformsToP1(true)
var someNotP1Value = StructDoesNotConformToP1()
var someP2Value = Struct3ConformsToP2()
var someP2Value2 = Struct4ConformsToP2(Struct3ConformsToP2())
var someP1Ref = ClassConformsToP1()
var someP1Ref2 = Class2ConformsToP1(true)
var someNotP1Ref = ClassDoesNotConformToP1()
expectTrue(someP1Value is P1)
expectTrue(someP1Value2 is P1)
expectFalse(someNotP1Value is P1)
expectTrue(someP2Value is P2)
expectTrue(someP2Value2 is P2)
expectTrue(someP1Ref is P1)
expectTrue(someP1Ref2 is P1)
expectFalse(someNotP1Ref is P1)
expectTrue(someP1Value as P1 is P1)
expectTrue(someP1Value2 as P1 is P1)
expectTrue(someP2Value as P2 is P2)
expectTrue(someP2Value2 as P2 is P2)
expectTrue(someP1Ref as P1 is P1)
expectTrue(someP1Value as Q1 is P1)
expectTrue(someP1Value2 as Q1 is P1)
expectFalse(someNotP1Value as Q1 is P1)
expectTrue(someP2Value as Q1 is P2)
expectTrue(someP2Value2 as Q1 is P2)
expectTrue(someP1Ref as Q1 is P1)
expectTrue(someP1Ref2 as Q1 is P1)
expectFalse(someNotP1Ref as Q1 is P1)
expectTrue(someP1Value as Any is P1)
expectTrue(someP1Value2 as Any is P1)
expectFalse(someNotP1Value as Any is P1)
expectTrue(someP2Value as Any is P2)
expectTrue(someP2Value2 as Any is P2)
expectTrue(someP1Ref as Any is P1)
expectTrue(someP1Ref2 as Any is P1)
expectFalse(someNotP1Ref as Any is P1)
expectTrue(someP1Ref as AnyObject is P1)
expectTrue(someP1Ref2 as AnyObject is P1)
expectFalse(someNotP1Ref as AnyObject is P1)
expectTrue((someP1Value as P1).boolValue)
expectTrue((someP1Value2 as P1).boolValue)
expectEqual("10 20 30 40", (someP2Value as P2).description)
expectEqual("10 20 30 40 50 60 70 80", (someP2Value2 as P2).description)
expectTrue((someP1Ref as P1).boolValue)
expectTrue((someP1Ref2 as P1).boolValue)
expectTrue(((someP1Value as Q1) as! P1).boolValue)
expectTrue(((someP1Value2 as Q1) as! P1).boolValue)
expectEqual("10 20 30 40", ((someP2Value as Q1) as! P2).description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Q1) as! P2).description)
expectTrue(((someP1Ref as Q1) as! P1).boolValue)
expectTrue(((someP1Ref2 as Q1) as! P1).boolValue)
expectTrue(((someP1Value as Any) as! P1).boolValue)
expectTrue(((someP1Value2 as Any) as! P1).boolValue)
expectEqual("10 20 30 40", ((someP2Value as Any) as! P2).description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Any) as! P2).description)
expectTrue(((someP1Ref as Any) as! P1).boolValue)
expectTrue(((someP1Ref2 as Any) as! P1).boolValue)
expectTrue(((someP1Ref as AnyObject) as! P1).boolValue)
expectEmpty((someNotP1Value as? P1))
expectEmpty((someNotP1Ref as? P1))
expectTrue(((someP1Value as Q1) as? P1)!.boolValue)
expectTrue(((someP1Value2 as Q1) as? P1)!.boolValue)
expectEmpty(((someNotP1Value as Q1) as? P1))
expectEqual("10 20 30 40", ((someP2Value as Q1) as? P2)!.description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Q1) as? P2)!.description)
expectTrue(((someP1Ref as Q1) as? P1)!.boolValue)
expectTrue(((someP1Ref2 as Q1) as? P1)!.boolValue)
expectEmpty(((someNotP1Ref as Q1) as? P1))
expectTrue(((someP1Value as Any) as? P1)!.boolValue)
expectTrue(((someP1Value2 as Any) as? P1)!.boolValue)
expectEmpty(((someNotP1Value as Any) as? P1))
expectEqual("10 20 30 40", ((someP2Value as Any) as? P2)!.description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Any) as? P2)!.description)
expectTrue(((someP1Ref as Any) as? P1)!.boolValue)
expectTrue(((someP1Ref2 as Any) as? P1)!.boolValue)
expectEmpty(((someNotP1Ref as Any) as? P1))
expectTrue(((someP1Ref as AnyObject) as? P1)!.boolValue)
expectTrue(((someP1Ref2 as AnyObject) as? P1)!.boolValue)
expectEmpty(((someNotP1Ref as AnyObject) as? P1))
let doesThrow: Int throws -> Int = { $0 }
let doesNotThrow: String -> String = { $0 }
var any: Any = doesThrow
expectTrue(doesThrow as Any is Int throws -> Int)
expectFalse(doesThrow as Any is String throws -> Int)
expectFalse(doesThrow as Any is String throws -> String)
expectFalse(doesThrow as Any is Int throws -> String)
expectFalse(doesThrow as Any is Int -> Int)
expectFalse(doesThrow as Any is String throws -> String)
expectFalse(doesThrow as Any is String -> String)
expectTrue(doesNotThrow as Any is String throws -> String)
expectTrue(doesNotThrow as Any is String -> String)
expectFalse(doesNotThrow as Any is Int -> String)
expectFalse(doesNotThrow as Any is Int -> Int)
expectFalse(doesNotThrow as Any is String -> Int)
expectFalse(doesNotThrow as Any is Int throws -> Int)
expectFalse(doesNotThrow as Any is Int -> Int)
}
extension Int {
class ExtensionClassConformsToP2 : P2 {
var description: String { return "abc" }
}
private class PrivateExtensionClassConformsToP2 : P2 {
var description: String { return "def" }
}
}
Runtime.test("dynamic cast to existential with cross-module extensions") {
let internalObj = Int.ExtensionClassConformsToP2()
let privateObj = Int.PrivateExtensionClassConformsToP2()
expectTrue(internalObj is P2)
expectTrue(privateObj is P2)
}
class SomeClass {}
struct SomeStruct {}
enum SomeEnum {
case A
init() { self = .A }
}
Runtime.test("typeName") {
expectEqual("a.SomeClass", _typeName(SomeClass.self))
expectEqual("a.SomeStruct", _typeName(SomeStruct.self))
expectEqual("a.SomeEnum", _typeName(SomeEnum.self))
expectEqual("protocol<>.Protocol", _typeName(Any.Protocol.self))
expectEqual("Swift.AnyObject.Protocol", _typeName(AnyObject.Protocol.self))
expectEqual("Swift.AnyObject.Type.Protocol", _typeName(AnyClass.Protocol.self))
expectEqual("Swift.Optional<Swift.AnyObject>.Type", _typeName((AnyObject?).Type.self))
var a: Any = SomeClass()
expectEqual("a.SomeClass", _typeName(a.dynamicType))
a = SomeStruct()
expectEqual("a.SomeStruct", _typeName(a.dynamicType))
a = SomeEnum()
expectEqual("a.SomeEnum", _typeName(a.dynamicType))
a = AnyObject.self
expectEqual("Swift.AnyObject.Protocol", _typeName(a.dynamicType))
a = AnyClass.self
expectEqual("Swift.AnyObject.Type.Protocol", _typeName(a.dynamicType))
a = (AnyObject?).self
expectEqual("Swift.Optional<Swift.AnyObject>.Type",
_typeName(a.dynamicType))
a = Any.self
expectEqual("protocol<>.Protocol", _typeName(a.dynamicType))
}
class SomeSubclass : SomeClass {}
protocol SomeProtocol {}
class SomeConformingClass : SomeProtocol {}
Runtime.test("typeByName") {
expectTrue(_typeByName("a.SomeClass") == SomeClass.self)
expectTrue(_typeByName("a.SomeSubclass") == SomeSubclass.self)
// name lookup will be via protocol conformance table
expectTrue(_typeByName("a.SomeConformingClass") == SomeConformingClass.self)
}
Runtime.test("demangleName") {
expectEqual("", _stdlib_demangleName(""))
expectEqual("abc", _stdlib_demangleName("abc"))
expectEqual("\0", _stdlib_demangleName("\0"))
expectEqual("Swift.Double", _stdlib_demangleName("_TtSd"))
expectEqual("x.a : x.Foo<x.Foo<x.Foo<Swift.Int, Swift.Int>, x.Foo<Swift.Int, Swift.Int>>, x.Foo<x.Foo<Swift.Int, Swift.Int>, x.Foo<Swift.Int, Swift.Int>>>",
_stdlib_demangleName("_Tv1x1aGCS_3FooGS0_GS0_SiSi_GS0_SiSi__GS0_GS0_SiSi_GS0_SiSi___"))
expectEqual("Foobar", _stdlib_demangleName("_TtC13__lldb_expr_46Foobar"))
}
Runtime.test("_stdlib_atomicCompareExchangeStrongPtr") {
typealias IntPtr = UnsafeMutablePointer<Int>
var origP1 = IntPtr(bitPattern: 0x10101010)
var origP2 = IntPtr(bitPattern: 0x20202020)
var origP3 = IntPtr(bitPattern: 0x30303030)
do {
var object = origP1
var expected = origP1
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &object, expected: &expected, desired: origP2)
expectTrue(r)
expectEqual(origP2, object)
expectEqual(origP1, expected)
}
do {
var object = origP1
var expected = origP2
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &object, expected: &expected, desired: origP3)
expectFalse(r)
expectEqual(origP1, object)
expectEqual(origP1, expected)
}
struct FooStruct {
var i: Int
var object: IntPtr
var expected: IntPtr
init(_ object: IntPtr, _ expected: IntPtr) {
self.i = 0
self.object = object
self.expected = expected
}
}
do {
var foo = FooStruct(origP1, origP1)
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &foo.object, expected: &foo.expected, desired: origP2)
expectTrue(r)
expectEqual(origP2, foo.object)
expectEqual(origP1, foo.expected)
}
do {
var foo = FooStruct(origP1, origP2)
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &foo.object, expected: &foo.expected, desired: origP3)
expectFalse(r)
expectEqual(origP1, foo.object)
expectEqual(origP1, foo.expected)
}
}
Runtime.test("casting AnyObject to class metatypes") {
do {
var ao: AnyObject = SomeClass()
expectTrue(ao as? Any.Type == nil)
expectTrue(ao as? AnyClass == nil)
}
do {
var a: Any = SomeClass()
expectTrue(a as? Any.Type == nil)
expectTrue(a as? AnyClass == nil)
a = SomeClass.self
expectTrue(a as? Any.Type == SomeClass.self)
expectTrue(a as? AnyClass == SomeClass.self)
expectTrue(a as? SomeClass.Type == SomeClass.self)
}
}
class Malkovich: Malkovichable {
var malkovich: String { return "malkovich" }
}
protocol Malkovichable: class {
var malkovich: String { get }
}
struct GenericStructWithReferenceStorage<T> {
var a: T
unowned(safe) var unownedConcrete: Malkovich
unowned(unsafe) var unmanagedConcrete: Malkovich
weak var weakConcrete: Malkovich?
unowned(safe) var unownedProto: Malkovichable
unowned(unsafe) var unmanagedProto: Malkovichable
weak var weakProto: Malkovichable?
}
func exerciseReferenceStorageInGenericContext<T>(
x: GenericStructWithReferenceStorage<T>,
forceCopy y: GenericStructWithReferenceStorage<T>
) {
expectEqual(x.unownedConcrete.malkovich, "malkovich")
expectEqual(x.unmanagedConcrete.malkovich, "malkovich")
expectEqual(x.weakConcrete!.malkovich, "malkovich")
expectEqual(x.unownedProto.malkovich, "malkovich")
expectEqual(x.unmanagedProto.malkovich, "malkovich")
expectEqual(x.weakProto!.malkovich, "malkovich")
expectEqual(y.unownedConcrete.malkovich, "malkovich")
expectEqual(y.unmanagedConcrete.malkovich, "malkovich")
expectEqual(y.weakConcrete!.malkovich, "malkovich")
expectEqual(y.unownedProto.malkovich, "malkovich")
expectEqual(y.unmanagedProto.malkovich, "malkovich")
expectEqual(y.weakProto!.malkovich, "malkovich")
}
Runtime.test("Struct layout with reference storage types") {
let malkovich = Malkovich()
let x = GenericStructWithReferenceStorage(a: malkovich,
unownedConcrete: malkovich,
unmanagedConcrete: malkovich,
weakConcrete: malkovich,
unownedProto: malkovich,
unmanagedProto: malkovich,
weakProto: malkovich)
exerciseReferenceStorageInGenericContext(x, forceCopy: x)
expectEqual(x.unownedConcrete.malkovich, "malkovich")
expectEqual(x.unmanagedConcrete.malkovich, "malkovich")
expectEqual(x.weakConcrete!.malkovich, "malkovich")
expectEqual(x.unownedProto.malkovich, "malkovich")
expectEqual(x.unmanagedProto.malkovich, "malkovich")
expectEqual(x.weakProto!.malkovich, "malkovich")
// Make sure malkovich lives long enough.
print(malkovich)
}
var Reflection = TestSuite("Reflection")
func wrap1 (x: Any) -> Any { return x }
func wrap2<T>(x: T) -> Any { return wrap1(x) }
func wrap3 (x: Any) -> Any { return wrap2(x) }
func wrap4<T>(x: T) -> Any { return wrap3(x) }
func wrap5 (x: Any) -> Any { return wrap4(x) }
class JustNeedAMetatype {}
Reflection.test("nested existential containers") {
let wrapped = wrap5(JustNeedAMetatype.self)
expectEqual("\(wrapped)", "JustNeedAMetatype")
}
Reflection.test("dumpToAStream") {
var output = ""
dump([ 42, 4242 ], &output)
expectEqual("▿ 2 elements\n - 42\n - 4242\n", output)
}
struct StructWithDefaultMirror {
let s: String
init (_ s: String) {
self.s = s
}
}
Reflection.test("Struct/NonGeneric/DefaultMirror") {
do {
var output = ""
dump(StructWithDefaultMirror("123"), &output)
expectEqual("▿ a.StructWithDefaultMirror\n - s: \"123\"\n", output)
}
do {
// Build a String around an interpolation as a way of smoke-testing that
// the internal _MirrorType implementation gets memory management right.
var output = ""
dump(StructWithDefaultMirror("\(456)"), &output)
expectEqual("▿ a.StructWithDefaultMirror\n - s: \"456\"\n", output)
}
expectEqual(.Struct, Mirror(reflecting: StructWithDefaultMirror("")).displayStyle)
}
struct GenericStructWithDefaultMirror<T, U> {
let first: T
let second: U
}
Reflection.test("Struct/Generic/DefaultMirror") {
do {
var value = GenericStructWithDefaultMirror<Int, [Any?]>(
first: 123,
second: [ "abc", 456, 789.25 ])
var output = ""
dump(value, &output)
let expected =
"▿ a.GenericStructWithDefaultMirror<Swift.Int, Swift.Array<Swift.Optional<protocol<>>>>\n" +
" - first: 123\n" +
" ▿ second: 3 elements\n" +
" ▿ Optional(\"abc\")\n" +
" - Some: \"abc\"\n" +
" ▿ Optional(456)\n" +
" - Some: 456\n" +
" ▿ Optional(789.25)\n" +
" - Some: 789.25\n"
expectEqual(expected, output)
}
}
enum NoPayloadEnumWithDefaultMirror {
case A, ß
}
Reflection.test("Enum/NoPayload/DefaultMirror") {
do {
let value: [NoPayloadEnumWithDefaultMirror] =
[.A, .ß]
var output = ""
dump(value, &output)
let expected =
"▿ 2 elements\n" +
" - a.NoPayloadEnumWithDefaultMirror.A\n" +
" - a.NoPayloadEnumWithDefaultMirror.ß\n"
expectEqual(expected, output)
}
}
enum SingletonNonGenericEnumWithDefaultMirror {
case OnlyOne(Int)
}
Reflection.test("Enum/SingletonNonGeneric/DefaultMirror") {
do {
let value = SingletonNonGenericEnumWithDefaultMirror.OnlyOne(5)
var output = ""
dump(value, &output)
let expected =
"▿ a.SingletonNonGenericEnumWithDefaultMirror.OnlyOne\n" +
" - OnlyOne: 5\n"
expectEqual(expected, output)
}
}
enum SingletonGenericEnumWithDefaultMirror<T> {
case OnlyOne(T)
}
Reflection.test("Enum/SingletonGeneric/DefaultMirror") {
do {
let value = SingletonGenericEnumWithDefaultMirror.OnlyOne("IIfx")
var output = ""
dump(value, &output)
let expected =
"▿ a.SingletonGenericEnumWithDefaultMirror<Swift.String>.OnlyOne\n" +
" - OnlyOne: \"IIfx\"\n"
expectEqual(expected, output)
}
expectEqual(0, LifetimeTracked.instances)
do {
let value = SingletonGenericEnumWithDefaultMirror.OnlyOne(
LifetimeTracked(0))
expectEqual(1, LifetimeTracked.instances)
var output = ""
dump(value, &output)
}
expectEqual(0, LifetimeTracked.instances)
}
enum SinglePayloadNonGenericEnumWithDefaultMirror {
case Cat
case Dog
case Volleyball(String, Int)
}
Reflection.test("Enum/SinglePayloadNonGeneric/DefaultMirror") {
do {
let value: [SinglePayloadNonGenericEnumWithDefaultMirror] =
[.Cat,
.Dog,
.Volleyball("Wilson", 2000)]
var output = ""
dump(value, &output)
let expected =
"▿ 3 elements\n" +
" - a.SinglePayloadNonGenericEnumWithDefaultMirror.Cat\n" +
" - a.SinglePayloadNonGenericEnumWithDefaultMirror.Dog\n" +
" ▿ a.SinglePayloadNonGenericEnumWithDefaultMirror.Volleyball\n" +
" ▿ Volleyball: (2 elements)\n" +
" - .0: \"Wilson\"\n" +
" - .1: 2000\n"
expectEqual(expected, output)
}
}
enum SinglePayloadGenericEnumWithDefaultMirror<T, U> {
case Well
case Faucet
case Pipe(T, U)
}
Reflection.test("Enum/SinglePayloadGeneric/DefaultMirror") {
do {
let value: [SinglePayloadGenericEnumWithDefaultMirror<Int, [Int]>] =
[.Well,
.Faucet,
.Pipe(408, [415])]
var output = ""
dump(value, &output)
let expected =
"▿ 3 elements\n" +
" - a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Well\n" +
" - a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Faucet\n" +
" ▿ a.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Pipe\n" +
" ▿ Pipe: (2 elements)\n" +
" - .0: 408\n" +
" ▿ .1: 1 element\n" +
" - 415\n"
expectEqual(expected, output)
}
}
enum MultiPayloadTagBitsNonGenericEnumWithDefaultMirror {
case Plus
case SE30
case Classic(mhz: Int)
case Performa(model: Int)
}
Reflection.test("Enum/MultiPayloadTagBitsNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadTagBitsNonGenericEnumWithDefaultMirror] =
[.Plus,
.SE30,
.Classic(mhz: 16),
.Performa(model: 220)]
var output = ""
dump(value, &output)
let expected =
"▿ 4 elements\n" +
" - a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Plus\n" +
" - a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.SE30\n" +
" ▿ a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Classic\n" +
" - Classic: 16\n" +
" ▿ a.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Performa\n" +
" - Performa: 220\n"
expectEqual(expected, output)
}
}
class Floppy {
let capacity: Int
init(capacity: Int) { self.capacity = capacity }
}
class CDROM {
let capacity: Int
init(capacity: Int) { self.capacity = capacity }
}
enum MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror {
case MacWrite
case MacPaint
case FileMaker
case ClarisWorks(floppy: Floppy)
case HyperCard(cdrom: CDROM)
}
Reflection.test("Enum/MultiPayloadSpareBitsNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror] =
[.MacWrite,
.MacPaint,
.FileMaker,
.ClarisWorks(floppy: Floppy(capacity: 800)),
.HyperCard(cdrom: CDROM(capacity: 600))]
var output = ""
dump(value, &output)
let expected =
"▿ 5 elements\n" +
" - a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacWrite\n" +
" - a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacPaint\n" +
" - a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.FileMaker\n" +
" ▿ a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.ClarisWorks\n" +
" ▿ ClarisWorks: a.Floppy #0\n" +
" - capacity: 800\n" +
" ▿ a.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.HyperCard\n" +
" ▿ HyperCard: a.CDROM #1\n" +
" - capacity: 600\n"
expectEqual(expected, output)
}
}
enum MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror {
case MacWrite
case MacPaint
case FileMaker
case ClarisWorks(floppy: Bool)
case HyperCard(cdrom: Bool)
}
Reflection.test("Enum/MultiPayloadTagBitsSmallNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror] =
[.MacWrite,
.MacPaint,
.FileMaker,
.ClarisWorks(floppy: true),
.HyperCard(cdrom: false)]
var output = ""
dump(value, &output)
let expected =
"▿ 5 elements\n" +
" - a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacWrite\n" +
" - a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacPaint\n" +
" - a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.FileMaker\n" +
" ▿ a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.ClarisWorks\n" +
" - ClarisWorks: true\n" +
" ▿ a.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.HyperCard\n" +
" - HyperCard: false\n"
expectEqual(expected, output)
}
}
enum MultiPayloadGenericEnumWithDefaultMirror<T, U> {
case IIe
case IIgs
case Centris(ram: T)
case Quadra(hdd: U)
case PowerBook170
case PowerBookDuo220
}
Reflection.test("Enum/MultiPayloadGeneric/DefaultMirror") {
do {
let value: [MultiPayloadGenericEnumWithDefaultMirror<Int, String>] =
[.IIe,
.IIgs,
.Centris(ram: 4096),
.Quadra(hdd: "160MB"),
.PowerBook170,
.PowerBookDuo220]
var output = ""
dump(value, &output)
let expected =
"▿ 6 elements\n" +
" - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIe\n" +
" - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIgs\n" +
" ▿ a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Centris\n" +
" - Centris: 4096\n" +
" ▿ a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Quadra\n" +
" - Quadra: \"160MB\"\n" +
" - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBook170\n" +
" - a.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBookDuo220\n"
expectEqual(expected, output)
}
expectEqual(0, LifetimeTracked.instances)
do {
let value = MultiPayloadGenericEnumWithDefaultMirror<LifetimeTracked,
LifetimeTracked>
.Quadra(hdd: LifetimeTracked(0))
expectEqual(1, LifetimeTracked.instances)
var output = ""
dump(value, &output)
}
expectEqual(0, LifetimeTracked.instances)
}
enum Foo<T> {
indirect case Foo(Int)
case Bar(T)
}
enum List<T> {
case Nil
indirect case Cons(first: T, rest: List<T>)
}
Reflection.test("Enum/IndirectGeneric/DefaultMirror") {
let x = Foo<String>.Foo(22)
let y = Foo<String>.Bar("twenty-two")
expectEqual("\(x)", "Foo(22)")
expectEqual("\(y)", "Bar(\"twenty-two\")")
let list = List.Cons(first: 0, rest: .Cons(first: 1, rest: .Nil))
expectEqual("\(list)",
"Cons(0, a.List<Swift.Int>.Cons(1, a.List<Swift.Int>.Nil))")
}
class Brilliant : CustomReflectable {
let first: Int
let second: String
init(_ fst: Int, _ snd: String) {
self.first = fst
self.second = snd
}
func customMirror() -> Mirror {
return Mirror(self, children: ["first": first, "second": second, "self": self])
}
}
/// Subclasses inherit their parents' custom mirrors.
class Irradiant : Brilliant {
init() {
super.init(400, "")
}
}
Reflection.test("CustomMirror") {
do {
var output = ""
dump(Brilliant(123, "four five six"), &output)
let expected =
"▿ a.Brilliant #0\n" +
" - first: 123\n" +
" - second: \"four five six\"\n" +
" ▿ self: a.Brilliant #0\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), &output, maxDepth: 0)
expectEqual("▹ a.Brilliant #0\n", output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), &output, maxItems: 3)
let expected =
"▿ a.Brilliant #0\n" +
" - first: 123\n" +
" - second: \"four five six\"\n" +
" (1 more child)\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), &output, maxItems: 2)
let expected =
"▿ a.Brilliant #0\n" +
" - first: 123\n" +
" (2 more children)\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), &output, maxItems: 1)
let expected =
"▿ a.Brilliant #0\n" +
" (3 children)\n"
expectEqual(expected, output)
}
do {
// Check that object identifiers are unique to class instances.
let a = Brilliant(1, "")
let b = Brilliant(2, "")
let c = Brilliant(3, "")
// Equatable
checkEquatable(true, ObjectIdentifier(a), ObjectIdentifier(a))
checkEquatable(false, ObjectIdentifier(a), ObjectIdentifier(b))
// Comparable
func isComparable<X : Comparable>(x: X) {}
isComparable(ObjectIdentifier(a))
// Check the ObjectIdentifier created is stable
expectTrue(
(ObjectIdentifier(a) < ObjectIdentifier(b))
!= (ObjectIdentifier(a) > ObjectIdentifier(b)))
expectFalse(
ObjectIdentifier(a) >= ObjectIdentifier(b)
&& ObjectIdentifier(a) <= ObjectIdentifier(b))
// Check ordering is transitive
expectEqual(
[ ObjectIdentifier(a), ObjectIdentifier(b), ObjectIdentifier(c) ].sort(),
[ ObjectIdentifier(c), ObjectIdentifier(b), ObjectIdentifier(a) ].sort())
}
}
Reflection.test("CustomMirrorIsInherited") {
do {
var output = ""
dump(Irradiant(), &output)
let expected =
"▿ a.Brilliant #0\n" +
" - first: 400\n" +
" - second: \"\"\n" +
" ▿ self: a.Brilliant #0\n"
expectEqual(expected, output)
}
}
protocol SomeNativeProto {}
extension Int: SomeNativeProto {}
Reflection.test("MetatypeMirror") {
do {
var output = ""
let concreteMetatype = Int.self
dump(concreteMetatype, &output)
let expectedInt = "- Swift.Int #0\n"
expectEqual(expectedInt, output)
let anyMetatype: Any.Type = Int.self
output = ""
dump(anyMetatype, &output)
expectEqual(expectedInt, output)
let nativeProtocolMetatype: SomeNativeProto.Type = Int.self
output = ""
dump(nativeProtocolMetatype, &output)
expectEqual(expectedInt, output)
let concreteClassMetatype = SomeClass.self
let expectedSomeClass = "- a.SomeClass #0\n"
output = ""
dump(concreteClassMetatype, &output)
expectEqual(expectedSomeClass, output)
let nativeProtocolConcreteMetatype = SomeNativeProto.self
let expectedNativeProtocolConcrete = "- a.SomeNativeProto #0\n"
output = ""
dump(nativeProtocolConcreteMetatype, &output)
expectEqual(expectedNativeProtocolConcrete, output)
}
}
Reflection.test("TupleMirror") {
do {
var output = ""
let tuple =
(Brilliant(384, "seven six eight"), StructWithDefaultMirror("nine"))
dump(tuple, &output)
let expected =
"▿ (2 elements)\n" +
" ▿ .0: a.Brilliant #0\n" +
" - first: 384\n" +
" - second: \"seven six eight\"\n" +
" ▿ self: a.Brilliant #0\n" +
" ▿ .1: a.StructWithDefaultMirror\n" +
" - s: \"nine\"\n"
expectEqual(expected, output)
expectEqual(.Tuple, Mirror(reflecting: tuple).displayStyle)
}
do {
// A tuple of stdlib types with mirrors.
var output = ""
let tuple = (1, 2.5, false, "three")
dump(tuple, &output)
let expected =
"▿ (4 elements)\n" +
" - .0: 1\n" +
" - .1: 2.5\n" +
" - .2: false\n" +
" - .3: \"three\"\n"
expectEqual(expected, output)
}
do {
// A nested tuple.
var output = ""
let tuple = (1, ("Hello", "World"))
dump(tuple, &output)
let expected =
"▿ (2 elements)\n" +
" - .0: 1\n" +
" ▿ .1: (2 elements)\n" +
" - .0: \"Hello\"\n" +
" - .1: \"World\"\n"
expectEqual(expected, output)
}
}
class DullClass {}
Reflection.test("ClassReflection") {
expectEqual(.Class, Mirror(reflecting: DullClass()).displayStyle)
}
Reflection.test("String/Mirror") {
do {
var output = ""
dump("", &output)
let expected =
"- \"\"\n"
expectEqual(expected, output)
}
do {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}", &output)
let expected =
"- \"\u{61}\u{304b}\u{3099}\u{1f425}\"\n"
expectEqual(expected, output)
}
}
Reflection.test("String.UTF8View/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
var output = ""
dump("\u{61}\u{304b}\u{3099}".utf8, &output)
let expected =
"▿ UTF8View(\"\u{61}\u{304b}\u{3099}\")\n" +
" - 97\n" +
" - 227\n" +
" - 129\n" +
" - 139\n" +
" - 227\n" +
" - 130\n" +
" - 153\n"
expectEqual(expected, output)
}
Reflection.test("String.UTF16View/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}".utf16, &output)
let expected =
"▿ StringUTF16(\"\u{61}\u{304b}\u{3099}\u{1f425}\")\n" +
" - 97\n" +
" - 12363\n" +
" - 12441\n" +
" - 55357\n" +
" - 56357\n"
expectEqual(expected, output)
}
Reflection.test("String.UnicodeScalarView/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}".unicodeScalars, &output)
let expected =
"▿ StringUnicodeScalarView(\"\u{61}\u{304b}\u{3099}\u{1f425}\")\n" +
" - \"\u{61}\"\n" +
" - \"\\u{304B}\"\n" +
" - \"\\u{3099}\"\n" +
" - \"\\u{0001F425}\"\n"
expectEqual(expected, output)
}
Reflection.test("Character/Mirror") {
do {
// U+0061 LATIN SMALL LETTER A
let input: Character = "\u{61}"
var output = ""
dump(input, &output)
let expected =
"- \"\u{61}\"\n"
expectEqual(expected, output)
}
do {
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: Character = "\u{304b}\u{3099}"
var output = ""
dump(input, &output)
let expected =
"- \"\u{304b}\u{3099}\"\n"
expectEqual(expected, output)
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: Character = "\u{1f425}"
var output = ""
dump(input, &output)
let expected =
"- \"\u{1f425}\"\n"
expectEqual(expected, output)
}
}
Reflection.test("UnicodeScalar") {
do {
// U+0061 LATIN SMALL LETTER A
let input: UnicodeScalar = "\u{61}"
var output = ""
dump(input, &output)
let expected =
"- \"\u{61}\"\n"
expectEqual(expected, output)
}
do {
// U+304B HIRAGANA LETTER KA
let input: UnicodeScalar = "\u{304b}"
var output = ""
dump(input, &output)
let expected =
"- \"\\u{304B}\"\n"
expectEqual(expected, output)
}
do {
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: UnicodeScalar = "\u{3099}"
var output = ""
dump(input, &output)
let expected =
"- \"\\u{3099}\"\n"
expectEqual(expected, output)
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: UnicodeScalar = "\u{1f425}"
var output = ""
dump(input, &output)
let expected =
"- \"\\u{0001F425}\"\n"
expectEqual(expected, output)
}
}
Reflection.test("Bool") {
do {
var output = ""
dump(false, &output)
let expected =
"- false\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(true, &output)
let expected =
"- true\n"
expectEqual(expected, output)
}
}
// FIXME: these tests should cover Float80.
// FIXME: these tests should be automatically generated from the list of
// available floating point types.
Reflection.test("Float") {
do {
var output = ""
dump(Float.NaN, &output)
let expected =
"- nan\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Float.infinity, &output)
let expected =
"- inf\n"
expectEqual(expected, output)
}
do {
var input: Float = 42.125
var output = ""
dump(input, &output)
let expected =
"- 42.125\n"
expectEqual(expected, output)
}
}
Reflection.test("Double") {
do {
var output = ""
dump(Double.NaN, &output)
let expected =
"- nan\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Double.infinity, &output)
let expected =
"- inf\n"
expectEqual(expected, output)
}
do {
var input: Double = 42.125
var output = ""
dump(input, &output)
let expected =
"- 42.125\n"
expectEqual(expected, output)
}
}
// A struct type and class type whose NominalTypeDescriptor.FieldNames
// data is exactly eight bytes long. FieldNames data of exactly
// 4 or 8 or 16 bytes was once miscompiled on arm64.
struct EightByteFieldNamesStruct {
let abcdef = 42
}
class EightByteFieldNamesClass {
let abcdef = 42
}
Reflection.test("FieldNamesBug") {
do {
let expected =
"▿ a.EightByteFieldNamesStruct\n" +
" - abcdef: 42\n"
var output = ""
dump(EightByteFieldNamesStruct(), &output)
expectEqual(expected, output)
}
do {
let expected =
"▿ a.EightByteFieldNamesClass #0\n" +
" - abcdef: 42\n"
var output = ""
dump(EightByteFieldNamesClass(), &output)
expectEqual(expected, output)
}
}
Reflection.test("MirrorMirror") {
var object = 1
var mirror = Mirror(reflecting: object)
var mirrorMirror = Mirror(reflecting: mirror)
expectEqual(0, mirrorMirror.children.count)
}
Reflection.test("COpaquePointer/null") {
// Don't crash on null pointers. rdar://problem/19708338
var sequence = COpaquePointer()
var mirror = Mirror(reflecting: sequence)
var child = mirror.children.first!
expectEqual("(Opaque Value)", "\(child.1)")
}
Reflection.test("StaticString/Mirror") {
do {
var output = ""
dump("" as StaticString, &output)
let expected =
"- \"\"\n"
expectEqual(expected, output)
}
do {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}" as StaticString, &output)
let expected =
"- \"\u{61}\u{304b}\u{3099}\u{1f425}\"\n"
expectEqual(expected, output)
}
}
Reflection.test("DictionaryGenerator/Mirror") {
let d: [MinimalHashableValue : OpaqueValue<Int>] =
[ MinimalHashableValue(0) : OpaqueValue(0) ]
var output = ""
dump(d.generate(), &output)
let expected =
"- Swift.DictionaryGenerator<StdlibUnittest.MinimalHashableValue, StdlibUnittest.OpaqueValue<Swift.Int>>\n"
expectEqual(expected, output)
}
Reflection.test("SetGenerator/Mirror") {
let s: Set<MinimalHashableValue> = [ MinimalHashableValue(0)]
var output = ""
dump(s.generate(), &output)
let expected =
"- Swift.SetGenerator<StdlibUnittest.MinimalHashableValue>\n"
expectEqual(expected, output)
}
var BitTwiddlingTestSuite = TestSuite("BitTwiddling")
func computeCountLeadingZeroes(x: Int64) -> Int64 {
var x = x
var r: Int64 = 64
while x != 0 {
x >>= 1
r -= 1
}
return r
}
BitTwiddlingTestSuite.test("_countLeadingZeros") {
for i in Int64(0)..<1000 {
expectEqual(computeCountLeadingZeroes(i), _countLeadingZeros(i))
}
expectEqual(0, _countLeadingZeros(Int64.min))
}
BitTwiddlingTestSuite.test("_isPowerOf2/Int") {
func asInt(a: Int) -> Int { return a }
expectFalse(_isPowerOf2(asInt(-1025)))
expectFalse(_isPowerOf2(asInt(-1024)))
expectFalse(_isPowerOf2(asInt(-1023)))
expectFalse(_isPowerOf2(asInt(-4)))
expectFalse(_isPowerOf2(asInt(-3)))
expectFalse(_isPowerOf2(asInt(-2)))
expectFalse(_isPowerOf2(asInt(-1)))
expectFalse(_isPowerOf2(asInt(0)))
expectTrue(_isPowerOf2(asInt(1)))
expectTrue(_isPowerOf2(asInt(2)))
expectFalse(_isPowerOf2(asInt(3)))
expectTrue(_isPowerOf2(asInt(1024)))
#if arch(i386) || arch(arm)
// Not applicable to 32-bit architectures.
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le)
expectTrue(_isPowerOf2(asInt(0x8000_0000)))
#else
fatalError("implement")
#endif
expectFalse(_isPowerOf2(Int.min))
expectFalse(_isPowerOf2(Int.max))
}
BitTwiddlingTestSuite.test("_isPowerOf2/UInt") {
func asUInt(a: UInt) -> UInt { return a }
expectFalse(_isPowerOf2(asUInt(0)))
expectTrue(_isPowerOf2(asUInt(1)))
expectTrue(_isPowerOf2(asUInt(2)))
expectFalse(_isPowerOf2(asUInt(3)))
expectTrue(_isPowerOf2(asUInt(1024)))
expectTrue(_isPowerOf2(asUInt(0x8000_0000)))
expectFalse(_isPowerOf2(UInt.max))
}
BitTwiddlingTestSuite.test("_floorLog2") {
expectEqual(_floorLog2(1), 0)
expectEqual(_floorLog2(8), 3)
expectEqual(_floorLog2(15), 3)
expectEqual(_floorLog2(Int64.max), 62) // 63 minus 1 for sign bit.
}
var AvailabilityVersionsTestSuite = TestSuite("AvailabilityVersions")
AvailabilityVersionsTestSuite.test("lexicographic_compare") {
func version(
major: Int,
_ minor: Int,
_ patch: Int
) -> _SwiftNSOperatingSystemVersion {
return _SwiftNSOperatingSystemVersion(
majorVersion: major,
minorVersion: minor,
patchVersion: patch
)
}
checkComparable(.EQ, version(0, 0, 0), version(0, 0, 0))
checkComparable(.LT, version(0, 0, 0), version(0, 0, 1))
checkComparable(.LT, version(0, 0, 0), version(0, 1, 0))
checkComparable(.LT, version(0, 0, 0), version(1, 0, 0))
checkComparable(.LT,version(10, 9, 0), version(10, 10, 0))
checkComparable(.LT,version(10, 9, 11), version(10, 10, 0))
checkComparable(.LT,version(10, 10, 3), version(10, 11, 0))
checkComparable(.LT, version(8, 3, 0), version(9, 0, 0))
checkComparable(.LT, version(0, 11, 0), version(10, 10, 4))
checkComparable(.LT, version(0, 10, 0), version(10, 10, 4))
checkComparable(.LT, version(3, 2, 1), version(4, 3, 2))
checkComparable(.LT, version(1, 2, 3), version(2, 3, 1))
checkComparable(.EQ, version(10, 11, 12), version(10, 11, 12))
checkEquatable(true, version(1, 2, 3), version(1, 2, 3))
checkEquatable(false, version(1, 2, 3), version(1, 2, 42))
checkEquatable(false, version(1, 2, 3), version(1, 42, 3))
checkEquatable(false, version(1, 2, 3), version(42, 2, 3))
}
AvailabilityVersionsTestSuite.test("_stdlib_isOSVersionAtLeast") {
func isAtLeastOS(major: Int, _ minor: Int, _ patch: Int) -> Bool {
return _getBool(_stdlib_isOSVersionAtLeast(major._builtinWordValue,
minor._builtinWordValue,
patch._builtinWordValue))
}
// _stdlib_isOSVersionAtLeast is broken for
// watchOS. rdar://problem/20234735
#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
// This test assumes that no version component on an OS we test upon
// will ever be greater than 1066 and that every major version will always
// be greater than 1.
expectFalse(isAtLeastOS(1066, 0, 0))
expectTrue(isAtLeastOS(0, 1066, 0))
expectTrue(isAtLeastOS(0, 0, 1066))
#endif
}
runAllTests()
| apache-2.0 | 70bb06f4bd134aac6e11557342355591 | 26.340453 | 158 | 0.655051 | 3.763453 | false | false | false | false |
perlmunger/NewFreeApps | NewFreeApps/MasterViewController.swift | 1 | 7721 | //
// MasterViewController.swift
// NewFreeApps
//
// Created by Matt Long on 10/9/14.
// Copyright (c) 2014 Matt Long. All rights reserved.
//
import UIKit
import CoreData
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var managedObjectContext: NSManagedObjectContext? = nil
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "dataDidUpdate:", name: "dataDidUpdateNotification", object: nil)
}
func dataDidUpdate(notification:NSNotification) {
_fetchedResultsController = nil
self.fetchedResultsController
self.tableView.reloadData()
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! EntryMO
(segue.destinationViewController as DetailViewController).detailItem = object
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section] as NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject)
var error: NSError? = nil
do {
try context.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! EntryMO
cell.textLabel?.text = object.title ?? "Untitled"
cell.detailTextLabel?.text = object.link ?? "No link provided"
cell.imageView?.setImageWithURL(NSURL(string: object.imageLink!))
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Entry", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "releaseDate", ascending: false)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = [sortDescriptor]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
var error: NSError? = nil
do {
try _fetchedResultsController!.performFetch()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: NSManagedObject, atIndexPath indexPath: NSIndexPath, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath)!, atIndexPath: indexPath)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
default:
return
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/
}
| mit | 8a79e4cd2076fd6a88659055ad091cc0 | 42.376404 | 360 | 0.685015 | 6.152191 | false | false | false | false |
coffee-cup/solis | SunriseSunset/LocationChangeViewController.swift | 1 | 10023 | //
// LocationChangeViewController.swift
// SunriseSunset
//
// Created by Jake Runzer on 2016-06-17.
// Copyright © 2016 Puddllee. All rights reserved.
//
import Foundation
import UIKit
import GooglePlaces
import SPPermission
class LocationChangeViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, SPPermissionDialogDelegate {
@IBOutlet weak var searchTextField: UISearchBar!
@IBOutlet weak var searchTableView: UITableView!
lazy var placesClient = GMSPlacesClient()
lazy var filter = GMSAutocompleteFilter()
var places: [SunPlace] = []
var placeHistory: [SunPlace] = []
let defaults = Defaults.defaults
var notificationPlaceDirty = false
var newNotificationSunPlace: SunPlace?
var locationCompletion: (() -> ())?
override func viewDidLoad() {
super.viewDidLoad()
searchTextField.delegate = self
searchTextField.showsCancelButton = true
searchTableView.delegate = self
searchTableView.dataSource = self
filter.type = .city
if let locationHistory = SunLocation.getLocationHistory() {
placeHistory = locationHistory
} else {
placeHistory = []
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setNeedsStatusBarAppearanceUpdate()
searchTextField.becomeFirstResponder()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
deinit {
Bus.removeSubscriptions(self)
}
override var prefersStatusBarHidden : Bool {
return false
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.default
}
func isSearching() -> Bool {
if let text = searchTextField.text {
return !text.isEmpty
}
return false
}
func goBack() {
if notificationPlaceDirty {
Bus.sendMessage(.changeNotificationPlace, data: nil)
if let newNotificationSunPlace = newNotificationSunPlace {
Analytics.setNotificationPlace(false, sunPlace: newNotificationSunPlace)
} else {
Analytics.setNotificationPlace(true, sunPlace: nil)
}
}
searchTextField.resignFirstResponder()
dismiss(animated: true, completion: nil)
}
func updateWithSearchResults(_ results: [GMSAutocompletePrediction]) {
places = results.map { result in
return SunPlace(primary: result.attributedPrimaryText.string, secondary: (result.attributedSecondaryText?.string)!, placeID: result.placeID!)
}
searchTableView.reloadData()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if !searchText.isEmpty {
placesClient.autocompleteQuery(searchText, bounds: nil, filter: filter) { results, error in
guard error == nil else {
print("Autocomplete error \(error!)")
return
}
self.updateWithSearchResults(results!)
}
} else {
searchTableView.reloadData()
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
goBack()
}
@IBAction func cancelButtonDidTouch(_ sender: AnyObject) {
// goBack()
}
@IBAction func setButtonDidTouch(_ sender: AnyObject) {
goBack()
}
func ensureLocationPermissions(completion: @escaping () -> ()) {
if SPPermission.isAllowed(.locationWhenInUse) {
SunLocation.startLocationWatching()
completion()
} else {
locationCompletion = completion
SPPermission.Dialog.request(with: [.locationWhenInUse], on: self, delegate: self, dataSource: PermissionController())
}
}
@objc func didAllow(permission: SPPermissionType) {
if let locationCompletion = locationCompletion {
locationCompletion()
}
locationCompletion = nil
}
// Table View
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
goBack()
if (indexPath as NSIndexPath).row == 0 {
ensureLocationPermissions {
SunLocation.selectLocation(true, location: nil, name: nil, sunplace: nil)
Analytics.selectLocation(true, sunPlace: nil)
}
} else {
var sunplace: SunPlace!
if isSearching() {
sunplace = places[(indexPath as NSIndexPath).row - 1]
let placeID = sunplace.placeID
placesClient.lookUpPlaceID(placeID) { googlePlace, error in
if let error = error {
print("PlaceID lookup error \(error)")
return
}
guard let coordinate = googlePlace?.coordinate else {
return
}
guard let _ = googlePlace?.name else {
return
}
sunplace.location = coordinate
print("\(sunplace.primary) - \(coordinate)")
SunLocation.selectLocation(false, location: coordinate, name: sunplace.primary, sunplace: sunplace)
Analytics.selectLocation(false, sunPlace: sunplace)
}
} else {
sunplace = placeHistory[(indexPath as NSIndexPath).row - 1]
SunLocation.selectLocation(false, location: sunplace.location, name: sunplace.primary, sunplace: sunplace)
Analytics.selectLocation(false, sunPlace: sunplace)
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return isSearching() ? places.count + 1 : placeHistory.count + 1
}
func getNotificationPlaceID() -> String? {
if let sunPlaceString = defaults.object(forKey: DefaultKey.notificationPlace.description) as? String {
if sunPlaceString != "" {
if let sunPlace = SunPlace.sunPlaceFromString(sunPlaceString) {
return sunPlace.placeID
}
}
}
return nil
}
func setNotificationSunPlace(_ sunPlace: SunPlace?) {
sunPlace?.isNotification = true
let sunPlaceString = sunPlace == nil ? "" : sunPlace?.toString
defaults.set(sunPlaceString, forKey: DefaultKey.notificationPlace.description)
newNotificationSunPlace = sunPlace
}
@objc func bellButtonDidTouch(_ bellButton: BellButton) {
if bellButton.useCurrentLocation {
setNotificationSunPlace(nil)
} else {
if let sunPlace = bellButton.sunPlace {
setNotificationSunPlace(sunPlace)
}
}
notificationPlaceDirty = true
searchTableView.reloadData()
}
func setBellButton(_ button: BellButton, sunPlace: SunPlace?) {
button.setImage(UIImage(named: "bell_grey"), for: UIControl.State())
button.setImage(UIImage(named: "bell_red"), for: .selected)
button.sunPlace = sunPlace
let placeId: String? = getNotificationPlaceID()
button.isSelected = false
if let sunPlace = sunPlace {
// custom notification
if placeId != nil && placeId! == sunPlace.placeID {
button.isSelected = true
}
} else {
// current location notification
if placeId == nil {
button.isSelected = true
}
}
button.addTarget(self, action: #selector(bellButtonDidTouch), for: .touchUpInside)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell!
if (indexPath as NSIndexPath).row == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "CurrentPlaceCell")
if let locationName = SunLocation.getCurrentLocationName() {
let locationLabel = cell.viewWithTag(3)! as! UILabel
let bellButton = cell.viewWithTag(4)! as! BellButton
setBellButton(bellButton, sunPlace: nil)
locationLabel.text = locationName
}
} else {
cell = tableView.dequeueReusableCell(withIdentifier: "PlaceCell")!
var sunplace: SunPlace!
if isSearching() {
sunplace = places[(indexPath as NSIndexPath).row - 1]
} else {
sunplace = placeHistory[(indexPath as NSIndexPath).row - 1]
}
let cityLabel = cell.viewWithTag(1)! as! UILabel
let stateCountryLabel = cell.viewWithTag(2)! as! UILabel
let bellButton = cell.viewWithTag(4)! as! BellButton
if !isSearching() {
setBellButton(bellButton, sunPlace: sunplace)
bellButton.isHidden = false
} else {
bellButton.isHidden = true
}
cityLabel.text = sunplace.primary
stateCountryLabel.text = sunplace.secondary
}
return cell
}
}
| mit | 904e49a57607589366a275d314d9e0d0 | 33.088435 | 153 | 0.576232 | 5.521763 | false | false | false | false |
brentsimmons/Evergreen | Mac/MainWindow/Sidebar/Cell/SidebarCell.swift | 1 | 4108 | //
// SidebarCell.swift
// NetNewsWire
//
// Created by Brent Simmons on 8/1/15.
// Copyright © 2015 Ranchero Software, LLC. All rights reserved.
//
import Foundation
import RSCore
import Account
import RSTree
class SidebarCell : NSTableCellView {
var iconImage: IconImage? {
didSet {
updateFaviconImage()
}
}
var shouldShowImage = false {
didSet {
if shouldShowImage != oldValue {
needsLayout = true
}
faviconImageView.iconImage = shouldShowImage ? iconImage : nil
}
}
var cellAppearance: SidebarCellAppearance? {
didSet {
if cellAppearance != oldValue {
needsLayout = true
}
}
}
var unreadCount: Int {
get {
return unreadCountView.unreadCount
}
set {
if unreadCountView.unreadCount != newValue {
unreadCountView.unreadCount = newValue
unreadCountView.isHidden = (newValue < 1)
needsLayout = true
}
}
}
var name: String {
get {
return titleView.stringValue
}
set {
if titleView.stringValue != newValue {
titleView.stringValue = newValue
needsDisplay = true
needsLayout = true
}
}
}
private let titleView: NSTextField = {
let textField = NSTextField(labelWithString: "")
textField.usesSingleLineMode = true
textField.maximumNumberOfLines = 1
textField.isEditable = false
textField.lineBreakMode = .byTruncatingTail
textField.allowsDefaultTighteningForTruncation = false
return textField
}()
private let faviconImageView = IconView()
private let unreadCountView = UnreadCountView(frame: NSZeroRect)
override var backgroundStyle: NSView.BackgroundStyle {
didSet {
updateFaviconImage()
}
}
override var isFlipped: Bool {
return true
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
override func layout() {
if let cellAppearance = cellAppearance {
titleView.font = cellAppearance.textFieldFont
}
resizeSubviews(withOldSize: NSZeroSize)
}
override func resizeSubviews(withOldSize oldSize: NSSize) {
guard let cellAppearance = cellAppearance else {
return
}
let layout = SidebarCellLayout(appearance: cellAppearance, cellSize: bounds.size, shouldShowImage: shouldShowImage, textField: titleView, unreadCountView: unreadCountView)
layoutWith(layout)
}
override func accessibilityLabel() -> String? {
if unreadCount > 0 {
let unreadLabel = NSLocalizedString("unread", comment: "Unread label for accessiblity")
return "\(name) \(unreadCount) \(unreadLabel)"
} else {
return name
}
}
}
private extension SidebarCell {
func commonInit() {
addSubviewAtInit(unreadCountView)
addSubviewAtInit(faviconImageView)
addSubviewAtInit(titleView)
}
func addSubviewAtInit(_ view: NSView) {
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
}
func layoutWith(_ layout: SidebarCellLayout) {
faviconImageView.setFrame(ifNotEqualTo: layout.faviconRect)
titleView.setFrame(ifNotEqualTo: layout.titleRect)
unreadCountView.setFrame(ifNotEqualTo: layout.unreadCountRect)
}
func updateFaviconImage() {
var updatedIconImage = iconImage
if let iconImage = iconImage, iconImage.isSymbol {
if backgroundStyle != .normal {
let image = iconImage.image.tinted(with: .white)
updatedIconImage = IconImage(image, isSymbol: iconImage.isSymbol, isBackgroundSupressed: iconImage.isBackgroundSupressed)
} else {
if let preferredColor = iconImage.preferredColor {
let image = iconImage.image.tinted(with: NSColor(cgColor: preferredColor)!)
updatedIconImage = IconImage(image, isSymbol: iconImage.isSymbol, isBackgroundSupressed: iconImage.isBackgroundSupressed)
} else {
let image = iconImage.image.tinted(with: .controlAccentColor)
updatedIconImage = IconImage(image, isSymbol: iconImage.isSymbol, isBackgroundSupressed: iconImage.isBackgroundSupressed)
}
}
}
if let image = updatedIconImage {
faviconImageView.iconImage = shouldShowImage ? image : nil
} else {
faviconImageView.iconImage = nil
}
}
}
| mit | fa96613927bb43120e30230f07d74607 | 23.446429 | 173 | 0.732165 | 3.870877 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.