repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AlexLombry/SwiftMastery-iOS10 | refs/heads/master | PlayGround/Closures.playground/Contents.swift | apache-2.0 | 1 | //: Playground - noun: a place where people can play
import UIKit
var lastNames = ["Stark", "Kent", "Snowden", "Manning"]
func sortB(_ str1: String, _ str2: String) -> Bool {
return str1 > str2
}
var reversed = lastNames.sorted(by: sortB)
// With closures expression
// Parameter type / return type can be inferred, not needed to write it down
var reversed2 = lastNames.sorted(by: { (str1: String, str2: String) -> Bool in
return str1 > str2
})
// inline closure expression when used as a function argument
var reversed3 = lastNames.sorted(by: { str1, str2 in return str1 > str2 })
// implicit return (return can be omitted
var reversed4 = lastNames.sorted(by: { str1, str2 in str1 > str2 })
// shorthand argument names for inline losures $0, $1, $2 ...
var reversed5 = lastNames.sorted(by: { $0 > $1 })
print(reversed2)
// { (parameters) -> ReturnType in
// code
// }
// Swift :
/*
{ (str1: String, str2: String) -> Bool in
return str1 > str2
}
*/
// PHP :
/*
function ($str1, $str2): bool {
return $str1 > $str2
}
*/
// { (str1: String, str2: String) -> Bool in return str1 > str2 }
// Trainling closures
lastNames.sorted{(str1: String, str2: String) -> Bool in
return str1 > str2
}
let digits = [0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine"]
let numbers = [25, 82, 615]
let strings = numbers.map { (number) -> String in
var number = number
var output = ""
repeat {
output = digits[number % 10]! + output
number /= 10
} while number > 0
return output
}
//print(strings)
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}
let inc = makeIncrementer(forIncrement: 5)
inc()
inc()
inc()
let inc8 = makeIncrementer(forIncrement: 8)
inc8()
inc8()
inc8()
| bd46838b19e65ff09ffbfcb53c265a5b | 18.93 | 123 | 0.617662 | false | false | false | false |
apple/swift | refs/heads/main | test/Constraints/subscript.swift | apache-2.0 | 4 | // RUN: %target-typecheck-verify-swift
// Simple subscript of arrays:
func simpleSubscript(_ array: [Float], x: Int) -> Float {
_ = array[x]
return array[x]
}
// Subscript of archetype.
protocol IntToStringSubscript {
subscript (i : Int) -> String { get }
}
class FauxDictionary {
subscript (i : Int) -> String {
get {
return String(i)
}
}
}
func archetypeSubscript<T : IntToStringSubscript, U : FauxDictionary>(_ t: T, u: U)
-> String {
// Subscript an archetype.
if false { return t[17] }
// Subscript an archetype for which the subscript operator is in a base class.
return u[17]
}
// Subscript of existential type.
func existentialSubscript(_ a: IntToStringSubscript) -> String {
return a[17]
}
// Static of above:
// Subscript of archetype.
protocol IntToStringStaticSubscript {
static subscript (i : Int) -> String { get }
}
class FauxStaticDictionary {
static subscript (i : Int) -> String {
get {
return String(i)
}
}
}
func archetypeStaticSubscript<
T : IntToStringStaticSubscript, U : FauxStaticDictionary
>(_ t: T.Type, u: U.Type) -> String {
// Subscript an archetype.
if false { return t[17] }
// Subscript an archetype for which the subscript operator is in a base class.
return u[17]
}
// Subscript of existential type.
func existentialStaticSubscript(
_ a: IntToStringStaticSubscript.Type
) -> String {
return a[17]
}
class MyDictionary<Key, Value> {
subscript (key : Key) -> Value {
get {}
}
}
class MyStringToInt<T> : MyDictionary<String, Int> { }
// Subscript of generic type.
func genericSubscript<T>(_ t: T,
array: Array<Int>,
i2i: MyDictionary<Int, Int>,
t2i: MyDictionary<T, Int>,
s2i: MyStringToInt<()>) -> Int {
if true { return array[5] }
if true { return i2i[5] }
if true { return t2i[t] }
return s2i["hello"]
}
// <rdar://problem/21364448> QoI: Poor error message for ambiguous subscript call
extension String {
func number() -> Int { } // expected-note {{found this candidate}}
func number() -> Double { } // expected-note {{found this candidate}}
}
let _ = "a".number // expected-error {{ambiguous use of 'number()'}}
extension Int {
subscript(key: String) -> Int { get {} } // expected-note {{found this candidate}}
subscript(key: String) -> Double { get {} } // expected-note {{found this candidate}}
}
let _ = 1["1"] // expected-error {{ambiguous use of 'subscript(_:)'}}
let squares = [ 1, 2, 3 ].reduce([:]) { (dict, n) in
// expected-warning@-1 {{empty collection literal requires an explicit type}}
var dict = dict
dict[n] = n * n
return dict
}
// <rdar://problem/23670252> QoI: Misleading error message when assigning a value from [String : AnyObject]
func r23670252(_ dictionary: [String : AnyObject], someObject: AnyObject) {
let color : String?
color = dictionary["color"] // expected-error {{cannot assign value of type 'AnyObject?' to type 'String?'}}
_ = color
}
// https://github.com/apple/swift/issues/43333
// Type mismatch reported as extraneous parameter
do {
struct S {
subscript(b : Int) -> Int
{ return 0 }
subscript(a a : UInt) -> Int { return 0 }
}
S()[a: Int()] // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
}
// rdar://problem/25601561 - Qol: Bad diagnostic for failed assignment from Any to more specific type
struct S_r25601561 {
func value() -> Any? { return "hi" }
}
class C_r25601561 {
var a: [S_r25601561?] = []
func test(i: Int) -> String {
let s: String = a[i]!.value()! // expected-error {{cannot convert value of type 'Any' to specified type 'String'}}
return s
}
}
// rdar://problem/31977679 - Misleading diagnostics when using subscript with incorrect argument
func r31977679_1(_ properties: [String: String]) -> Any? {
return properties[0] // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
func r31977679_2(_ properties: [String: String]) -> Any? {
return properties["foo"] // Ok
}
// rdar://problem/45819956 - inout-to-pointer in a subscript arg could use a better diagnostic
func rdar_45819956() {
struct S {
subscript(takesPtr ptr: UnsafeMutablePointer<Int>) -> Int {
get { return 0 }
}
}
let s = S()
var i = 0
// TODO: It should be possible to suggest `withUnsafe[Mutable]Pointer` as a fix-it
_ = s[takesPtr: &i]
// expected-error@-1 {{cannot pass an inout argument to a subscript; use 'withUnsafeMutablePointer' to explicitly convert argument to a pointer}}
}
// rdar://problem/45825806
// https://github.com/apple/swift/issues/49738
// Array-to-pointer in subscript arg crashes compiler
do {
struct S {
subscript(takesPtr ptr: UnsafePointer<Int>) -> Int {
get { return 0 }
}
}
let s = S()
_ = s[takesPtr: [1, 2, 3]] // Ok
}
func test_generic_subscript_requirements_mismatch_diagnostics() {
struct S {
subscript<T: StringProtocol>(_: T) -> T { // expected-note {{where 'T' = 'Int'}}
fatalError()
}
subscript<T, U: Collection>(v v: [T]) -> U where U.Element == T {
fatalError()
}
subscript<T: Collection>(number num: T) -> Int where T.Element: BinaryInteger {
// expected-note@-1 {{'T.Element' = 'String'}}
return 42
}
}
var s = S()
_ = s[42] // expected-error {{subscript 'subscript(_:)' requires that 'Int' conform to 'StringProtocol'}}
var arr: [Int] = []
let _: [String] = s[v: arr] // expected-error {{cannot convert value of type '[Int]' to expected argument type '[String]'}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}}
s[number: ["hello"]] // expected-error {{subscript 'subscript(number:)' requires that 'String' conform to 'BinaryInteger'}}
}
// rdar://61084565 - infinite recursion in dynamic member lookup
func rdar61084565() {
@dynamicMemberLookup
struct Foo {
subscript(dynamicMember _: KeyPath<Foo, Int>) -> Int {
return 42
}
}
let a = Foo()
a[] // expected-error {{value of type 'Foo' has no subscripts}}
}
// Note: In Swift >= 6 mode this would become an error.
func test_subscript_accepts_type_name_argument() {
struct A {
subscript(a: A.Type) -> Int { get { 42 } }
}
func test(a: A, optA: A?) {
let _ = a[A] // expected-warning {{expected member name or constructor call after type name}}
// expected-note@-1 {{add arguments after the type to construct a value of the type}} {{16-16=()}}
// expected-note@-2 {{use '.self' to reference the type object}} {{16-16=.self}}
let _ = optA?[A] // expected-warning {{expected member name or constructor call after type name}}
// expected-note@-1 {{add arguments after the type to construct a value of the type}} {{20-20=()}}
// expected-note@-2 {{use '.self' to reference the type object}} {{20-20=.self}}
}
}
| 220a29e0505d3586bdb348f64c897d9d | 28.020747 | 147 | 0.639834 | false | false | false | false |
BenEmdon/swift-algorithm-club | refs/heads/master | Rootish Array Stack/RootishArrayStack.playground/Contents.swift | mit | 4 | //: Playground - noun: a place where people can play
import Darwin
public struct RootishArrayStack<T> {
// MARK: - Instance variables
fileprivate var blocks = [Array<T?>]()
fileprivate var internalCount = 0
// MARK: - Init
public init() { }
// MARK: - Calculated variables
var count: Int {
return internalCount
}
var capacity: Int {
return blocks.count * (blocks.count + 1) / 2
}
var isEmpty: Bool {
return blocks.count == 0
}
var first: T? {
guard capacity > 0 else { return nil }
return blocks[0][0]
}
var last: T? {
guard capacity > 0 else { return nil }
let block = self.block(fromIndex: count - 1)
let innerBlockIndex = self.innerBlockIndex(fromIndex: count - 1, fromBlock: block)
return blocks[block][innerBlockIndex]
}
// MARK: - Equations
fileprivate func block(fromIndex index: Int) -> Int {
let block = Int(ceil((-3.0 + sqrt(9.0 + 8.0 * Double(index))) / 2))
return block
}
fileprivate func innerBlockIndex(fromIndex index: Int, fromBlock block: Int) -> Int {
return index - block * (block + 1) / 2
}
// MARK: - Behavior
fileprivate mutating func growIfNeeded() {
if capacity - blocks.count < count + 1 {
let newArray = [T?](repeating: nil, count: blocks.count + 1)
blocks.append(newArray)
}
}
fileprivate mutating func shrinkIfNeeded() {
if capacity + blocks.count >= count {
while blocks.count > 0 && (blocks.count - 2) * (blocks.count - 1) / 2 >= count {
blocks.remove(at: blocks.count - 1)
}
}
}
public subscript(index: Int) -> T {
get {
let block = self.block(fromIndex: index)
let innerBlockIndex = self.innerBlockIndex(fromIndex: index, fromBlock: block)
return blocks[block][innerBlockIndex]!
}
set(newValue) {
let block = self.block(fromIndex: index)
let innerBlockIndex = self.innerBlockIndex(fromIndex: index, fromBlock: block)
blocks[block][innerBlockIndex] = newValue
}
}
public mutating func insert(element: T, atIndex index: Int) {
growIfNeeded()
internalCount += 1
var i = count - 1
while i > index {
self[i] = self[i - 1]
i -= 1
}
self[index] = element
}
public mutating func append(element: T) {
insert(element: element, atIndex: count)
}
fileprivate mutating func makeNil(atIndex index: Int) {
let block = self.block(fromIndex: index)
let innerBlockIndex = self.innerBlockIndex(fromIndex: index, fromBlock: block)
blocks[block][innerBlockIndex] = nil
}
public mutating func remove(atIndex index: Int) -> T {
let element = self[index]
for i in index..<count - 1 {
self[i] = self[i + 1]
}
internalCount -= 1
makeNil(atIndex: count)
shrinkIfNeeded()
return element
}
// MARK: - Struct to string
public var memoryDescription: String {
var description = "{\n"
for block in blocks {
description += "\t["
for index in 0..<block.count {
description += "\(block[index])"
if index + 1 != block.count {
description += ", "
}
}
description += "]\n"
}
return description + "}"
}
}
extension RootishArrayStack: CustomStringConvertible {
public var description: String {
var description = "["
for index in 0..<count {
description += "\(self[index])"
if index + 1 != count {
description += ", "
}
}
return description + "]"
}
}
var list = RootishArrayStack<String>()
list.isEmpty // true
list.first // nil
list.last // nil
list.count // 0
list.capacity // 0
list.memoryDescription
// {
// }
list.append(element: "Hello")
list.isEmpty // false
list.first // "Hello"
list.last // "hello"
list.count // 1
list.capacity // 1
list.memoryDescription
// {
// [Optional("Hello")]
// }
list.append(element: "World")
list.isEmpty // false
list.first // "Hello"
list.last // "World"
list.count // 2
list.capacity // 3
list[0] // "Hello"
list[1] // "World"
//list[2] // crash!
list.memoryDescription
// {
// [Optional("Hello")]
// [Optional("World"), nil]
// }
list.insert(element: "Swift", atIndex: 1)
list.isEmpty // false
list.first // "Hello"
list.last // "World"
list.count // 3
list.capacity // 6
list[0] // "Hello"
list[1] // "Swift"
list[2] // "World"
list.memoryDescription
// {
// [Optional("Hello")]
// [Optional("Swift"), Optional("World")]
// [nil, nil, nil]
// }
list.remove(atIndex: 2) // "World"
list.isEmpty // false
list.first // "Hello"
list.last // "Swift"
list.count // 2
list.capacity // 3
list[0] // "Hello"
list[1] // "Swift"
//list[2] // crash!
list[0] = list[1]
list[1] = "is awesome"
list // ["Swift", "is awesome"]
| 5261aec951bfc26debf2d69075a0c67c | 20.004566 | 86 | 0.629565 | false | false | false | false |
MadAppGang/SmartLog | refs/heads/master | Pods/CoreStore/Sources/DispatchQueue+CoreStore.swift | mit | 2 | //
// DispatchQueue+CoreStore.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
// MARK: - DispatchQueue
internal extension DispatchQueue {
@nonobjc @inline(__always)
internal static func serial(_ label: String, qos: DispatchQoS = .default) -> DispatchQueue {
return DispatchQueue(
label: label,
qos: qos,
attributes: [],
autoreleaseFrequency: .inherit,
target: nil
)
}
@nonobjc @inline(__always)
internal static func concurrent(_ label: String, qos: DispatchQoS = .default) -> DispatchQueue {
return DispatchQueue(
label: label,
qos: qos,
attributes: .concurrent,
autoreleaseFrequency: .inherit,
target: nil
)
}
@nonobjc
internal func cs_isCurrentExecutionContext() -> Bool {
enum Static {
static let specificKey = DispatchSpecificKey<ObjectIdentifier>()
}
let specific = ObjectIdentifier(self)
self.setSpecific(key: Static.specificKey, value: specific)
return DispatchQueue.getSpecific(key: Static.specificKey) == specific
}
@nonobjc @inline(__always)
internal func cs_sync<T>(_ closure: () throws -> T) rethrows -> T {
return try self.sync { try autoreleasepool(invoking: closure) }
}
@nonobjc @inline(__always)
internal func cs_async(_ closure: @escaping () -> Void) {
self.async { autoreleasepool(invoking: closure) }
}
@nonobjc @inline(__always)
internal func cs_barrierSync<T>(_ closure: () throws -> T) rethrows -> T {
return try self.sync(flags: .barrier) { try autoreleasepool(invoking: closure) }
}
@nonobjc @inline(__always)
internal func cs_barrierAsync(_ closure: @escaping () -> Void) {
self.async(flags: .barrier) { autoreleasepool(invoking: closure) }
}
// MARK: Private
}
| 835dc3225dc80ae6756c163c5fab5f72 | 31.824742 | 100 | 0.635364 | false | false | false | false |
IngmarStein/swift | refs/heads/master | test/expr/closure/basic.swift | apache-2.0 | 4 | // RUN: %target-parse-verify-swift
func takeIntToInt(_ f: (Int) -> Int) { }
func takeIntIntToInt(_ f: (Int, Int) -> Int) { }
// Simple closures
func simple() {
takeIntToInt({(x: Int) -> Int in
return x + 1
})
takeIntIntToInt({(x: Int, y: Int) -> Int in
return x + y
})
}
// Closures with variadic argument lists
func variadic() {
var f = {(start: Int, rest: Int...) -> Int in
var result = start
for x in rest {
result += x
}
return result
}
_ = f(1)
_ = f(1, 2)
_ = f(1, 3)
let D = { (Ss ...) in 1 } // expected-error{{'...' cannot be applied to a subpattern which is not explicitly typed}}, expected-error{{unable to infer closure type in the current context}}
}
// Closures with attributes in the parameter list.
func attrs() {
_ = {(z: inout Int) -> Int in z }
}
// Closures with argument and parameter names.
func argAndParamNames() -> Int {
let _: (_ x: Int, _ y: Int) -> Int = { (a x, b y) in x + y } // expected-error 2 {{closure cannot have keyword arguments}}
let f1: (_ x: Int, _ y: Int) -> Int = { (x, y) in x + y }
_ = f1(1, 2)
return f1(1, 2)
}
| 4c1fe11742a510ee45e93c60395c956f | 25.162791 | 189 | 0.574222 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | refs/heads/master | 17--Anybody-Out-There?/GitHub Friends/GitHub Friends/DetailViewController.swift | cc0-1.0 | 1 | //
// ViewController.swift
// GitHub Friends
//
// Created by Pedro Trujillo on 10/29/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController
{
var userImageView:UIImageView!
var imagePath = "gravatar.png"
var userImage:UIImage!
var gitHubFriend: GitHubFriend!
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.whiteColor()
//
self.loadImage(gitHubFriend.largeImageURL)
self.setLabels(gitHubFriend.login,x: view.center.x, y: userImageView.center.y * 0.4)
self.setLabels(gitHubFriend.name,x: view.center.x, y: userImageView.center.y * 1.6)
self.setLabels(gitHubFriend.email,x: view.center.x, y: userImageView.center.y * 1.7)
self.setLabels(gitHubFriend.location,x: view.center.x, y: userImageView.center.y * 1.8)
self.setLabels(gitHubFriend.company,x: view.center.x, y: userImageView.center.y * 1.9)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setLabels( labelString:String = "Penpenuche", x :CGFloat = 0, y :CGFloat = 0)
{
let loginLabel:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 60))
//self.loginLabel.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width * 0.9 , height: self.view.frame.size.width * 0.1)
loginLabel.text = labelString
loginLabel.center.x = x
loginLabel.center.y = y
loginLabel.numberOfLines = 1
loginLabel.textAlignment = .Center
view.addSubview(loginLabel)
}
func loadImage(var ImagePath:String = "")
{
if ImagePath == ""
{ImagePath = self.imagePath}
else
{self.imagePath = ImagePath}
if let url = NSURL(string: ImagePath)
{
if let data = NSData(contentsOfURL: url)
{
self.userImage = UIImage(data: data)
self.userImageView = UIImageView(image: userImage!)
self.userImageView!.contentMode = UIViewContentMode.ScaleAspectFit
self.userImageView.frame = CGRect(x: 0, y: 0 , width: self.view.frame.size.width * 0.9 , height: self.view.frame.size.width * 0.9 )
self.userImageView.center.x = view.center.x
self.userImageView.center.y = UIScreen.mainScreen().bounds.height * 0.5
view.addSubview(userImageView)
}
}
}
/*
// 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.
}
*/
}
| 515908ea3e1cce1cebcaef246e467476 | 31.969072 | 147 | 0.611945 | false | false | false | false |
WhisperSystems/Signal-iOS | refs/heads/master | Signal/src/ViewControllers/LoadingViewController.swift | gpl-3.0 | 1 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
// The initial presentation is intended to be indistinguishable from the Launch Screen.
// After a delay we present some "loading" UI so the user doesn't think the app is frozen.
@objc
public class LoadingViewController: UIViewController {
var logoView: UIImageView!
var topLabel: UILabel!
var bottomLabel: UILabel!
let labelStack = UIStackView()
var topLabelTimer: Timer?
var bottomLabelTimer: Timer?
override public func loadView() {
self.view = UIView()
view.backgroundColor = UIColor.ows_materialBlue
self.logoView = UIImageView(image: #imageLiteral(resourceName: "logoSignal"))
view.addSubview(logoView)
logoView.autoCenterInSuperview()
logoView.autoPinToSquareAspectRatio()
logoView.autoMatch(.width, to: .width, of: view, withMultiplier: 1/3)
self.topLabel = buildLabel()
topLabel.alpha = 0
topLabel.font = UIFont.ows_dynamicTypeTitle2
topLabel.text = NSLocalizedString("DATABASE_VIEW_OVERLAY_TITLE", comment: "Title shown while the app is updating its database.")
labelStack.addArrangedSubview(topLabel)
self.bottomLabel = buildLabel()
bottomLabel.alpha = 0
bottomLabel.font = UIFont.ows_dynamicTypeBody
bottomLabel.text = NSLocalizedString("DATABASE_VIEW_OVERLAY_SUBTITLE", comment: "Subtitle shown while the app is updating its database.")
labelStack.addArrangedSubview(bottomLabel)
labelStack.axis = .vertical
labelStack.alignment = .center
labelStack.spacing = 8
view.addSubview(labelStack)
labelStack.autoPinEdge(.top, to: .bottom, of: logoView, withOffset: 20)
labelStack.autoPinLeadingToSuperviewMargin()
labelStack.autoPinTrailingToSuperviewMargin()
labelStack.setCompressionResistanceHigh()
labelStack.setContentHuggingHigh()
NotificationCenter.default.addObserver(self,
selector: #selector(didBecomeActive),
name: NSNotification.Name.OWSApplicationDidBecomeActive,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(didEnterBackground),
name: NSNotification.Name.OWSApplicationDidEnterBackground,
object: nil)
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// We only show the "loading" UI if it's a slow launch. Otherwise this ViewController
// should be indistinguishable from the launch screen.
let kTopLabelThreshold: TimeInterval = 5
topLabelTimer = Timer.weakScheduledTimer(withTimeInterval: kTopLabelThreshold, target: self, selector: #selector(showTopLabel), userInfo: nil, repeats: false)
let kBottomLabelThreshold: TimeInterval = 15
topLabelTimer = Timer.weakScheduledTimer(withTimeInterval: kBottomLabelThreshold, target: self, selector: #selector(showBottomLabelAnimated), userInfo: nil, repeats: false)
}
// UIStackView removes hidden subviews from the layout.
// UIStackView considers views with a sufficiently low
// alpha to be "hidden". This can cause layout to glitch
// briefly when returning from background. Therefore we
// use a "min" alpha value when fading in labels that is
// high enough to avoid this UIStackView behavior.
private let kMinAlpha: CGFloat = 0.1
@objc
private func showBottomLabelAnimated() {
Logger.verbose("")
bottomLabel.layer.removeAllAnimations()
bottomLabel.alpha = kMinAlpha
UIView.animate(withDuration: 0.1) {
self.bottomLabel.alpha = 1
}
}
@objc
private func showTopLabel() {
topLabel.layer.removeAllAnimations()
topLabel.alpha = 0.2
UIView.animate(withDuration: 0.9, delay: 0, options: [.autoreverse, .repeat, .curveEaseInOut], animations: {
self.topLabel.alpha = 1.0
}, completion: nil)
}
private func showBottomLabel() {
bottomLabel.layer.removeAllAnimations()
self.bottomLabel.alpha = 1
}
// MARK: -
@objc func didBecomeActive() {
AssertIsOnMainThread()
Logger.info("")
guard viewHasEnteredBackground else {
// If the app is returning from background, skip any
// animations and show the top and bottom labels.
return
}
topLabelTimer?.invalidate()
topLabelTimer = nil
bottomLabelTimer?.invalidate()
bottomLabelTimer = nil
showTopLabel()
showBottomLabel()
labelStack.layoutSubviews()
view.layoutSubviews()
}
private var viewHasEnteredBackground = false
@objc func didEnterBackground() {
AssertIsOnMainThread()
Logger.info("")
viewHasEnteredBackground = true
}
// MARK: Orientation
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
// MARK:
private func buildLabel() -> UILabel {
let label = UILabel()
label.textColor = .white
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
return label
}
}
| 92d8646443772f114896c134e2b91c85 | 33.583851 | 180 | 0.647989 | false | false | false | false |
doronkatz/firefox-ios | refs/heads/master | Client/Frontend/Widgets/TwoLineCell.swift | mpl-2.0 | 5 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
struct TwoLineCellUX {
static let ImageSize: CGFloat = 29
static let ImageCornerRadius: CGFloat = 8
static let BorderViewMargin: CGFloat = 16
static let BadgeSize: CGFloat = 16
static let BadgeMargin: CGFloat = 16
static let BorderFrameSize: CGFloat = 32
static let TextColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.black : UIColor(rgb: 0x333333)
static let DetailTextColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.darkGray : UIColor.gray
static let DetailTextTopMargin: CGFloat = 0
}
class TwoLineTableViewCell: UITableViewCell {
fileprivate let twoLineHelper = TwoLineCellHelper()
let _textLabel = UILabel()
let _detailTextLabel = UILabel()
// Override the default labels with our own to disable default UITableViewCell label behaviours like dynamic type
override var textLabel: UILabel? {
return _textLabel
}
override var detailTextLabel: UILabel? {
return _detailTextLabel
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: reuseIdentifier)
contentView.addSubview(_textLabel)
contentView.addSubview(_detailTextLabel)
twoLineHelper.setUpViews(self, textLabel: textLabel!, detailTextLabel: detailTextLabel!, imageView: imageView!)
indentationWidth = 0
layoutMargins = UIEdgeInsets.zero
separatorInset = UIEdgeInsets(top: 0, left: TwoLineCellUX.ImageSize + 2 * TwoLineCellUX.BorderViewMargin, bottom: 0, right: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
twoLineHelper.layoutSubviews()
}
override func prepareForReuse() {
super.prepareForReuse()
self.textLabel!.alpha = 1
self.imageView!.alpha = 1
self.selectionStyle = .default
separatorInset = UIEdgeInsets(top: 0, left: TwoLineCellUX.ImageSize + 2 * TwoLineCellUX.BorderViewMargin, bottom: 0, right: 0)
twoLineHelper.setupDynamicFonts()
}
// Save background color on UITableViewCell "select" because it disappears in the default behavior
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
let color = imageView?.backgroundColor
super.setHighlighted(highlighted, animated: animated)
imageView?.backgroundColor = color
}
// Save background color on UITableViewCell "select" because it disappears in the default behavior
override func setSelected(_ selected: Bool, animated: Bool) {
let color = imageView?.backgroundColor
super.setSelected(selected, animated: animated)
imageView?.backgroundColor = color
}
func setRightBadge(_ badge: UIImage?) {
if let badge = badge {
self.accessoryView = UIImageView(image: badge)
} else {
self.accessoryView = nil
}
twoLineHelper.hasRightBadge = badge != nil
}
func setLines(_ text: String?, detailText: String?) {
twoLineHelper.setLines(text, detailText: detailText)
}
func mergeAccessibilityLabels(_ views: [AnyObject?]? = nil) {
twoLineHelper.mergeAccessibilityLabels(views)
}
}
class SiteTableViewCell: TwoLineTableViewCell {
let borderView = UIView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: reuseIdentifier)
twoLineHelper.setUpViews(self, textLabel: textLabel!, detailTextLabel: detailTextLabel!, imageView: imageView!)
}
override func layoutSubviews() {
super.layoutSubviews()
twoLineHelper.layoutSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TwoLineHeaderFooterView: UITableViewHeaderFooterView {
fileprivate let twoLineHelper = TwoLineCellHelper()
// UITableViewHeaderFooterView includes textLabel and detailTextLabel, so we can't override
// them. Unfortunately, they're also used in ways that interfere with us just using them: I get
// hard crashes in layout if I just use them; it seems there's a battle over adding to the
// contentView. So we add our own members, and cover up the other ones.
let _textLabel = UILabel()
let _detailTextLabel = UILabel()
let imageView = UIImageView()
// Yes, this is strange.
override var textLabel: UILabel? {
return _textLabel
}
// Yes, this is strange.
override var detailTextLabel: UILabel? {
return _detailTextLabel
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
twoLineHelper.setUpViews(self, textLabel: _textLabel, detailTextLabel: _detailTextLabel, imageView: imageView)
contentView.addSubview(_textLabel)
contentView.addSubview(_detailTextLabel)
contentView.addSubview(imageView)
layoutMargins = UIEdgeInsets.zero
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
twoLineHelper.layoutSubviews()
}
override func prepareForReuse() {
super.prepareForReuse()
twoLineHelper.setupDynamicFonts()
}
func mergeAccessibilityLabels(_ views: [AnyObject?]? = nil) {
twoLineHelper.mergeAccessibilityLabels(views)
}
}
private class TwoLineCellHelper {
weak var container: UIView?
var textLabel: UILabel!
var detailTextLabel: UILabel!
var imageView: UIImageView!
var hasRightBadge: Bool = false
// TODO: Not ideal. We should figure out a better way to get this initialized.
func setUpViews(_ container: UIView, textLabel: UILabel, detailTextLabel: UILabel, imageView: UIImageView) {
self.container = container
self.textLabel = textLabel
self.detailTextLabel = detailTextLabel
self.imageView = imageView
if let headerView = self.container as? UITableViewHeaderFooterView {
headerView.contentView.backgroundColor = UIColor.clear
} else {
self.container?.backgroundColor = UIColor.clear
}
textLabel.textColor = TwoLineCellUX.TextColor
detailTextLabel.textColor = TwoLineCellUX.DetailTextColor
setupDynamicFonts()
imageView.contentMode = .scaleAspectFill
imageView.layer.cornerRadius = 6 //hmm
imageView.layer.masksToBounds = true
}
func setupDynamicFonts() {
textLabel.font = DynamicFontHelper.defaultHelper.DeviceFontHistoryPanel
detailTextLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallHistoryPanel
}
func layoutSubviews() {
guard let container = self.container else {
return
}
let height = container.frame.height
let textLeft = TwoLineCellUX.ImageSize + 2 * TwoLineCellUX.BorderViewMargin
let textLabelHeight = textLabel.intrinsicContentSize.height
let detailTextLabelHeight = detailTextLabel.intrinsicContentSize.height
var contentHeight = textLabelHeight
if detailTextLabelHeight > 0 {
contentHeight += detailTextLabelHeight + TwoLineCellUX.DetailTextTopMargin
}
let textRightInset: CGFloat = hasRightBadge ? (TwoLineCellUX.BadgeSize + TwoLineCellUX.BadgeMargin) : 0
imageView.frame = CGRect(x: TwoLineCellUX.BorderViewMargin, y: (height - TwoLineCellUX.ImageSize) / 2, width: TwoLineCellUX.ImageSize, height: TwoLineCellUX.ImageSize)
textLabel.frame = CGRect(x: textLeft, y: (height - contentHeight) / 2,
width: container.frame.width - textLeft - TwoLineCellUX.BorderViewMargin - textRightInset, height: textLabelHeight)
detailTextLabel.frame = CGRect(x: textLeft, y: textLabel.frame.maxY + TwoLineCellUX.DetailTextTopMargin,
width: container.frame.width - textLeft - TwoLineCellUX.BorderViewMargin - textRightInset, height: detailTextLabelHeight)
}
func setLines(_ text: String?, detailText: String?) {
if text?.isEmpty ?? true {
textLabel.text = detailText
detailTextLabel.text = nil
} else {
textLabel.text = text
detailTextLabel.text = detailText
}
}
func mergeAccessibilityLabels(_ labels: [AnyObject?]?) {
let labels = labels ?? [textLabel, imageView, detailTextLabel]
let label = labels.map({ (label: AnyObject?) -> NSAttributedString? in
var label = label
if let view = label as? UIView {
label = view.value(forKey: "accessibilityLabel") as (AnyObject?)
}
if let attrString = label as? NSAttributedString {
return attrString
} else if let string = label as? String {
return NSAttributedString(string: string)
} else {
return nil
}
}).filter({
$0 != nil
}).reduce(NSMutableAttributedString(string: ""), {
if $0.length > 0 {
$0.append(NSAttributedString(string: ", "))
}
$0.append($1!)
return $0
})
container?.isAccessibilityElement = true
container?.setValue(NSAttributedString(attributedString: label), forKey: "accessibilityLabel")
}
}
| e2428356e2219b4a5e3b38ccd25b6c8a | 36.346008 | 175 | 0.677561 | false | false | false | false |
nathantannar4/NTComponents | refs/heads/master | NTComponents/Extensions/CALayer.swift | mit | 1 | //
// CALayer.swift
// NTComponents
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 6/26/17.
//
public extension CALayer {
func hideShadow() {
shadowOpacity = 0
}
func setDefaultShadow() {
shadowColor = Color.Default.Shadow.cgColor
shadowOpacity = Color.Default.Shadow.Opacity
shadowOffset = Color.Default.Shadow.Offset
shadowRadius = Color.Default.Shadow.Radius
}
}
| dc8bbf1a008fc612be231fd7dbe35e21 | 37.8 | 82 | 0.721005 | false | false | false | false |
kay-kim/stitch-examples | refs/heads/master | todo/ios/Pods/StitchCore/StitchCore/StitchCore/Source/Core/KeychainPasswordItem.swift | apache-2.0 | 1 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A struct for accessing generic password keychain items.
*/
import Foundation
struct KeychainPasswordItem {
// MARK: Types
enum KeychainError: Error {
case noPassword
case unexpectedPasswordData
case unexpectedItemData
case unhandledError(status: OSStatus)
}
// MARK: Properties
let service: String
private(set) var account: String
let accessGroup: String?
// MARK: Intialization
init(service: String, account: String, accessGroup: String? = nil) {
self.service = service
self.account = account
self.accessGroup = accessGroup
}
// MARK: Keychain access
func readPassword() throws -> String {
/*
Build a query to find the item that matches the service, account and
access group.
*/
var query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
query[kSecMatchLimit as String] = kSecMatchLimitOne
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecReturnData as String] = kCFBooleanTrue
// Try to fetch the existing keychain item that matches the query.
var queryResult: AnyObject?
let status = withUnsafeMutablePointer(to: &queryResult) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
// Check the return status and throw an error if appropriate.
guard status != errSecItemNotFound else { throw KeychainError.noPassword }
guard status == noErr else { throw KeychainError.unhandledError(status: status) }
// Parse the password string from the query result.
guard let existingItem = queryResult as? [String: AnyObject],
let passwordData = existingItem[kSecValueData as String] as? Data,
let password = String(data: passwordData, encoding: String.Encoding.utf8)
else {
throw KeychainError.unexpectedPasswordData
}
return password
}
func savePassword(_ password: String) throws {
// Encode the password into an Data object.
let encodedPassword = password.data(using: String.Encoding.utf8)!
do {
// Check for an existing item in the keychain.
try _ = readPassword()
// Update the existing item with the new password.
var attributesToUpdate = [String: AnyObject]()
attributesToUpdate[kSecValueData as String] = encodedPassword as AnyObject?
let query = KeychainPasswordItem.keychainQuery(withService: service,
account: account,
accessGroup: accessGroup)
let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr else { throw KeychainError.unhandledError(status: status) }
} catch KeychainError.noPassword {
/*
No password was found in the keychain. Create a dictionary to save
as a new keychain item.
*/
var newItem = KeychainPasswordItem.keychainQuery(withService: service,
account: account,
accessGroup: accessGroup)
newItem[kSecValueData as String] = encodedPassword as AnyObject?
// Add a the new item to the keychain.
let status = SecItemAdd(newItem as CFDictionary, nil)
// Throw an error if an unexpected status was returned.
guard status == noErr else { throw KeychainError.unhandledError(status: status) }
}
}
mutating func renameAccount(_ newAccountName: String) throws {
// Try to update an existing item with the new account name.
var attributesToUpdate = [String: AnyObject]()
attributesToUpdate[kSecAttrAccount as String] = newAccountName as AnyObject?
let query = KeychainPasswordItem.keychainQuery(withService: service,
account: self.account,
accessGroup: accessGroup)
let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr || status == errSecItemNotFound else {
throw KeychainError.unhandledError(status: status)
}
self.account = newAccountName
}
func deleteItem() throws {
// Delete the existing item from the keychain.
let query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
let status = SecItemDelete(query as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr || status == errSecItemNotFound else {
throw KeychainError.unhandledError(status: status)
}
}
static func passwordItems(forService service: String, accessGroup: String? = nil) throws -> [KeychainPasswordItem] {
// Build a query for all items that match the service and access group.
var query = KeychainPasswordItem.keychainQuery(withService: service, accessGroup: accessGroup)
query[kSecMatchLimit as String] = kSecMatchLimitAll
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecReturnData as String] = kCFBooleanFalse
// Fetch matching items from the keychain.
var queryResult: AnyObject?
let status = withUnsafeMutablePointer(to: &queryResult) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
// If no items were found, return an empty array.
guard status != errSecItemNotFound else { return [] }
// Throw an error if an unexpected status was returned.
guard status == noErr else { throw KeychainError.unhandledError(status: status) }
// Cast the query result to an array of dictionaries.
guard let resultData = queryResult as? [[String: AnyObject]] else { throw KeychainError.unexpectedItemData }
// Create a `KeychainPasswordItem` for each dictionary in the query result.
var passwordItems = [KeychainPasswordItem]()
for result in resultData {
guard let account = result[kSecAttrAccount as String] as? String else {
throw KeychainError.unexpectedItemData
}
let passwordItem = KeychainPasswordItem(service: service, account: account, accessGroup: accessGroup)
passwordItems.append(passwordItem)
}
return passwordItems
}
// MARK: Convenience
private static func keychainQuery(withService service: String,
account: String? = nil,
accessGroup: String? = nil) -> [String: AnyObject] {
var query = [String: AnyObject]()
query[kSecClass as String] = kSecClassGenericPassword
query[kSecAttrService as String] = service as AnyObject?
if let account = account {
query[kSecAttrAccount as String] = account as AnyObject?
}
if let accessGroup = accessGroup {
query[kSecAttrAccessGroup as String] = accessGroup as AnyObject?
}
return query
}
}
| d6b45715212421430df50792f59cd692 | 39.602094 | 120 | 0.631593 | false | false | false | false |
habr/ChatTaskAPI | refs/heads/master | IQKeyboardManager/Demo/Swift_Demo/ViewController/SettingsViewController.swift | mit | 1 | //
// SettingsViewController.swift
// Demo
//
// Created by Iftekhar on 26/08/15.
// Copyright (c) 2015 Iftekhar. All rights reserved.
//
class SettingsViewController: UITableViewController, OptionsViewControllerDelegate {
let sectionTitles = [
"UIKeyboard handling",
"IQToolbar handling",
"UITextView handling",
"UIKeyboard appearance overriding",
"Resign first responder handling",
"UISound handling",
"UIAnimation handling"]
let keyboardManagerProperties = [
["Enable", "Keyboard Distance From TextField", "Prevent Showing Bottom Blank Space"],
["Enable AutoToolbar","Toolbar Manage Behaviour","Should Toolbar Uses TextField TintColor","Should Show TextField Placeholder","Placeholder Font"],
["Can Adjust TextView","Should Fix TextView Clip"],
["Override Keyboard Appearance","UIKeyboard Appearance"],
["Should Resign On Touch Outside"],
["Should Play Input Clicks"],
["Should Adopt Default Keyboard Animation"]]
let keyboardManagerPropertyDetails = [
["Enable/Disable IQKeyboardManager","Set keyboard distance from textField","Prevent to show blank space between UIKeyboard and View"],
["Automatic add the IQToolbar on UIKeyboard","AutoToolbar previous/next button managing behaviour","Uses textField's tintColor property for IQToolbar","Add the textField's placeholder text on IQToolbar","UIFont for IQToolbar placeholder text"],
["Adjust textView's frame when it is too big in height","Adjust textView's contentInset to fix a bug"],
["Override the keyboardAppearance for all UITextField/UITextView","All the UITextField keyboardAppearance is set using this property"],
["Resigns Keyboard on touching outside of UITextField/View"],
["Plays inputClick sound on next/previous/done click"],
["Uses keyboard default animation curve style to move view"]]
var selectedIndexPathForOptions : NSIndexPath?
@IBAction func doneAction (sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
/** UIKeyboard Handling */
func enableAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().enable = sender.on
self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade)
}
func keyboardDistanceFromTextFieldAction (sender: UIStepper) {
IQKeyboardManager.sharedManager().keyboardDistanceFromTextField = CGFloat(sender.value)
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.None)
}
func preventShowingBottomBlankSpaceAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().preventShowingBottomBlankSpace = sender.on
self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade)
}
/** IQToolbar handling */
func enableAutoToolbarAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().enableAutoToolbar = sender.on
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Fade)
}
func shouldToolbarUsesTextFieldTintColorAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor = sender.on
}
func shouldShowTextFieldPlaceholder (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder = sender.on
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Fade)
}
/** UITextView handling */
func canAdjustTextViewAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().canAdjustTextView = sender.on
self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade)
}
func shouldFixTextViewClipAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldFixTextViewClip = sender.on
self.tableView.reloadSections(NSIndexSet(index: 3), withRowAnimation: UITableViewRowAnimation.Fade)
}
/** "Keyboard appearance overriding */
func overrideKeyboardAppearanceAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().overrideKeyboardAppearance = sender.on
self.tableView.reloadSections(NSIndexSet(index: 3), withRowAnimation: UITableViewRowAnimation.Fade)
}
/** Resign first responder handling */
func shouldResignOnTouchOutsideAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = sender.on
}
/** Sound handling */
func shouldPlayInputClicksAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldPlayInputClicks = sender.on
}
/** Animation handling */
func shouldAdoptDefaultKeyboardAnimation (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldAdoptDefaultKeyboardAnimation = sender.on
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sectionTitles.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (section)
{
case 0:
if IQKeyboardManager.sharedManager().enable == true {
let properties = keyboardManagerProperties[section]
return properties.count
} else {
return 1
}
case 1:
if IQKeyboardManager.sharedManager().enableAutoToolbar == false {
return 1
} else if IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder == false {
return 4
} else {
let properties = keyboardManagerProperties[section]
return properties.count
}
case 3:
if IQKeyboardManager.sharedManager().overrideKeyboardAppearance == true {
let properties = keyboardManagerProperties[section]
return properties.count
} else {
return 1
}
case 2,4,5,6:
let properties = keyboardManagerProperties[section]
return properties.count
default:
return 0
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch (indexPath.section) {
case 0:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().enable
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: Selector("enableAction:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("StepperTableViewCell") as! StepperTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.stepper.value = Double(IQKeyboardManager.sharedManager().keyboardDistanceFromTextField)
cell.labelStepperValue.text = NSString(format: "%.0f", IQKeyboardManager.sharedManager().keyboardDistanceFromTextField) as String
cell.stepper.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.stepper.addTarget(self, action: Selector("keyboardDistanceFromTextFieldAction:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 2:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().preventShowingBottomBlankSpace
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: Selector("preventShowingBottomBlankSpaceAction:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
case 1:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().enableAutoToolbar
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: Selector("enableAutoToolbarAction:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
return cell
case 2:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: Selector("shouldToolbarUsesTextFieldTintColorAction:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 3:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: Selector("shouldShowTextFieldPlaceholder:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 4:
let cell = tableView.dequeueReusableCellWithIdentifier("NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
return cell
default:
break
}
case 2:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().canAdjustTextView
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: Selector("canAdjustTextViewAction:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldFixTextViewClip
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: Selector("shouldFixTextViewClipwAction:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
case 3:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().overrideKeyboardAppearance
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: Selector("overrideKeyboardAppearanceAction:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
return cell
default:
break
}
case 4:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldResignOnTouchOutside
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: Selector("shouldResignOnTouchOutsideAction:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
case 5:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldPlayInputClicks
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: Selector("shouldPlayInputClicksAction:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
case 6:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldAdoptDefaultKeyboardAnimation
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: Selector("shouldAdoptDefaultKeyboardAnimation:"), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
default:
break
}
return UITableViewCell()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
if identifier == "OptionsViewController" {
let controller = segue.destinationViewController as! OptionsViewController
controller.delegate = self
let cell = sender as! UITableViewCell
selectedIndexPathForOptions = self.tableView.indexPathForCell(cell)
if let selectedIndexPath = selectedIndexPathForOptions {
if selectedIndexPath.section == 1 && selectedIndexPath.row == 1 {
controller.title = "Toolbar Manage Behaviour"
controller.options = ["IQAutoToolbar By Subviews","IQAutoToolbar By Tag","IQAutoToolbar By Position"]
controller.selectedIndex = IQKeyboardManager.sharedManager().toolbarManageBehaviour.hashValue
} else if selectedIndexPath.section == 1 && selectedIndexPath.row == 4 {
controller.title = "Fonts"
controller.options = ["Bold System Font","Italic system font","Regular"]
controller.selectedIndex = IQKeyboardManager.sharedManager().toolbarManageBehaviour.hashValue
let fonts = [UIFont.boldSystemFontOfSize(12),UIFont.italicSystemFontOfSize(12),UIFont.systemFontOfSize(12)]
if let placeholderFont = IQKeyboardManager.sharedManager().placeholderFont {
if let index = fonts.indexOf(placeholderFont) {
controller.selectedIndex = index
}
}
} else if selectedIndexPath.section == 3 && selectedIndexPath.row == 1 {
controller.title = "Keyboard Appearance"
controller.options = ["UIKeyboardAppearance Default","UIKeyboardAppearance Dark","UIKeyboardAppearance Light"]
controller.selectedIndex = IQKeyboardManager.sharedManager().keyboardAppearance.hashValue
}
}
}
}
}
func optionsViewController(controller: OptionsViewController, index: NSInteger) {
if let selectedIndexPath = selectedIndexPathForOptions {
if selectedIndexPath.section == 1 && selectedIndexPath.row == 1 {
IQKeyboardManager.sharedManager().toolbarManageBehaviour = IQAutoToolbarManageBehaviour(rawValue: index)!
} else if selectedIndexPath.section == 1 && selectedIndexPath.row == 4 {
let fonts = [UIFont.boldSystemFontOfSize(12),UIFont.italicSystemFontOfSize(12),UIFont.systemFontOfSize(12)]
IQKeyboardManager.sharedManager().placeholderFont = fonts[index]
} else if selectedIndexPath.section == 3 && selectedIndexPath.row == 1 {
IQKeyboardManager.sharedManager().keyboardAppearance = UIKeyboardAppearance(rawValue: index)!
}
}
}
}
| 642cf29f860e33f021347958caa4b89e | 44.084906 | 252 | 0.603013 | false | false | false | false |
mcjcloud/Show-And-Sell | refs/heads/master | Show And Sell/DonateItemViewController.swift | apache-2.0 | 1 | //
// DontateItemViewController.swift
// Show And Sell
//
// Created by Brayden Cloud on 9/5/16.
// Copyright © 2016 Brayden Cloud. All rights reserved.
//
// UIViewController implementation to prompt the user for Item details for donating an item (posting it to server)
//
import UIKit
class DonateItemViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// UI Elements
var activityView: UIActivityIndicatorView!
@IBOutlet var itemNameField: UITextField!
@IBOutlet var itemPriceField: UITextField!
@IBOutlet var itemConditionField: UITextField!
@IBOutlet var itemDescription: UITextView!
@IBOutlet var imageButton: UIButton!
@IBOutlet var doneButton: UIBarButtonItem!
let picker = UIImagePickerController()
let completeOverlay = OverlayView(type: .complete, text: "Item Donated!")
// data
var item: Item?
var groupId: String?
let priceMinimum = 0.31
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// init manually made Views
activityView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
// give textfield edit change targets
setupTextField(itemNameField)
itemNameField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
setupTextField(itemPriceField)
itemPriceField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
itemPriceField.delegate = self
setupTextField(itemConditionField)
itemConditionField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
// make textfields dismiss when uiview tapped
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)))
// assign necessary delegates
picker.delegate = self
itemDescription.delegate = self
// fill in default values (if existant)
itemNameField.text = item?.name
itemPriceField.text = item?.price
itemConditionField.text = item?.condition
itemDescription.text = (item?.itemDescription.characters.count ?? 0) > 0 ? item?.itemDescription : "A Short Description"
// get image
if let pic = item?.thumbnail {
let imageData = Data(base64Encoded: pic)
let image = UIImage(data: imageData!)
imageButton.contentMode = .scaleAspectFit
imageButton.setBackgroundImage(image, for: .normal)
}
// start the button as false.
doneButton.isEnabled = false
}
override func viewWillDisappear(_ animated: Bool) {
dismissKeyboard()
}
// MARK: Text field/view
func textFieldDidEndEditing(_ textField: UITextField) {
let price = Double(textField.text!)!
if price < 0.31 {
textField.text = "0.31"
// display alert
let priceAlert = UIAlertController(title: "Price is too low", message: "The price of your item cannot be less than $0.31", preferredStyle: .alert)
priceAlert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
self.present(priceAlert, animated: true, completion: nil)
}
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text == "" {
textView.text = "A Short Description"
}
textChanged(itemNameField)
}
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.text == "A Short Description" {
textView.text = ""
}
}
// MARK: Image picker
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
dismiss(animated: true, completion: nil)
// set the image to the button background.
let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage
imageButton.contentMode = .scaleAspectFit
imageButton.setBackgroundImage(chosenImage, for: .normal)
// check if all fields are filled.
textChanged(itemNameField)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// dismiss
dismiss(animated: true, completion: nil)
}
// MARK: IBAction
@IBAction func chooseImage(_ sender: UIButton) {
// dismiss keyboard
dismissKeyboard()
// prompt for choose or take
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let chooseAction = UIAlertAction(title: "Choose Photo", style: .default) { action in
// image chooser.
self.picker.allowsEditing = true
self.picker.sourceType = .photoLibrary
self.picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
self.present(self.picker, animated: true, completion: nil)
}
let takeAction = UIAlertAction(title: "Take Photo", style: .default) { action in
// image taker.
self.picker.allowsEditing = true
self.picker.sourceType = .camera
self.picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .camera)!
self.present(self.picker, animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
// create action menu
alertController.addAction(chooseAction)
if UIImagePickerController.isSourceTypeAvailable(.camera) {
alertController.addAction(takeAction)
}
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
@IBAction func cancelDonate(_ sender: UIBarButtonItem) {
dismiss(animated: true)
}
@IBAction func donate(_ sender: UIBarButtonItem) {
// dismiss keyobard
dismissKeyboard()
// check that the price is okay
let dPrice = Double(itemPriceField.text!)!
if dPrice < priceMinimum { // 31 cent price minimum due to braintree
itemPriceField.text = "0.31"
// display alert
let priceAlert = UIAlertController(title: "Price is too low", message: "The price of your item cannot be less than $0.31", preferredStyle: .alert)
priceAlert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
self.present(priceAlert, animated: true, completion: nil)
return
}
// start animation
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: self.activityView)
self.activityView.startAnimating()
// force unwrap data because they all have to be filled to click done.
let name = itemNameField.text!
let price = itemPriceField.text!
let condition = itemConditionField.text!
let desc = itemDescription.text!
let imageData = UIImagePNGRepresentation(resizeImage(image: imageButton.currentBackgroundImage!, targetSize: CGSize(width: imageButton.currentBackgroundImage!.size.width * 0.1, height: imageButton.currentBackgroundImage!.size.height * 0.1)))
let thumbnail = imageData!.base64EncodedString()
print("groupId: \(groupId)")
// make a post request to add the item to the appropriate group TODO:
let item = Item(itemId: "", groupId: self.groupId ?? "", ownerId: AppData.user!.userId, name: name, price: price, condition: condition, itemDescription: desc, thumbnail: thumbnail, approved: false)
HttpRequestManager.post(item: item) { item, response, error in
// stop animating in main thread
DispatchQueue.main.async {
self.activityView.stopAnimating()
self.navigationItem.rightBarButtonItem = self.doneButton
}
// see if the item was posted
let httpResponse = response as? HTTPURLResponse
switch httpResponse?.statusCode ?? 0 {
case 200:
print("ITEM POSTED")
// dismiss in UI thread
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
let window = UIApplication.shared.keyWindow
self.completeOverlay.showAnimatedOverlay(view: window!)
}
default:
DispatchQueue.main.async {
// display error message from the server
let errorAlert = UIAlertController(title: "Error", message: "Error donating Item.", preferredStyle: .alert)
let dismissAction = UIAlertAction(title: "Dismiss", style: .default, handler: nil)
errorAlert.addAction(dismissAction)
self.present(errorAlert, animated: true, completion: nil)
}
}
}
}
// MARK: Helper
func textChanged(_ textField: UITextField) {
doneButton.isEnabled = shouldEnableDoneButton()
}
// returns true if all of the text fields are filled out and the image is chosen.
func shouldEnableDoneButton() -> Bool {
// check if the fields are empty.
return (itemNameField.text?.characters.count) ?? 0 > 0 &&
(itemPriceField.text?.characters.count) ?? 0 > 0 &&
(Double(itemPriceField.text ?? "0.0") ?? 0.0) > 0.30 &&
(itemConditionField.text?.characters.count) ?? 0 > 0 &&
(itemDescription.text?.characters.count) ?? 0 > 0 &&
imageButton.backgroundImage(for: .normal) != nil
}
// setup the custom TextField
func setupTextField(_ textfield: UITextField) {
// edit password field
let width = CGFloat(1.5)
let border = CALayer()
border.borderColor = UIColor(colorLiteralRed: 0.298, green: 0.686, blue: 0.322, alpha: 1.0).cgColor // Green
border.frame = CGRect(x: 0, y: textfield.frame.size.height - width, width: textfield.frame.size.width, height: textfield.frame.size.height)
border.borderWidth = width
textfield.layer.addSublayer(border)
textfield.layer.masksToBounds = true
textfield.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
}
// dismiss a keyboard
func dismissKeyboard() {
itemNameField.resignFirstResponder()
itemPriceField.resignFirstResponder()
itemConditionField.resignFirstResponder()
itemDescription.resignFirstResponder()
}
// resize image
func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
print("resizing image")
print("old size: \(size)")
let widthRatio = targetSize.width / image.size.width
let heightRatio = targetSize.height / image.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print("new size: \(newImage!.size)")
return newImage!
}
}
| 12dd677def726ccdcbd222cc11c5b9d0 | 41.733333 | 249 | 0.633385 | false | false | false | false |
mlmc03/SwiftFM-DroidFM | refs/heads/master | Haneke/CryptoSwiftMD5.swift | apache-2.0 | 2 | //
// CryptoSwiftMD5.Swif
//
// To date, adding CommonCrypto to a Swift framework is problematic. See:
// http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework
// We're using a subset of CryptoSwift as a (temporary?) alternative.
// The following is an altered source version that only includes MD5. The original software can be found at:
// https://github.com/krzyzanowskim/CryptoSwift
// This is the original copyright notice:
/*
Copyright (C) 2014 Marcin Krzyżanowski <[email protected]>
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
- This notice may not be removed or altered from any source or binary distribution.
*/
import Foundation
/** array of bytes, little-endian representation */
func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] {
let totalBytes = length ?? (sizeofValue(value) * 8)
let valuePointer = UnsafeMutablePointer<T>.alloc(1)
valuePointer.memory = value
let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer)
var bytes = [UInt8](count: totalBytes, repeatedValue: 0)
for j in 0..<min(sizeof(T),totalBytes) {
bytes[totalBytes - 1 - j] = (bytesPointer + j).memory
}
valuePointer.destroy()
valuePointer.dealloc(1)
return bytes
}
extension Int {
/** Array of bytes with optional padding (little-endian) */
public func bytes(totalBytes: Int = sizeof(Int)) -> [UInt8] {
return arrayOfBytes(self, length: totalBytes)
}
}
extension NSMutableData {
/** Convenient way to append bytes */
internal func appendBytes(arrayOfBytes: [UInt8]) {
self.appendBytes(arrayOfBytes, length: arrayOfBytes.count)
}
}
class HashBase {
var message: NSData
init(_ message: NSData) {
self.message = message
}
/** Common part for hash calculation. Prepare header data. */
func prepare(len: Int = 64) -> NSMutableData {
let tmpMessage: NSMutableData = NSMutableData(data: self.message)
// Step 1. Append Padding Bits
tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
var msgLength = tmpMessage.length
var counter = 0
while msgLength % len != (len - 8) {
counter += 1
msgLength += 1
}
let bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8)))
tmpMessage.appendBytes(bufZeros, length: counter)
return tmpMessage
}
}
func rotateLeft(v: UInt32, n: UInt32) -> UInt32 {
return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
}
class MD5 : HashBase {
/** specifies the per-round shift amounts */
private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let k: [UInt32] = [0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,
0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,
0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,
0x6b901122,0xfd987193,0xa679438e,0x49b40821,
0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,
0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8,
0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,
0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,
0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,
0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,
0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05,
0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,
0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,
0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,
0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,
0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391]
private let h:[UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
func calculate() -> NSData {
let tmpMessage = prepare()
// hash values
var hh = h
// Step 2. Append Length a 64-bit representation of lengthInBits
let lengthInBits = (message.length * 8)
let lengthBytes = lengthInBits.bytes(64 / 8)
tmpMessage.appendBytes(lengthBytes.reverse())
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
var leftMessageBytes = tmpMessage.length
var i = 0
while i < tmpMessage.length {
defer {
i = i + chunkSizeBytes
leftMessageBytes -= chunkSizeBytes
}
let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
var M:[UInt32] = [UInt32](count: 16, repeatedValue: 0)
let range = NSRange(location:0, length: M.count * sizeof(UInt32))
chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range)
// Initialize hash value for this chunk:
var A:UInt32 = hh[0]
var B:UInt32 = hh[1]
var C:UInt32 = hh[2]
var D:UInt32 = hh[3]
var dTemp:UInt32 = 0
// Main loop
for j in 0..<k.count {
var g = 0
var F:UInt32 = 0
switch (j) {
case 0...15:
F = (B & C) | ((~B) & D)
g = j
break
case 16...31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32...47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48...63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), n: s[j])
A = dTemp
}
hh[0] = hh[0] &+ A
hh[1] = hh[1] &+ B
hh[2] = hh[2] &+ C
hh[3] = hh[3] &+ D
}
let buf: NSMutableData = NSMutableData()
hh.forEach({ (item) -> () in
var i:UInt32 = item.littleEndian
buf.appendBytes(&i, length: sizeofValue(i))
})
return buf.copy() as! NSData
}
} | 49cd156ca9fb3cf6a9d737eaa6b1acf8 | 35.565854 | 213 | 0.574249 | false | false | false | false |
melling/ios_topics | refs/heads/master | SimpleTableView/SimpleTableView/ViewController.swift | cc0-1.0 | 1 | //
// ViewController.swift
// SimpleTableView
//
// Created by Michael Mellinger on 3/8/16.
//
import UIKit
class ViewController: UIViewController {
private let tableViewController = SimpleTableViewController()
// MARK: - Build View
private func addTableView() {
tableViewController.tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableViewController.tableView)
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
tableViewController.tableView.topAnchor.constraint(equalToSystemSpacingBelow: guide.topAnchor, multiplier: 1.0),
tableViewController.tableView.bottomAnchor.constraint(equalToSystemSpacingBelow: guide.bottomAnchor, multiplier: 1.0),
tableViewController.tableView.leftAnchor.constraint(equalTo: guide.leftAnchor, constant: 0),
tableViewController.tableView.rightAnchor.constraint(equalTo: guide.rightAnchor, constant: 0),
])
}
// MARK: - View Management
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(named: "AppleVideosColor")
navigationController?.navigationBar.prefersLargeTitles = true
self.title = "Table Subclass"
addTableView()
}
}
| 5e4737c0610e9874398ba73c5da6aab8 | 26.959184 | 130 | 0.678102 | false | false | false | false |
nghiaphunguyen/NKit | refs/heads/master | NKit/Source/UINavigationController/UINavigationController+Animation.swift | mit | 1 | //
// UINavigationController+Animation.swift
//
// Created by Nghia Nguyen on 12/7/15.
//
import UIKit
public extension UINavigationController {
public func nk_animationPushToViewController(_ viewController: UIViewController,
duration: TimeInterval = 0.3,
type: CATransitionType = CATransitionType.moveIn,
subType: CATransitionSubtype = CATransitionSubtype.fromBottom,
timingFunc: CAMediaTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default)) {
let animation = CATransition()
animation.duration = duration
animation.type = type
animation.subtype = subType
animation.timingFunction = timingFunc
self.pushViewController(viewController, animated: false)
self.view.layer.add(animation, forKey: nil)
}
public func nk_animationPop(duration: TimeInterval = 0.3,
type: CATransitionType = CATransitionType.moveIn,
subType: CATransitionSubtype = CATransitionSubtype.fromBottom,
timingFunc: CAMediaTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default)) {
let animation = CATransition()
animation.duration = duration
animation.type = type
animation.subtype = subType
animation.timingFunction = timingFunc
self.view.layer.add(animation, forKey: nil)
self.popViewController(animated: false)
}
public func nk_animateToViewController(_ viewController: UIViewController) {
nk_animationPushToViewController(viewController, duration: 0.3, type: CATransitionType.moveIn, subType: CATransitionSubtype.fromRight)
}
public func nk_animatePushFromBottomToViewController(_ viewController: UIViewController) {
self.nk_animationPushToViewController(viewController, duration: 0.3, type: CATransitionType.moveIn, subType: CATransitionSubtype.fromTop)
}
public func nk_animatePopByFading() {
self.nk_animationPop(duration: 0.5, type: CATransitionType.fade, subType: CATransitionSubtype.fromRight)
}
public func nk_animatePopFromTop() {
self.nk_animationPop(duration: 0.3, type: CATransitionType.reveal, subType: CATransitionSubtype.fromBottom)
}
public func nk_animatePopFromLeft() {
self.nk_animationPop(duration: 0.3, type: CATransitionType.moveIn, subType: CATransitionSubtype.fromLeft)
}
public func nk_animatePopFromTopToViewController(_ viewController: UIViewController) {
let indexOfSaveVC: Int = self.viewControllers.index(of: viewController) ?? 0
var indexToPopNoAnimation: Int = self.viewControllers.count - 1
while indexToPopNoAnimation > indexOfSaveVC + 1 {
self.popViewController(animated: false)
indexToPopNoAnimation -= 1
}
self.nk_animationPop(duration: 0.3, type: CATransitionType.reveal, subType: CATransitionSubtype.fromBottom)
}
public func nk_animationPopToViewControllerClass(_ viewControllerClass: AnyClass) -> Bool {
if let viewController = self.nk_viewControllerOfClass(viewControllerClass) {
self.nk_animatePopFromTopToViewController(viewController)
return true
}
return false
}
public func nk_viewControllerOfClass(_ viewControllerClass: AnyClass) -> UIViewController? {
for vc: UIViewController in self.viewControllers {
if vc.isKind(of: viewControllerClass) {
return vc
}
}
return nil
}
}
| 61cb5ee642ab7ba0e91110ff7246654d | 43.4 | 150 | 0.662692 | false | false | false | false |
Mindera/Alicerce | refs/heads/master | Tests/AlicerceTests/DeepLinking/Route+ComponentTests.swift | mit | 1 | import XCTest
@testable import Alicerce
class Route_ComponentTests: XCTestCase {
// MARK: init
// success
func testInit_WithValidComponent_ShouldSucceed() {
XCTAssertEqual(try Route.Component(component: "test"), .constant("test"))
XCTAssertEqual(try Route.Component(component: ":test"), .parameter("test"))
XCTAssertEqual(try Route.Component(component: "*"), .wildcard)
XCTAssertEqual(try Route.Component(component: "**"), .catchAll(nil))
XCTAssertEqual(try Route.Component(component: "**test"), .catchAll("test"))
}
// failure
func testInit_WithValueContainingAForwardSlash_ShouldFail() {
XCTAssertInitThrowsUnallowedForwardSlash(value: "/")
XCTAssertInitThrowsUnallowedForwardSlash(value: "/foo")
XCTAssertInitThrowsUnallowedForwardSlash(value: "foo/")
XCTAssertInitThrowsUnallowedForwardSlash(value: "fo/o")
}
func testInit_WithValueConsistingOfAParameterWithAnEmptyName_ShouldFail() {
XCTAssertThrowsError(try Route.Component(component: ":"), "🔥 Unexpected success!") {
guard case Route.InvalidComponentError.emptyParameterName = $0 else {
XCTFail("🔥: unexpected error \($0)!")
return
}
}
}
func testInit_WithValueConsistingOfAnInvalidWildcard_ShouldFail() {
XCTAssertThrowsError(try Route.Component(component: "*foo"), "🔥 Unexpected success!") {
guard case Route.InvalidComponentError.invalidWildcard = $0 else {
XCTFail("🔥: unexpected error \($0)!")
return
}
}
}
// MARK: description
func testDescription_ShouldMatchValue() {
XCTAssertEqual(Route.Component("").description, "")
XCTAssertEqual(Route.Component("constant").description, "constant")
XCTAssertEqual(Route.Component(":parameter").description, ":parameter")
XCTAssertEqual(Route.Component("*").description, "*")
XCTAssertEqual(Route.Component("**").description, "**")
XCTAssertEqual(Route.Component("**catchAll").description, "**catchAll")
}
// MARK: debugDescription
func testDebugDescription_ShouldMatchValue() {
XCTAssertEqual(Route.Component("").debugDescription, ".constant()")
XCTAssertEqual(Route.Component("constant").debugDescription, ".constant(constant)")
XCTAssertEqual(Route.Component(":parameter").debugDescription, ".variable(parameter)")
XCTAssertEqual(Route.Component("*").debugDescription, ".wildcard")
XCTAssertEqual(Route.Component("**").debugDescription, ".catchAll")
XCTAssertEqual(Route.Component("**catchAll").debugDescription, ".catchAll(catchAll)")
}
// MARK: path
func testPath_WithEmptyArray_ShouldReturnEmptyString() {
XCTAssertEqual([Route.Component]().path, "")
}
func testPath_WithNotEmptyArray_ShouldReturnCorrectPathString() {
let componentsA: [Route.Component] = ["some", "path", ":with", "*", "**annotations"]
XCTAssertEqual(componentsA.path, "some/path/:with/*/**annotations")
let componentsB: [Route.Component] = ["yet", "another", ":path", "", "**"]
XCTAssertEqual(componentsB.path, "yet/another/:path//**")
}
}
private extension Route_ComponentTests {
func XCTAssertInitThrowsUnallowedForwardSlash(
value: String,
file: StaticString = #file,
line: UInt = #line
) {
XCTAssertThrowsError(
try Route.Component(component: value),
"🔥 Unexpected success!",
file: file,
line: line
) {
guard case Route.InvalidComponentError.unallowedForwardSlash = $0 else {
XCTFail("🔥: unexpected error \($0)!", file: file, line: line)
return
}
}
}
}
extension Route.Component: ExpressibleByStringLiteral {
public init(stringLiteral value: String) { try! self.init(component: value) }
}
| ba806b0d844b1b88eae5694668531d29 | 33.843478 | 95 | 0.644622 | false | true | false | false |
Zahzi/DMX-DIP-Converter | refs/heads/master | DMX-DIP Converter/Pods/LicensesKit/LicensesKit/Model/Licenses/CustomLicense.swift | gpl-3.0 | 2 | //
// CustomLicense.swift
// LicensesKit
//
// Created by Matthew Wyskiel on 10/11/14.
// Copyright (c) 2014 Matthew Wyskiel. All rights reserved.
//
import UIKit
/**
Describes a library's license that is not one of the default licenses included with this library.
*/
@objc public class CustomLicense: NSObject, License {
private var privateName: String = ""
/// The name of the license
public var name: String {
get {
return self.privateName
}
set {
self.privateName = newValue
}
}
private var privateSummaryText: String = ""
/// The license summary text
public var summaryText: String {
get {
return self.privateSummaryText
}
set {
self.privateSummaryText = newValue
}
}
private var privateFullText: String = ""
/// The license full text
public var fullText: String {
get {
return self.privateFullText
}
set {
self.privateFullText = newValue
}
}
private var privateVersion: String = ""
/// The license version
public var version: String {
get {
return self.privateVersion
}
set {
self.privateVersion = newValue
}
}
private var privateURL: String = ""
/// The license URL
public var url: String {
get {
return self.privateURL
}
set {
self.privateURL = newValue
}
}
/**
The designated initializer for a CustomLicense object.
- parameter name: The name of the license
- parameter summaryText: The license summary text
- parameter fullText: The license full text
- parameter version: The license version
- parameter url: The license URL
- returns: An instance of CustomLicense
*/
public init(name: String, summaryText: String, fullText: String, version: String, url: String) {
super.init()
self.name = name
self.summaryText = summaryText
self.fullText = fullText
self.version = version
self.url = url
}
private override init() {
}
}
/// Equatable conformance - defining equivalence for `CustomLicense`
public func ==(lhs: CustomLicense, rhs: CustomLicense) -> Bool {
return lhs.name == rhs.name
} | 555d19995697595c165c0ff63bf3e83b | 23.227723 | 100 | 0.577269 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Parse/omit_return_ifdecl.swift | apache-2.0 | 7 | // RUN: %target-swift-frontend %s -typecheck -verify
// MARK: - Helpers
@discardableResult
func logAndReturn<T : CustomStringConvertible>(_ t: T) -> String {
let log = "\(t)"
print(log)
return log
}
@discardableResult
func failableLogAndReturn<T : CustomStringConvertible>(_ t: T) throws -> String {
let log = "\(t)"
print(log)
return log
}
typealias MyOwnVoid = ()
func failableIdentity<T>(_ t: T) throws -> T {
#if true
t
#endif
}
enum MyOwnNever {}
func myOwnFatalError() -> MyOwnNever { fatalError() }
struct MyOwnInt : ExpressibleByIntegerLiteral { init(integerLiteral: Int) {} }
struct MyOwnFloat : ExpressibleByFloatLiteral { init(floatLiteral: Double) {} }
struct MyOwnBoolean : ExpressibleByBooleanLiteral { init(booleanLiteral: Bool) {} }
struct MyOwnString : ExpressibleByStringLiteral { init(stringLiteral: String) {} }
struct MyOwnInterpolation : ExpressibleByStringInterpolation { init(stringLiteral: String) {} }
enum Unit {
case only
}
struct Initable {}
struct StructWithProperty {
var foo: Int
}
@dynamicMemberLookup
struct DynamicStruct {
subscript(dynamicMember input: String) -> String { return input }
}
struct MyOwnArray<Element> : ExpressibleByArrayLiteral {
init(arrayLiteral elements: Element...) {}
}
struct MyOwnDictionary<Key, Value> : ExpressibleByDictionaryLiteral {
init(dictionaryLiteral elements: (Key, Value)...) {}
}
struct SubscriptableStruct {
subscript(int: Int) -> Int {
#if true
int
#endif
}
}
extension Int {
var zero: Int {
#if true
0
#endif
}
}
extension Optional where Wrapped == Int {
var someZero: Int? {
#if true
Int?.some(0)
#endif
}
}
protocol SomeProto {
func foo() -> String
}
struct SomeProtoConformer : SomeProto {
func foo() -> String { "howdy" }
}
class Base {}
class Derived : Base {}
extension Int {
init() { self = 0 }
}
// MARK: - Notable Free Functions
func identity<T>(_ t: T) -> T {
#if true
t
#endif
}
internal func _fatalErrorFlags() -> UInt32 {
#if true
return 0
#endif
}
internal func _assertionFailure(
_ prefix: StaticString, _ message: String,
flags: UInt32
) -> Never {
#if true
fatalError()
#endif
}
internal func _diagnoseUnexpectedEnumCaseValue<SwitchedValue, RawValue>(
type: SwitchedValue.Type,
rawValue: RawValue
) -> Never {
#if true
_assertionFailure("Fatal error",
"unexpected enum case '\(type)(rawValue: \(rawValue))'",
flags: _fatalErrorFlags())
#endif
}
// MARK: - Free Functions
func ff_nop() {
#if true
#endif
}
func ff_nop_false() {
#if false
#endif
}
func ff_missing() -> String {
#if true
#endif
}
func ff_implicit() -> String {
#if true
"hello"
#endif
}
func ff_explicit() -> String {
#if true
return "hello"
#endif
}
func ff_explicitClosure() -> () -> Void {
#if true
return { print("howdy") }
#endif
}
func ff_implicitClosure() -> () -> Void {
#if true
{ print("howdy") }
#endif
}
func ff_explicitMultilineClosure() -> () -> String {
#if true
return {
let one = "big a"
let two = "little a"
return "\(one) + \(two)"
}
#endif
}
func ff_implicitMultilineClosure() -> () -> String {
#if true
{
let one = "big a"
let two = "little a"
return "\(one) + \(two)"
}
#endif
}
func ff_implicitWrong() -> String {
#if true
17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}}
#endif
}
func ff_explicitWrong() -> String {
#if true
return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}}
#endif
}
func ff_implicitMulti() -> String {
#if true
print("uh oh")
"shucks howdy" // expected-warning {{string literal is unused}}
#endif
}
func ff_explicitMulti() -> String {
#if true
print("okay")
return "all right"
#endif
}
func ff_effectfulUsed() -> String {
#if true
logAndReturn("okay")
#endif
}
// Unused Returns
func ff_effectfulIgnored() {
#if true
logAndReturn("okay")
#endif
}
func ff_effectfulIgnoredExplicitReturnTypeVoid() -> Void {
#if true
logAndReturn("okay")
#endif
}
func ff_effectfulIgnoredExplicitReturnTypeSwiftVoid() -> Swift.Void {
#if true
logAndReturn("okay")
#endif
}
func ff_effectfulIgnoredExplicitReturnTypeMyVoidTypealias() -> MyOwnVoid {
#if true
logAndReturn("okay")
#endif
}
func ff_effectfulIgnoredExplicitReturnTypeEmptyTuple() -> () {
#if true
logAndReturn("okay")
#endif
}
// Stubs
func ff_stubImplicitReturn() {
#if true
fatalError()
#endif
}
func ff_stubExplicitReturnTypeVoid() -> Void {
#if true
fatalError()
#endif
}
func ff_stubExplicitReturnTypeSwiftVoid() -> Swift.Void {
#if true
fatalError()
#endif
}
func ff_stubExplicitReturnTypeMyVoidTypealias() -> MyOwnVoid {
#if true
fatalError()
#endif
}
func ff_stubExplicitReturnTypeEmptyTuple() -> () {
#if true
fatalError()
#endif
}
func ff_stubImplicitReturnNever() -> Never {
#if true
fatalError()
#endif
}
func ff_stubExplicitReturnNever() -> Never {
#if true
return fatalError()
#endif
}
func ff_stubExplicitReturnNeverAsMyOwnNever() -> MyOwnNever {
#if true
return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}}
#endif
}
func ff_stubExplicitReturnMyOwnNeverAsNever() -> Never {
#if true
return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}}
#endif
}
func ff_stubImplicitReturnNeverAsMyOwnNever() -> MyOwnNever {
#if true
fatalError()
#endif
}
func ff_stubImplicitReturnMyOwnNeverAsNever() -> Never {
#if true
myOwnFatalError()
#endif
}
func ff_stubReturnString() -> String {
#if true
fatalError()
#endif
}
func ff_stubReturnGeneric<T>() -> T {
#if true
fatalError()
#endif
}
// Trying
func ff_tryExplicit() throws -> String {
#if true
return try failableIdentity("shucks")
#endif
}
func ff_tryImplicit() throws -> String {
#if true
try failableIdentity("howdy")
#endif
}
func ff_tryExplicitMissingThrows() -> String {
#if true
return try failableIdentity("shucks") // expected-error {{errors thrown from here are not handled}}
#endif
}
func ff_tryImplicitMissingThrows() -> String {
#if true
try failableIdentity("howdy") // expected-error {{errors thrown from here are not handled}}
#endif
}
// Forced Trying
func ff_forceTryExplicit() -> String {
#if true
return try! failableIdentity("howdy")
#endif
}
func ff_forceTryImplicit() -> String {
#if true
try! failableIdentity("shucks")
#endif
}
func ff_forceTryExplicitAddingThrows() throws -> String {
#if true
return try! failableIdentity("howdy")
#endif
}
func ff_forceTryImplicitAddingThrows() throws -> String {
#if true
try! failableIdentity("shucks")
#endif
}
// Optional Trying
func ff_optionalTryExplicit() -> String? {
#if true
return try? failableIdentity("howdy")
#endif
}
func ff_optionalTryImplicit() -> String? {
#if true
try? failableIdentity("shucks")
#endif
}
func ff_optionalTryExplicitAddingThrows() throws -> String? {
#if true
return try? failableIdentity("shucks")
#endif
}
func ff_optionalTryImplicitAddingThrows() throws -> String? {
#if true
try? failableIdentity("howdy")
#endif
}
// Inferred Return Types
func ff_inferredIntegerLiteralInt() -> Int {
#if true
0
#endif
}
func ff_inferredIntegerLiteralInt8() -> Int8 {
#if true
0
#endif
}
func ff_inferredIntegerLiteralInt16() -> Int16 {
#if true
0
#endif
}
func ff_inferredIntegerLiteralInt32() -> Int32 {
#if true
0
#endif
}
func ff_inferredIntegerLiteralInt64() -> Int64 {
#if true
0
#endif
}
func ff_inferredIntegerLiteralMyOwnInt() -> MyOwnInt {
#if true
0
#endif
}
func ff_nilLiteralInt() -> Int? {
#if true
nil
#endif
}
func ff_inferredFloatLiteralFloat() -> Float {
#if true
0.0
#endif
}
func ff_inferredFloatLiteralDouble() -> Double {
#if true
0.0
#endif
}
func ff_inferredFloatLiteralMyOwnDouble() -> MyOwnFloat {
#if true
0.0
#endif
}
func ff_inferredBooleanLiteralBool() -> Bool {
#if true
true
#endif
}
func ff_inferredBooleanLiteralMyOwnBoolean() -> MyOwnBoolean {
#if true
true
#endif
}
func ff_inferredStringLiteralString() -> String {
#if true
"howdy"
#endif
}
func ff_inferredStringLiteralMyOwnString() -> MyOwnString {
#if true
"howdy"
#endif
}
func ff_inferredInterpolatedStringLiteralString() -> String {
#if true
"\(0) \(1)"
#endif
}
func ff_inferredInterpolatedStringLiteralString() -> MyOwnInterpolation {
#if true
"\(0) \(1)"
#endif
}
func ff_inferredMagicFile() -> StaticString {
#if true
#file
#endif
}
func ff_inferredMagicLine() -> UInt {
#if true
#line // expected-error {{#line directive was renamed to #sourceLocation}}
#endif // expected-error {{parameterless closing #sourceLocation() directive without prior opening #sourceLocation(file:,line:) directive}}
}
func ff_inferredMagicColumn() -> UInt {
#if true
#column
#endif
}
func ff_inferredMagicFunction() -> StaticString {
#if true
#function
#endif
}
func ff_inferredMagicDSOHandle() -> UnsafeRawPointer {
#if true
#dsohandle
#endif
}
func ff_implicitDiscardExpr() {
#if true
_ = 3
#endif
}
func ff_implicitMetatype() -> String.Type {
#if true
String.self
#endif
}
func ff_implicitMemberRef(_ instance: StructWithProperty) -> Int {
#if true
instance.foo
#endif
}
func ff_implicitDynamicMember(_ s: DynamicStruct) -> String {
#if true
s.foo
#endif
}
func ff_implicitParenExpr() -> Int {
#if true
(3 + 5)
#endif
}
func ff_implicitTupleExpr() -> (Int, Int) {
#if true
(3, 5)
#endif
}
func ff_implicitArrayExprArray() -> [Int] {
#if true
[1, 3, 5]
#endif
}
func ff_implicitArrayExprSet() -> Set<Int> {
#if true
[1, 3, 5]
#endif
}
func ff_implicitArrayExprMyOwnArray() -> MyOwnArray<Int> {
#if true
[1, 3, 5]
#endif
}
func ff_implicitDictionaryExprDictionary() -> [Int : Int] {
#if true
[1 : 1, 2 : 2]
#endif
}
func ff_implicitDictionaryExprMyOwnDictionary() -> MyOwnDictionary<Int, Int> {
#if true
[1 : 1, 2 : 2]
#endif
}
func ff_implicitSubscriptExpr(_ s: SubscriptableStruct) -> Int {
#if true
s[13]
#endif
}
func ff_implicitKeyPathExprWritableKeyPath() -> WritableKeyPath<Int, Int> {
#if true
\Int.self
#endif
}
func ff_implicitKeyPathExprKeyPath() -> WritableKeyPath<Int, Int> {
#if true
\Int.self.self
#endif
}
func ff_implicitTupleElementExpr() -> Int {
#if true
(1,field:2).field
#endif
}
func ff_implicitBindExpr(_ opt: Int?) -> Int? {
#if true
opt?.zero
#endif
}
func ff_implicitOptionalEvaluation(_ opt: Int?) -> Int? {
#if true
(opt?.zero.zero).someZero
#endif
}
func ff_implicitForceValue(_ opt: Int?) -> Int {
#if true
opt!
#endif
}
func ff_implicitTemporarilyEscapableExpr(_ cl: () -> Void) -> () -> Void {
#if true
withoutActuallyEscaping(cl) { $0 }
#endif
}
func ff_implicitOpenExistentialExpr(_ f: SomeProto) -> String {
#if true
f.foo()
#endif
}
func ff_implicitInjectIntoOptionalExpr(_ int: Int) -> Int? {
#if true
int
#endif
}
func ff_implicitTupleShuffle(_ input: (one: Int, two: Int)) -> (two: Int, one: Int) {
#if true
input // expected-warning {{expression shuffles the elements of this tuple; this behavior is deprecated}}
#endif
}
func ff_implicitCollectionUpcast(_ derived: [Derived]) -> [Base] {
#if true
derived
#endif
}
func ff_implicitErasureExpr(_ conformer: SomeProtoConformer) -> SomeProto {
#if true
conformer
#endif
}
func ff_implicitAnyHashableErasureExpr(_ int: Int) -> AnyHashable {
#if true
int
#endif
}
func ff_implicitCallExpr<Input, Output>(input: Input, function: (Input) -> Output) -> Output {
#if true
function(input)
#endif
}
func ff_implicitPrefixUnaryOperator(int: Int) -> Int {
#if true
-int
#endif
}
func ff_implicitBinaryOperator(lhs: Int, rhs: Int) -> Int {
#if true
lhs - rhs
#endif
}
func ff_implicitConstructorCallRefExpr(lhs: Int, rhs: Int) -> Int {
#if true
Int()
#endif
}
func ff_implicitIsExpr<T>(t: T) -> Bool {
#if true
t is Int
#endif
}
func ff_implicitCoerceExpr<T>() -> T.Type {
#if true
T.self as T.Type
#endif
}
func ff_implicitConditionalCheckedCastExprAs<T>(t: T) -> Int? {
#if true
t as? Int
#endif
}
func ff_implicitForceCheckedCastExpr<T>(t: T) -> Int {
#if true
t as! Int
#endif
}
func ff_conditional(_ condition: Bool) -> Int {
#if true
condition ? 1 : -1
#endif
}
var __ff_implicitAssignExpr: Int = 0
func ff_implicitAssignExpr(newValue: Int) -> Void {
#if true
__ff_implicitAssignExpr = newValue
#endif
}
func ff_implicitMemberAccessInit() -> Initable {
#if true
Initable.init()
#endif
}
func ff_implicitMemberAccessEnumCase() -> Unit {
#if true
Unit.only
#endif
}
// MARK: - Free Properties : Implicit Get
var fv_nop: () {
#if true
#endif
}
var fv_nop_false: () {
#if false
#endif
}
var fv_missing: String {
#if true
#endif
}
var fv_missing_test: String {
get {}
}
var fv_implicit: String {
#if true
"hello"
#endif
}
var fv_explicit: String {
#if true
return "hello"
#endif
}
var fv_explicitClosure: () -> Void {
#if true
return { print("howdy") }
#endif
}
var fv_implicitClosure: () -> Void {
#if true
{ print("howdy") }
#endif
}
var fv_explicitMultilineClosure: () -> String {
#if true
return {
let one = "big a"
let two = "little a"
return "\(one) + \(two)"
}
#endif
}
var fv_implicitMultilineClosure: () -> String {
#if true
{
let one = "big a"
let two = "little a"
return "\(one) + \(two)"
}
#endif
}
var fv_implicitWrong: String {
#if true
17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}}
#endif
}
var fv_explicitWrong: String {
#if true
return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}}
#endif
}
var fv_implicitMulti: String {
#if true
print("uh oh")
"shucks howdy" // expected-warning {{string literal is unused}}
#endif
}
var fv_explicitMulti: String {
#if true
print("okay")
return "all right"
#endif
}
var fv_effectfulUsed: String {
#if true
logAndReturn("okay")
#endif
}
// Unused returns
var fv_effectfulIgnored: () {
#if true
logAndReturn("okay")
#endif
}
var fv_effectfulIgnoredVoid: Void {
#if true
logAndReturn("okay")
#endif
}
var fv_effectfulIgnoredSwiftVoid: Swift.Void {
#if true
logAndReturn("okay")
#endif
}
// Stubs
var fv_stubEmptyTuple: () {
#if true
fatalError()
#endif
}
var fv_stubVoid: Void {
#if true
fatalError()
#endif
}
var fv_stubSwiftVoid: Swift.Void {
#if true
fatalError()
#endif
}
var fv_stubMyVoidTypealias: MyOwnVoid {
#if true
fatalError()
#endif
}
var fv_stubImplicitReturnNever: Never {
#if true
fatalError()
#endif
}
var fv_stubExplicitReturnNever: Never {
#if true
return fatalError()
#endif
}
var fv_stubExplicitReturnNeverAsMyOwnNever: MyOwnNever {
#if true
return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}}
#endif
}
var fv_stubExplicitReturnMyOwnNeverAsNever: Never {
#if true
return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}}
#endif
}
var fv_stubImplicitReturnNeverAsMyOwnNever: MyOwnNever {
#if true
fatalError()
#endif
}
var fv_stubImplicitReturnMyOwnNeverAsNever: Never {
#if true
myOwnFatalError()
#endif
}
var fv_stubString: String {
#if true
fatalError()
#endif
}
// Forced Trying
var fv_forceTryUnusedExplicit: () {
#if true
return try! failableLogAndReturn("oh") //expected-error {{unexpected non-void return value in void function}}
#endif
}
var fv_forceTryUnusedImplicit: () {
#if true
try! failableLogAndReturn("uh")
#endif
}
var fv_forceTryExplicit: String {
#if true
return try! failableIdentity("shucks")
#endif
}
var fv_forceTryImplicit: String {
#if true
try! failableIdentity("howdy")
#endif
}
// Optional Trying
var fv_optionalTryUnusedExplicit: () {
#if true
return try? failableLogAndReturn("uh") //expected-error {{unexpected non-void return value in void function}}
#endif
}
var fv_optionalTryUnusedImplicit: () {
#if true
try? failableLogAndReturn("oh") //expected-warning {{result of 'try?' is unused}}
#endif
}
var fv_optionalTryExplicit: String? {
#if true
return try? failableIdentity("shucks")
#endif
}
var fv_optionalTryImplicit: String? {
#if true
try? failableIdentity("howdy")
#endif
}
// MARK: - Free Properties : Get
var fvg_nop: () {
get {
#if true
#endif
}
}
var fvg_nop_false: () {
get {
#if false
#endif
}
}
var fvg_missing: String {
get {
#if true
#endif
}
}
var fvg_implicit: String {
get {
#if true
"hello"
#endif
}
}
var fvg_explicit: String {
get {
#if true
return "hello"
#endif
}
}
var fvg_explicitClosure: () -> Void {
get {
#if true
return { print("howdy") }
#endif
}
}
var fvg_implicitClosure: () -> Void {
get {
#if true
{
#if true
print("howdy")
#endif
}
#endif
}
}
var fvg_explicitMultilineClosure: () -> String {
get {
#if true
return {
let one = "big a"
let two = "little a"
return "\(one) + \(two)"
}
#endif
}
}
var fvg_implicitMultilineClosure: () -> String {
get {
#if true
{
let one = "big a"
let two = "little a"
return "\(one) + \(two)"
}
#endif
}
}
var fvg_implicitWrong: String {
get {
#if true
17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}}
#endif
}
}
var fvg_explicitWrong: String {
get {
#if true
return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}}
#endif
}
}
var fvg_implicitMulti: String {
get {
#if true
print("uh oh")
"shucks howdy" // expected-warning {{string literal is unused}}
#endif
}
}
var fvg_explicitMulti: String {
get {
#if true
print("okay")
return "all right"
#endif
}
}
var fvg_effectfulUsed: String {
get {
#if true
logAndReturn("okay")
#endif
}
}
// Unused returns
var fvg_effectfulIgnored: () {
get {
#if true
logAndReturn("okay")
#endif
}
}
var fvg_effectfulIgnoredVoid: Void {
get {
#if true
logAndReturn("okay")
#endif
}
}
var fvg_effectfulIgnoredSwiftVoid: Swift.Void {
get {
#if true
logAndReturn("okay")
#endif
}
}
// Stubs
var fvg_stubEmptyTuple: () {
get {
#if true
fatalError()
#endif
}
}
var fvg_stubVoid: Void {
get {
#if true
fatalError()
#endif
}
}
var fvg_stubSwiftVoid: Swift.Void {
get {
#if true
fatalError()
#endif
}
}
var fvg_stubMyVoidTypealias: MyOwnVoid {
get {
#if true
fatalError()
#endif
}
}
var fvg_stubImplicitReturnNever: Never {
get {
#if true
fatalError()
#endif
}
}
var fvg_stubExplicitReturnNever: Never {
get {
#if true
return fatalError()
#endif
}
}
var fvg_stubExplicitReturnNeverAsMyOwnNever: MyOwnNever {
get {
#if true
return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}}
#endif
}
}
var fvg_stubExplicitReturnMyOwnNeverAsNever: Never {
get {
#if true
return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}}
#endif
}
}
var fvg_stubImplicitReturnNeverAsMyOwnNever: MyOwnNever {
get {
#if true
fatalError()
#endif
}
}
var fvg_stubImplicitReturnMyOwnNeverAsNever: Never {
get {
#if true
myOwnFatalError()
#endif
}
}
var fvg_stubString: String {
get {
#if true
fatalError()
#endif
}
}
// Forced Trying
var fvg_forceTryExplicit: String {
get {
#if true
return try! failableIdentity("shucks")
#endif
}
}
var fvg_forceTryImplicit: String {
get {
#if true
try! failableIdentity("howdy")
#endif
}
}
// Optional Trying
var fvg_optionalTryExplicit: String? {
get {
#if true
return try? failableIdentity("shucks")
#endif
}
}
var fvg_optionalTryImplicit: String? {
get {
#if true
try? failableIdentity("howdy")
#endif
}
}
// MARK: - Free Properties : Set
var fvs_nop: () {
get {
#if true
#endif
}
set {
#if true
#endif
}
}
var fvs_nop_false: () {
get {
#if false
#endif
}
set {
#if false
#endif
}
}
var fvs_implicit: String {
get {
#if true
"ok"
#endif
}
set {
#if true
"hello" // expected-warning {{string literal is unused}}
#endif
}
}
var fvs_explicit: String {
get {
#if true
"ok"
#endif
}
set {
#if true
return "hello" // expected-error {{unexpected non-void return value in void function}}
#endif
}
}
var fvs_explicitClosure: () -> Void {
get {
#if true
return {
#if true
print("howdy")
#endif
}
#endif
}
set {
#if true
return { // expected-error {{unexpected non-void return value in void function}}
#if true
print("howdy")
#endif
}
#endif
}
}
var fvs_implicitClosure: () -> Void {
get {
#if true
{
#if true
print("howdy")
#endif
}
#endif
}
set {
#if true
{ // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}}
#if true
print("howdy")
#endif
}
#endif
}
}
var fvs_implicitWrong: String {
get {
#if true
"ok"
#endif
}
set {
#if true
17 // expected-warning {{integer literal is unused}}
#endif
}
}
var fvs_explicitWrong: String {
get {
#if true
"ok"
#endif
}
set {
#if true
return 17 // expected-error {{unexpected non-void return value in void function}}
#endif
}
}
var fvs_implicitMulti: String {
get {
#if true
"ok"
#endif
}
set {
#if true
print("uh oh")
"shucks howdy" // expected-warning {{string literal is unused}}
#endif
}
}
var fvs_explicitMulti: String {
get {
#if true
"ok"
#endif
}
set {
#if true
print("okay")
return "all right" // expected-error {{unexpected non-void return value in void function}}
#endif
}
}
var fvs_effectfulUsed: String {
get {
#if true
"ok"
#endif
}
set {
#if true
logAndReturn("okay")
#endif
}
}
// Stubs
var fvs_stub: () {
get {
#if true
()
#endif
}
set {
#if true
fatalError()
#endif
}
}
var fvs_stubMyOwnFatalError: () {
get {
#if true
()
#endif
}
set {
#if true
myOwnFatalError()
#endif
}
}
// Forced Trying
var fvs_forceTryExplicit: String {
get {
#if true
"ok"
#endif
}
set {
#if true
return try! failableIdentity("shucks") // expected-error {{unexpected non-void return value in void function}}
#endif
}
}
var fvs_forceTryImplicit: String {
get {
#if true
"ok"
#endif
}
set {
#if true
try! failableIdentity("howdy") // expected-warning {{result of call to 'failableIdentity' is unused}}
#endif
}
}
// Optional Trying
var fvs_optionalTryExplicit: String? {
get {
#if true
"ok"
#endif
}
set {
#if true
return try? failableIdentity("shucks") // expected-error {{unexpected non-void return value in void function}}
#endif
}
}
var fvs_optionalTryImplicit: String? {
get {
#if true
"ok"
#endif
}
set {
#if true
try? failableIdentity("howdy") // expected-warning {{result of 'try?' is unused}}
#endif
}
}
// MARK: - Free Properties : Read
// MARK: - Free Properties : Modify
// MARK: - Subscripts : Implicit Readonly
enum S_nop {
subscript() -> () {
#if true
#endif
}
}
enum S_nop_false {
subscript() -> () {
#if false
#endif
}
}
enum S_missing {
subscript() -> String {
#if true
#endif
}
}
enum S_implicit {
subscript() -> String {
#if true
"hello"
#endif
}
}
enum S_explicit {
subscript() -> String {
#if true
return "hello"
#endif
}
}
enum S_explicitClosure {
subscript() -> () -> Void {
#if true
return { print("howdy") }
#endif
}
}
enum S_implicitClosure {
subscript() -> () -> Void {
#if true
{
#if true
print("howdy")
#endif
}
#endif
}
}
enum S_explicitMultilineClosure {
subscript() -> () -> String {
#if true
return {
let one = "big a"
let two = "little a"
return "\(one) + \(two)"
}
#endif
}
}
enum S_implicitMultilineClosure {
subscript() -> () -> String {
#if true
{
let one = "big a"
let two = "little a"
return "\(one) + \(two)"
}
#endif
}
}
enum S_implicitWrong {
subscript() -> String {
#if true
17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}}
#endif
}
}
enum S_explicitWrong {
subscript() -> String {
#if true
return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}}
#endif
}
}
enum S_implicitMulti {
subscript() -> String {
#if true
print("uh oh")
"shucks howdy" // expected-warning {{string literal is unused}}
#endif
}
}
enum S_explicitMulti {
subscript() -> String {
#if true
print("okay")
return "all right"
#endif
}
}
enum S_effectfulUsed {
subscript() -> String {
#if true
logAndReturn("okay")
#endif
}
}
// Unused returns
enum S_effectfulIgnored {
subscript() -> () {
#if true
logAndReturn("okay")
#endif
}
}
enum S_effectfulIgnoredVoid {
subscript() -> Void {
#if true
logAndReturn("okay")
#endif
}
}
enum S_effectfulIgnoredSwiftVoid {
subscript() -> Swift.Void {
#if true
logAndReturn("okay")
#endif
}
}
// Stubs
enum S_stubEmptyTuple {
subscript() -> () {
#if true
fatalError()
#endif
}
}
enum S_stubVoid {
subscript() -> Void {
#if true
fatalError()
#endif
}
}
enum S_stubSwiftVoid {
subscript() -> Swift.Void {
#if true
fatalError()
#endif
}
}
enum S_stubMyVoidTypealias {
subscript() -> MyOwnVoid {
#if true
fatalError()
#endif
}
}
enum S_stubImplicitReturnNever {
subscript() -> Never {
#if true
fatalError()
#endif
}
}
enum S_stubExplicitReturnNever {
subscript() -> Never {
#if true
return fatalError()
#endif
}
}
enum S_stubExplicitReturnNeverAsMyOwnNever {
subscript() -> MyOwnNever {
#if true
return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}}
#endif
}
}
enum S_stubExplicitReturnMyOwnNeverAsNever {
subscript() -> Never {
#if true
return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}}
#endif
}
}
enum S_stubImplicitReturnNeverAsMyOwnNever {
subscript() -> MyOwnNever {
#if true
fatalError()
#endif
}
}
enum S_stubImplicitReturnMyOwnNeverAsNever {
subscript() -> Never {
#if true
myOwnFatalError()
#endif
}
}
enum S_stubString {
subscript() -> String {
#if true
fatalError()
#endif
}
}
enum S_stubGeneric {
subscript<T>() -> T {
#if true
fatalError()
#endif
}
}
// Forced Trying
enum S_forceTryExplicit {
subscript() -> String {
#if true
return try! failableIdentity("shucks")
#endif
}
}
enum S_forceTryImplicit {
subscript() -> String {
#if true
try! failableIdentity("howdy")
#endif
}
}
// Optional Trying
enum S_optionalTryExplicit {
subscript() -> String? {
#if true
return try? failableIdentity("shucks")
#endif
}
}
enum S_optionalTryImplicit {
subscript() -> String? {
#if true
try? failableIdentity("howdy")
#endif
}
}
// MARK: - Subscripts : Explicit Readonly
enum SRO_nop {
subscript() -> () {
get {
#if true
#endif
}
}
}
enum SRO_nop_false {
subscript() -> () {
get {
#if false
#endif
}
}
}
enum SRO_missing {
subscript() -> String {
get {
#if true
#endif
}
}
}
enum SRO_implicit {
subscript() -> String {
get {
#if true
"hello"
#endif
}
}
}
enum SRO_explicit {
subscript() -> String {
get {
#if true
return "hello"
#endif
}
}
}
enum SRO_explicitClosure {
subscript() -> () -> Void {
get {
#if true
return {
#if true
print("howdy")
#endif
}
#endif
}
}
}
enum SRO_implicitClosure {
subscript() -> () -> Void {
get {
#if true
{
#if true
print("howdy")
#endif
}
#endif
}
}
}
enum SRO_explicitMultilineClosure {
subscript() -> () -> String {
get {
#if true
return {
let one = "big a"
let two = "little a"
return "\(one) + \(two)"
}
#endif
}
}
}
enum SRO_implicitMultilineClosure {
subscript() -> () -> String {
get {
#if true
{
let one = "big a"
let two = "little a"
return "\(one) + \(two)"
}
#endif
}
}
}
enum SRO_implicitWrong {
subscript() -> String {
get {
#if true
17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}}
#endif
}
}
}
enum SRO_explicitWrong {
subscript() -> String {
get {
#if true
return 17 // expected-error {{cannot convert return expression of type 'Int' to return type 'String'}}
#endif
}
}
}
enum SRO_implicitMulti {
subscript() -> String {
get {
#if true
print("uh oh")
"shucks howdy" // expected-warning {{string literal is unused}}
#endif
}
}
}
enum SRO_explicitMulti {
subscript() -> String {
get {
#if true
print("okay")
return "all right"
#endif
}
}
}
enum SRO_effectfulUsed {
subscript() -> String {
get {
#if true
logAndReturn("okay")
#endif
}
}
}
// Unused returns
enum SRO_effectfulIgnored {
subscript() -> () {
get {
#if true
logAndReturn("okay")
#endif
}
}
}
enum SRO_effectfulIgnoredVoid {
subscript() -> Void {
get {
#if true
logAndReturn("okay")
#endif
}
}
}
enum SRO_effectfulIgnoredSwiftVoid {
subscript() -> Swift.Void {
get {
#if true
logAndReturn("okay")
#endif
}
}
}
// Stubs
enum SRO_stubEmptyTuple {
subscript() -> () {
get {
#if true
fatalError()
#endif
}
}
}
enum SRO_stubVoid {
subscript() -> Void {
get {
#if true
fatalError()
#endif
}
}
}
enum SRO_stubSwiftVoid {
subscript() -> Swift.Void {
get {
#if true
fatalError()
#endif
}
}
}
enum SRO_stubMyVoidTypealias {
subscript() -> MyOwnVoid {
get {
#if true
fatalError()
#endif
}
}
}
enum SRO_stubImplicitReturnNever {
subscript() -> Never {
get {
#if true
fatalError()
#endif
}
}
}
enum SRO_stubExplicitReturnNever {
subscript() -> Never {
get {
#if true
return fatalError()
#endif
}
}
}
enum SRO_stubExplicitReturnNeverAsMyOwnNever {
subscript() -> MyOwnNever {
get {
#if true
return fatalError() // expected-error {{cannot convert return expression of type 'Never' to return type 'MyOwnNever'}}
#endif
}
}
}
enum SRO_stubExplicitReturnMyOwnNeverAsNever {
subscript() -> Never {
get {
#if true
return myOwnFatalError() // expected-error {{cannot convert return expression of type 'MyOwnNever' to return type 'Never'}}
#endif
}
}
}
enum SRO_stubImplicitReturnNeverAsMyOwnNever {
subscript() -> MyOwnNever {
get {
#if true
fatalError()
#endif
}
}
}
enum SRO_stubImplicitReturnMyOwnNeverAsNever {
subscript() -> Never {
get {
#if true
myOwnFatalError()
#endif
}
}
}
enum SRO_stubString {
subscript() -> String {
get {
#if true
fatalError()
#endif
}
}
}
enum SRO_stubGeneric {
subscript<T>() -> T {
get {
#if true
fatalError()
#endif
}
}
}
// Forced Trying
enum SRO_forceTryExplicit {
subscript() -> String {
get {
#if true
return try! failableIdentity("shucks")
#endif
}
}
}
enum SRO_forceTryImplicit {
subscript() -> String {
get {
#if true
try! failableIdentity("howdy")
#endif
}
}
}
// Optional Trying
enum SRO_optionalTryExplicit {
subscript() -> String? {
get {
#if true
return try? failableIdentity("shucks")
#endif
}
}
}
enum SRO_optionalTryImplicit {
subscript() -> String? {
get {
#if true
try? failableIdentity("howdy")
#endif
}
}
}
// MARK: - Subscripts : Set
// MARK: - Subscripts : Read/Modify
// MARK: - Constructors
struct C_nop {
init() {
#if true
#endif
}
}
struct C_nop_false {
init() {
#if false
#endif
}
}
struct C_missing {
var i: Int
init?() {
#if true
#endif
}
}
struct C_implicitNil {
init?() {
#if true
nil
#endif
}
}
struct C_explicitNil {
init?() {
#if true
return nil
#endif
}
}
struct C_forcedMissing {
var i: Int
init!() {
#if true
#endif
}
}
struct C_forcedImplicitNil {
init!() {
#if true
nil
#endif
}
}
struct C_forcedExplicitNil {
init?() {
#if true
return nil
#endif
}
}
struct C_implicit {
init() {
#if true
"hello" // expected-warning {{string literal is unused}}
#endif
}
}
struct C_explicit {
init() {
#if true
return "hello" // expected-error {{'nil' is the only return value permitted in an initializer}}
#endif
}
}
// MARK: - Destructors
class D_nop {
deinit {
#if true
#endif
}
}
class D_nop_false {
deinit {
#if false
#endif
}
}
class D_implicit {
deinit {
#if true
"bye now" // expected-warning {{string literal is unused}}
#endif
}
}
class D_explicit {
deinit {
#if true
return "bye now" // expected-error {{unexpected non-void return value in void function}}
#endif
}
}
class D_implicitMulti {
deinit {
#if true
print("okay")
"see ya" // expected-warning {{string literal is unused}}
#endif
}
}
class D_explicitMulti {
deinit {
#if true
print("okay")
return "see ya" // expected-error {{unexpected non-void return value in void function}}
#endif
}
}
// Unused returns
class D_effectfulIgnored {
deinit {
#if true
logAndReturn("bye now")
#endif
}
}
// Stubs
class D_stub {
deinit {
#if true
fatalError()
#endif
}
}
class D_stubMyOwnDeinit {
deinit {
#if true
myOwnFatalError()
#endif
}
}
// Forced Trying
class D_forceTryUnusedExplicit {
deinit {
#if true
return try! failableLogAndReturn("uh") // expected-error {{unexpected non-void return value in void function}}
#endif
}
}
class D_forceTryUnusedImplicit {
deinit {
#if true
try! failableLogAndReturn("oh")
#endif
}
}
// Optional Trying
class D_optionalTryUnusedExplicit {
deinit {
#if true
return try? failableLogAndReturn("uh") // expected-error {{unexpected non-void return value in void function}}
#endif
}
}
class D_optionalTryUnusedImplicit {
deinit {
#if true
try? failableLogAndReturn("oh") // expected-warning {{result of 'try?' is unused}}
#endif
}
}
// Miscellaneous
class CSuperExpr_Base { init() {} }
class CSuperExpr_Derived : CSuperExpr_Base { override init() { super.init() } }
class CImplicitIdentityExpr { func gimme() -> CImplicitIdentityExpr { self } }
class CImplicitDotSelfExpr { func gimme() -> CImplicitDotSelfExpr { self.self } }
func badIs<T>(_ value: Any, anInstanceOf type: T.Type) -> Bool {
#if true
value is type // expected-error {{cannot find type 'type' in scope}}
#endif
}
// Autoclosure Discriminators
func embedAutoclosure_standard() -> Int {
#if true
_helpEmbedAutoclosure_standard(42)
#endif
}
func _helpEmbedAutoclosure_standard<T>(_ value: @autoclosure () -> T) -> T {
#if true
value()
#endif
}
func embedAutoclosure_never() -> Int {
#if true
fatalError("unsupported")
#endif
}
// MARK: - If Declaration Variations
var double_nested_ifdecl: Int {
#if true
#if true
0
#endif
#endif
}
var triple_nested_ifdecl: Int {
#if true
#if true
#if true
0
#endif
#endif
#endif
}
var false_ifdecl: Int {
#if false
0
#else
1
#endif
}
var false_nested_ifdecl: Int {
#if false
0
#else
1
#endif
}
var mismatched_explicit_return_ifdecl: Int {
#if true
return 0
#else
1
#endif
}
var mismatched_implicit_return_ifdecl: Int {
#if true
0
#else
return 1
#endif
}
enum VerticalDirection {
case up, down
}
func implicitMember() -> VerticalDirection {
#if false
.up
#elseif true
.down
#else
.unknown
#endif
}
| 19c60566ba6c0937f41eb76ed3e31a34 | 15.665479 | 143 | 0.547711 | false | false | false | false |
pcperini/Thrust | refs/heads/master | Thrust/Source/Dictionary+ThrustExtensions.swift | mit | 1 | //
// Dictionary+ThrustExtensions.swift
// Thrust
//
// Created by Patrick Perini on 7/22/14.
// Copyright (c) 2014 pcperini. All rights reserved.
//
import Foundation
// MARK: - Operators
/// Adds the key-value relationships from the right-hand dictionary to the left-hand dictionary.
func +=<Key, Value>(inout lhs: [Key: Value], rhs: [Key: Value]) {
for key: Key in rhs.keys {
lhs[key] = rhs[key]
}
}
/// Removes the keys found in the right-hand array from the left-hand dictionary.
func -=<Key, Value>(inout lhs: [Key: Value], rhs: [Key]) {
for key: Key in rhs {
lhs.removeValueForKey(key)
}
}
extension Dictionary {
/// Initializes the dictionary from a set of 2-tuple key/values.
init(_ values: [(Key, Value)]) {
self = [:]
for (key, value) in values {
self[key] = value
}
}
} | 79313c9adb3c5bb0ed5e48041fa28617 | 24.588235 | 96 | 0.61565 | false | false | false | false |
gmilos/swift | refs/heads/master | stdlib/public/SDK/Foundation/NSError.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import CoreFoundation
import Darwin
//===----------------------------------------------------------------------===//
// NSError (as an out parameter).
//===----------------------------------------------------------------------===//
public typealias NSErrorPointer = AutoreleasingUnsafeMutablePointer<NSError?>?
// Note: NSErrorPointer becomes ErrorPointer in Swift 3.
public typealias ErrorPointer = NSErrorPointer
public // COMPILER_INTRINSIC
let _nilObjCError: Error = _GenericObjCError.nilError
@_silgen_name("swift_convertNSErrorToError")
public // COMPILER_INTRINSIC
func _convertNSErrorToError(_ error: NSError?) -> Error {
if let error = error {
return error
}
return _nilObjCError
}
@_silgen_name("swift_convertErrorToNSError")
public // COMPILER_INTRINSIC
func _convertErrorToNSError(_ error: Error) -> NSError {
return unsafeDowncast(_bridgeErrorToNSError(error), to: NSError.self)
}
/// Describes an error that provides localized messages describing why
/// an error occurred and provides more information about the error.
public protocol LocalizedError : Error {
/// A localized message describing what error occurred.
var errorDescription: String? { get }
/// A localized message describing the reason for the failure.
var failureReason: String? { get }
/// A localized message describing how one might recover from the failure.
var recoverySuggestion: String? { get }
/// A localized message providing "help" text if the user requests help.
var helpAnchor: String? { get }
}
public extension LocalizedError {
var errorDescription: String? { return nil }
var failureReason: String? { return nil }
var recoverySuggestion: String? { return nil }
var helpAnchor: String? { return nil }
}
@_silgen_name("NS_Swift_performErrorRecoverySelector")
internal func NS_Swift_performErrorRecoverySelector(
delegate: AnyObject?,
selector: Selector,
success: ObjCBool,
contextInfo: UnsafeMutableRawPointer?)
/// Class that implements the informal protocol
/// NSErrorRecoveryAttempting, which is used by NSError when it
/// attempts recovery from an error.
class _NSErrorRecoveryAttempter {
@objc(attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:)
func attemptRecovery(fromError nsError: NSError,
optionIndex recoveryOptionIndex: Int,
delegate: AnyObject?,
didRecoverSelector: Selector,
contextInfo: UnsafeMutableRawPointer?) {
let error = nsError as Error as! RecoverableError
error.attemptRecovery(optionIndex: recoveryOptionIndex) { success in
NS_Swift_performErrorRecoverySelector(
delegate: delegate,
selector: didRecoverSelector,
success: ObjCBool(success),
contextInfo: contextInfo)
}
}
@objc(attemptRecoveryFromError:optionIndex:)
func attemptRecovery(fromError nsError: NSError,
optionIndex recoveryOptionIndex: Int) -> Bool {
let error = nsError as Error as! RecoverableError
return error.attemptRecovery(optionIndex: recoveryOptionIndex)
}
}
/// Describes an error that may be recoverable by presenting several
/// potential recovery options to the user.
public protocol RecoverableError : Error {
/// Provides a set of possible recovery options to present to the user.
var recoveryOptions: [String] { get }
/// Attempt to recover from this error when the user selected the
/// option at the given index. This routine must call handler and
/// indicate whether recovery was successful (or not).
///
/// This entry point is used for recovery of errors handled at a
/// "document" granularity, that do not affect the entire
/// application.
func attemptRecovery(optionIndex recoveryOptionIndex: Int,
resultHandler handler: (_ recovered: Bool) -> Void)
/// Attempt to recover from this error when the user selected the
/// option at the given index. Returns true to indicate
/// successful recovery, and false otherwise.
///
/// This entry point is used for recovery of errors handled at
/// the "application" granularity, where nothing else in the
/// application can proceed until the attempted error recovery
/// completes.
func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool
}
public extension RecoverableError {
/// Default implementation that uses the application-model recovery
/// mechanism (``attemptRecovery(optionIndex:)``) to implement
/// document-modal recovery.
func attemptRecovery(optionIndex recoveryOptionIndex: Int,
resultHandler handler: (_ recovered: Bool) -> Void) {
handler(attemptRecovery(optionIndex: recoveryOptionIndex))
}
}
/// Describes an error type that specifically provides a domain, code,
/// and user-info dictionary.
public protocol CustomNSError : Error {
/// The domain of the error.
static var errorDomain: String { get }
/// The error code within the given domain.
var errorCode: Int { get }
/// The user-info dictionary.
var errorUserInfo: [String : Any] { get }
}
public extension CustomNSError {
/// Default domain of the error.
static var errorDomain: String {
return String(reflecting: type(of: self))
}
/// The error code within the given domain.
var errorCode: Int {
return _swift_getDefaultErrorCode(self)
}
/// The default user-info dictionary.
var errorUserInfo: [String : Any] {
return [:]
}
}
extension CustomNSError where Self: RawRepresentable, Self.RawValue: SignedInteger {
// The error code of Error with integral raw values is the raw value.
public var errorCode: Int {
return numericCast(self.rawValue)
}
}
extension CustomNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger {
// The error code of Error with integral raw values is the raw value.
public var errorCode: Int {
return numericCast(self.rawValue)
}
}
public extension Error where Self : CustomNSError {
/// Default implementation for customized NSErrors.
var _domain: String { return Self.errorDomain }
/// Default implementation for customized NSErrors.
var _code: Int { return self.errorCode }
}
public extension Error where Self: CustomNSError, Self: RawRepresentable,
Self.RawValue: SignedInteger {
/// Default implementation for customized NSErrors.
var _code: Int { return self.errorCode }
}
public extension Error where Self: CustomNSError, Self: RawRepresentable,
Self.RawValue: UnsignedInteger {
/// Default implementation for customized NSErrors.
var _code: Int { return self.errorCode }
}
public extension Error {
/// Retrieve the localized description for this error.
var localizedDescription: String {
return (self as NSError).localizedDescription
}
}
internal let _errorDomainUserInfoProviderQueue = DispatchQueue(
label: "SwiftFoundation._errorDomainUserInfoProviderQueue")
/// Retrieve the default userInfo dictionary for a given error.
@_silgen_name("swift_Foundation_getErrorDefaultUserInfo")
public func _swift_Foundation_getErrorDefaultUserInfo(_ error: Error)
-> AnyObject? {
let hasUserInfoValueProvider: Bool
// If the OS supports user info value providers, use those
// to lazily populate the user-info dictionary for this domain.
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
// Note: the Cocoa error domain specifically excluded from
// user-info value providers.
let domain = error._domain
if domain != NSCocoaErrorDomain {
_errorDomainUserInfoProviderQueue.sync {
if NSError.userInfoValueProvider(forDomain: domain) != nil { return }
NSError.setUserInfoValueProvider(forDomain: domain) { (nsError, key) in
let error = nsError as Error
switch key {
case NSLocalizedDescriptionKey:
return (error as? LocalizedError)?.errorDescription
case NSLocalizedFailureReasonErrorKey:
return (error as? LocalizedError)?.failureReason
case NSLocalizedRecoverySuggestionErrorKey:
return (error as? LocalizedError)?.recoverySuggestion
case NSHelpAnchorErrorKey:
return (error as? LocalizedError)?.helpAnchor
case NSLocalizedRecoveryOptionsErrorKey:
return (error as? RecoverableError)?.recoveryOptions
case NSRecoveryAttempterErrorKey:
if error is RecoverableError {
return _NSErrorRecoveryAttempter()
}
return nil
default:
return nil
}
}
}
assert(NSError.userInfoValueProvider(forDomain: domain) != nil)
hasUserInfoValueProvider = true
} else {
hasUserInfoValueProvider = false
}
} else {
hasUserInfoValueProvider = false
}
// Populate the user-info dictionary
var result: [String : Any]
// Initialize with custom user-info.
if let customNSError = error as? CustomNSError {
result = customNSError.errorUserInfo
} else {
result = [:]
}
// Handle localized errors. If we registered a user-info value
// provider, these will computed lazily.
if !hasUserInfoValueProvider,
let localizedError = error as? LocalizedError {
if let description = localizedError.errorDescription {
result[NSLocalizedDescriptionKey] = description
}
if let reason = localizedError.failureReason {
result[NSLocalizedFailureReasonErrorKey] = reason
}
if let suggestion = localizedError.recoverySuggestion {
result[NSLocalizedRecoverySuggestionErrorKey] = suggestion
}
if let helpAnchor = localizedError.helpAnchor {
result[NSHelpAnchorErrorKey] = helpAnchor
}
}
// Handle recoverable errors. If we registered a user-info value
// provider, these will computed lazily.
if !hasUserInfoValueProvider,
let recoverableError = error as? RecoverableError {
result[NSLocalizedRecoveryOptionsErrorKey] =
recoverableError.recoveryOptions
result[NSRecoveryAttempterErrorKey] = _NSErrorRecoveryAttempter()
}
return result as AnyObject
}
// NSError and CFError conform to the standard Error protocol. Compiler
// magic allows this to be done as a "toll-free" conversion when an NSError
// or CFError is used as an Error existential.
extension NSError : Error {
public var _domain: String { return domain }
public var _code: Int { return code }
public var _userInfo: AnyObject? { return userInfo as NSDictionary }
/// The "embedded" NSError is itself.
public func _getEmbeddedNSError() -> AnyObject? {
return self
}
}
extension CFError : Error {
public var _domain: String {
return CFErrorGetDomain(self) as String
}
public var _code: Int {
return CFErrorGetCode(self)
}
public var _userInfo: AnyObject? {
return CFErrorCopyUserInfo(self) as AnyObject
}
/// The "embedded" NSError is itself.
public func _getEmbeddedNSError() -> AnyObject? {
return self
}
}
// An error value to use when an Objective-C API indicates error
// but produces a nil error object.
public enum _GenericObjCError : Error {
case nilError
}
/// An internal protocol to represent Swift error enums that map to standard
/// Cocoa NSError domains.
public protocol _ObjectiveCBridgeableError : Error {
/// Produce a value of the error type corresponding to the given NSError,
/// or return nil if it cannot be bridged.
init?(_bridgedNSError: NSError)
}
/// A hook for the runtime to use _ObjectiveCBridgeableError in order to
/// attempt an "errorTypeValue as? SomeError" cast.
///
/// If the bridge succeeds, the bridged value is written to the uninitialized
/// memory pointed to by 'out', and true is returned. Otherwise, 'out' is
/// left uninitialized, and false is returned.
@_silgen_name("swift_stdlib_bridgeNSErrorToError")
public func _stdlib_bridgeNSErrorToError<
T : _ObjectiveCBridgeableError
>(_ error: NSError, out: UnsafeMutablePointer<T>) -> Bool {
if let bridged = T(_bridgedNSError: error) {
out.initialize(to: bridged)
return true
} else {
return false
}
}
/// Helper protocol for _BridgedNSError, which used to provide
/// default implementations.
public protocol __BridgedNSError : Error {
static var _nsErrorDomain: String { get }
}
// Allow two bridged NSError types to be compared.
extension __BridgedNSError
where Self: RawRepresentable, Self.RawValue: SignedInteger {
public static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.rawValue.toIntMax() == rhs.rawValue.toIntMax()
}
}
public extension __BridgedNSError
where Self: RawRepresentable, Self.RawValue: SignedInteger {
public final var _domain: String { return Self._nsErrorDomain }
public final var _code: Int { return Int(rawValue.toIntMax()) }
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
public init?(_bridgedNSError: NSError) {
if _bridgedNSError.domain != Self._nsErrorDomain {
return nil
}
self.init(rawValue: RawValue(IntMax(_bridgedNSError.code)))
}
public final var hashValue: Int { return _code }
}
// Allow two bridged NSError types to be compared.
extension __BridgedNSError
where Self: RawRepresentable, Self.RawValue: UnsignedInteger {
public static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.rawValue.toUIntMax() == rhs.rawValue.toUIntMax()
}
}
public extension __BridgedNSError
where Self: RawRepresentable, Self.RawValue: UnsignedInteger {
public final var _domain: String { return Self._nsErrorDomain }
public final var _code: Int {
return Int(bitPattern: UInt(rawValue.toUIntMax()))
}
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
public init?(_bridgedNSError: NSError) {
if _bridgedNSError.domain != Self._nsErrorDomain {
return nil
}
self.init(rawValue: RawValue(UIntMax(UInt(_bridgedNSError.code))))
}
public final var hashValue: Int { return _code }
}
/// Describes a raw representable type that is bridged to a particular
/// NSError domain.
///
/// This protocol is used primarily to generate the conformance to
/// _ObjectiveCBridgeableError for such an enum.
public protocol _BridgedNSError : __BridgedNSError,
RawRepresentable,
_ObjectiveCBridgeableError,
Hashable {
/// The NSError domain to which this type is bridged.
static var _nsErrorDomain: String { get }
}
/// Describes a bridged error that stores the underlying NSError, so
/// it can be queried.
public protocol _BridgedStoredNSError :
__BridgedNSError, _ObjectiveCBridgeableError, CustomNSError,
Hashable {
/// The type of an error code.
associatedtype Code: _ErrorCodeProtocol
/// The error code for the given error.
var code: Code { get }
//// Retrieves the embedded NSError.
var _nsError: NSError { get }
/// Create a new instance of the error type with the given embedded
/// NSError.
///
/// The \c error must have the appropriate domain for this error
/// type.
init(_nsError error: NSError)
}
/// TODO: Better way to do this?
internal func _stringDictToAnyHashableDict(_ input: [String : Any])
-> [AnyHashable : Any] {
var result = [AnyHashable : Any](minimumCapacity: input.count)
for (k, v) in input {
result[k] = v
}
return result
}
/// Various helper implementations for _BridgedStoredNSError
public extension _BridgedStoredNSError
where Code: RawRepresentable, Code.RawValue: SignedInteger {
// FIXME: Generalize to Integer.
public var code: Code {
return Code(rawValue: numericCast(_nsError.code))!
}
/// Initialize an error within this domain with the given ``code``
/// and ``userInfo``.
public init(_ code: Code, userInfo: [String : Any] = [:]) {
self.init(_nsError: NSError(domain: Self._nsErrorDomain,
code: numericCast(code.rawValue),
userInfo: _stringDictToAnyHashableDict(userInfo)))
}
/// The user-info dictionary for an error that was bridged from
/// NSError.
var userInfo: [String : Any] { return errorUserInfo }
}
/// Various helper implementations for _BridgedStoredNSError
public extension _BridgedStoredNSError
where Code: RawRepresentable, Code.RawValue: UnsignedInteger {
// FIXME: Generalize to Integer.
public var code: Code {
return Code(rawValue: numericCast(_nsError.code))!
}
/// Initialize an error within this domain with the given ``code``
/// and ``userInfo``.
public init(_ code: Code, userInfo: [String : Any] = [:]) {
self.init(_nsError: NSError(domain: Self._nsErrorDomain,
code: numericCast(code.rawValue),
userInfo: _stringDictToAnyHashableDict(userInfo)))
}
}
/// Implementation of __BridgedNSError for all _BridgedStoredNSErrors.
public extension _BridgedStoredNSError {
/// Default implementation of ``init(_bridgedNSError)`` to provide
/// bridging from NSError.
public init?(_bridgedNSError error: NSError) {
if error.domain != Self._nsErrorDomain {
return nil
}
self.init(_nsError: error)
}
}
/// Implementation of CustomNSError for all _BridgedStoredNSErrors.
public extension _BridgedStoredNSError {
// FIXME: Would prefer to have a clear "extract an NSError
// directly" operation.
static var errorDomain: String { return _nsErrorDomain }
var errorCode: Int { return _nsError.code }
var errorUserInfo: [String : Any] {
var result: [String : Any] = [:]
for (key, value) in _nsError.userInfo {
guard let stringKey = key.base as? String else { continue }
result[stringKey] = value
}
return result
}
}
/// Implementation of Hashable for all _BridgedStoredNSErrors.
public extension _BridgedStoredNSError {
var hashValue: Int {
return _nsError.hashValue
}
}
/// Describes the code of an error.
public protocol _ErrorCodeProtocol : Equatable {
/// The corresponding error code.
associatedtype _ErrorType
// FIXME: We want _ErrorType to be _BridgedStoredNSError and have its
// Code match Self, but we cannot express those requirements yet.
}
extension _ErrorCodeProtocol where Self._ErrorType: _BridgedStoredNSError {
/// Allow one to match an error code against an arbitrary error.
public static func ~=(match: Self, error: Error) -> Bool {
guard let specificError = error as? Self._ErrorType else { return false }
// FIXME: Work around IRGen crash when we set Code == Code._ErrorType.Code.
let specificCode = specificError.code as! Self
return match == specificCode
}
}
extension _BridgedStoredNSError {
/// Retrieve the embedded NSError from a bridged, stored NSError.
public func _getEmbeddedNSError() -> AnyObject? {
return _nsError
}
public static func == (lhs: Self, rhs: Self) -> Bool {
return lhs._nsError.isEqual(rhs._nsError)
}
}
@available(*, unavailable, renamed: "CocoaError")
public typealias NSCocoaError = CocoaError
/// Describes errors within the Cocoa error domain.
public struct CocoaError : _BridgedStoredNSError {
public let _nsError: NSError
public init(_nsError error: NSError) {
precondition(error.domain == NSCocoaErrorDomain)
self._nsError = error
}
public static var _nsErrorDomain: String { return NSCocoaErrorDomain }
/// The error code itself.
public struct Code : RawRepresentable, _ErrorCodeProtocol {
public typealias _ErrorType = CocoaError
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
}
public extension CocoaError {
private var _nsUserInfo: [AnyHashable : Any] {
return (self as NSError).userInfo
}
/// The file path associated with the error, if any.
var filePath: String? {
return _nsUserInfo[NSFilePathErrorKey as NSString] as? String
}
/// The string encoding associated with this error, if any.
var stringEncoding: String.Encoding? {
return (_nsUserInfo[NSStringEncodingErrorKey as NSString] as? NSNumber)
.map { String.Encoding(rawValue: $0.uintValue) }
}
/// The underlying error behind this error, if any.
var underlying: Error? {
return _nsUserInfo[NSUnderlyingErrorKey as NSString] as? Error
}
/// The URL associated with this error, if any.
var url: URL? {
return _nsUserInfo[NSURLErrorKey as NSString] as? URL
}
}
extension CocoaError.Code {
public static var fileNoSuchFile: CocoaError.Code {
return CocoaError.Code(rawValue: 4)
}
public static var fileLocking: CocoaError.Code {
return CocoaError.Code(rawValue: 255)
}
public static var fileReadUnknown: CocoaError.Code {
return CocoaError.Code(rawValue: 256)
}
public static var fileReadNoPermission: CocoaError.Code {
return CocoaError.Code(rawValue: 257)
}
public static var fileReadInvalidFileName: CocoaError.Code {
return CocoaError.Code(rawValue: 258)
}
public static var fileReadCorruptFile: CocoaError.Code {
return CocoaError.Code(rawValue: 259)
}
public static var fileReadNoSuchFile: CocoaError.Code {
return CocoaError.Code(rawValue: 260)
}
public static var fileReadInapplicableStringEncoding: CocoaError.Code {
return CocoaError.Code(rawValue: 261)
}
public static var fileReadUnsupportedScheme: CocoaError.Code {
return CocoaError.Code(rawValue: 262)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var fileReadTooLarge: CocoaError.Code {
return CocoaError.Code(rawValue: 263)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var fileReadUnknownStringEncoding: CocoaError.Code {
return CocoaError.Code(rawValue: 264)
}
public static var fileWriteUnknown: CocoaError.Code {
return CocoaError.Code(rawValue: 512)
}
public static var fileWriteNoPermission: CocoaError.Code {
return CocoaError.Code(rawValue: 513)
}
public static var fileWriteInvalidFileName: CocoaError.Code {
return CocoaError.Code(rawValue: 514)
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0)
public static var fileWriteFileExists: CocoaError.Code {
return CocoaError.Code(rawValue: 516)
}
public static var fileWriteInapplicableStringEncoding: CocoaError.Code {
return CocoaError.Code(rawValue: 517)
}
public static var fileWriteUnsupportedScheme: CocoaError.Code {
return CocoaError.Code(rawValue: 518)
}
public static var fileWriteOutOfSpace: CocoaError.Code {
return CocoaError.Code(rawValue: 640)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var fileWriteVolumeReadOnly: CocoaError.Code {
return CocoaError.Code(rawValue: 642)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
public static var fileManagerUnmountUnknown: CocoaError.Code {
return CocoaError.Code(rawValue: 768)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
public static var fileManagerUnmountBusy: CocoaError.Code {
return CocoaError.Code(rawValue: 769)
}
public static var keyValueValidation: CocoaError.Code {
return CocoaError.Code(rawValue: 1024)
}
public static var formatting: CocoaError.Code {
return CocoaError.Code(rawValue: 2048)
}
public static var userCancelled: CocoaError.Code {
return CocoaError.Code(rawValue: 3072)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var featureUnsupported: CocoaError.Code {
return CocoaError.Code(rawValue: 3328)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableNotLoadable: CocoaError.Code {
return CocoaError.Code(rawValue: 3584)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableArchitectureMismatch: CocoaError.Code {
return CocoaError.Code(rawValue: 3585)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableRuntimeMismatch: CocoaError.Code {
return CocoaError.Code(rawValue: 3586)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableLoad: CocoaError.Code {
return CocoaError.Code(rawValue: 3587)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableLink: CocoaError.Code {
return CocoaError.Code(rawValue: 3588)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListReadCorrupt: CocoaError.Code {
return CocoaError.Code(rawValue: 3840)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListReadUnknownVersion: CocoaError.Code {
return CocoaError.Code(rawValue: 3841)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListReadStream: CocoaError.Code {
return CocoaError.Code(rawValue: 3842)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListWriteStream: CocoaError.Code {
return CocoaError.Code(rawValue: 3851)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var propertyListWriteInvalid: CocoaError.Code {
return CocoaError.Code(rawValue: 3852)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var xpcConnectionInterrupted: CocoaError.Code {
return CocoaError.Code(rawValue: 4097)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var xpcConnectionInvalid: CocoaError.Code {
return CocoaError.Code(rawValue: 4099)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var xpcConnectionReplyInvalid: CocoaError.Code {
return CocoaError.Code(rawValue: 4101)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public static var ubiquitousFileUnavailable: CocoaError.Code {
return CocoaError.Code(rawValue: 4353)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public static var ubiquitousFileNotUploadedDueToQuota: CocoaError.Code {
return CocoaError.Code(rawValue: 4354)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public static var ubiquitousFileUbiquityServerNotAvailable: CocoaError.Code {
return CocoaError.Code(rawValue: 4355)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityHandoffFailed: CocoaError.Code {
return CocoaError.Code(rawValue: 4608)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityConnectionUnavailable: CocoaError.Code {
return CocoaError.Code(rawValue: 4609)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityRemoteApplicationTimedOut: CocoaError.Code {
return CocoaError.Code(rawValue: 4610)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityHandoffUserInfoTooLarge: CocoaError.Code {
return CocoaError.Code(rawValue: 4611)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
public static var coderReadCorrupt: CocoaError.Code {
return CocoaError.Code(rawValue: 4864)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
public static var coderValueNotFound: CocoaError.Code {
return CocoaError.Code(rawValue: 4865)
}
}
extension CocoaError.Code {
@available(*, deprecated, renamed: "fileNoSuchFile")
public static var fileNoSuchFileError: CocoaError.Code {
return CocoaError.Code(rawValue: 4)
}
@available(*, deprecated, renamed: "fileLocking")
public static var fileLockingError: CocoaError.Code {
return CocoaError.Code(rawValue: 255)
}
@available(*, deprecated, renamed: "fileReadUnknown")
public static var fileReadUnknownError: CocoaError.Code {
return CocoaError.Code(rawValue: 256)
}
@available(*, deprecated, renamed: "fileReadNoPermission")
public static var fileReadNoPermissionError: CocoaError.Code {
return CocoaError.Code(rawValue: 257)
}
@available(*, deprecated, renamed: "fileReadInvalidFileName")
public static var fileReadInvalidFileNameError: CocoaError.Code {
return CocoaError.Code(rawValue: 258)
}
@available(*, deprecated, renamed: "fileReadCorruptFile")
public static var fileReadCorruptFileError: CocoaError.Code {
return CocoaError.Code(rawValue: 259)
}
@available(*, deprecated, renamed: "fileReadNoSuchFile")
public static var fileReadNoSuchFileError: CocoaError.Code {
return CocoaError.Code(rawValue: 260)
}
@available(*, deprecated, renamed: "fileReadInapplicableStringEncoding")
public static var fileReadInapplicableStringEncodingError: CocoaError.Code {
return CocoaError.Code(rawValue: 261)
}
@available(*, deprecated, renamed: "fileReadUnsupportedScheme")
public static var fileReadUnsupportedSchemeError: CocoaError.Code {
return CocoaError.Code(rawValue: 262)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "fileReadTooLarge")
public static var fileReadTooLargeError: CocoaError.Code {
return CocoaError.Code(rawValue: 263)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "fileReadUnknownStringEncoding")
public static var fileReadUnknownStringEncodingError: CocoaError.Code {
return CocoaError.Code(rawValue: 264)
}
@available(*, deprecated, renamed: "fileWriteUnknown")
public static var fileWriteUnknownError: CocoaError.Code {
return CocoaError.Code(rawValue: 512)
}
@available(*, deprecated, renamed: "fileWriteNoPermission")
public static var fileWriteNoPermissionError: CocoaError.Code {
return CocoaError.Code(rawValue: 513)
}
@available(*, deprecated, renamed: "fileWriteInvalidFileName")
public static var fileWriteInvalidFileNameError: CocoaError.Code {
return CocoaError.Code(rawValue: 514)
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0)
@available(*, deprecated, renamed: "fileWriteFileExists")
public static var fileWriteFileExistsError: CocoaError.Code {
return CocoaError.Code(rawValue: 516)
}
@available(*, deprecated, renamed: "fileWriteInapplicableStringEncoding")
public static var fileWriteInapplicableStringEncodingError: CocoaError.Code {
return CocoaError.Code(rawValue: 517)
}
@available(*, deprecated, renamed: "fileWriteUnsupportedScheme")
public static var fileWriteUnsupportedSchemeError: CocoaError.Code {
return CocoaError.Code(rawValue: 518)
}
@available(*, deprecated, renamed: "fileWriteOutOfSpace")
public static var fileWriteOutOfSpaceError: CocoaError.Code {
return CocoaError.Code(rawValue: 640)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "fileWriteVolumeReadOnly")
public static var fileWriteVolumeReadOnlyError: CocoaError.Code {
return CocoaError.Code(rawValue: 642)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
@available(*, deprecated, renamed: "fileManagerUnmountUnknown")
public static var fileManagerUnmountUnknownError: CocoaError.Code {
return CocoaError.Code(rawValue: 768)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
@available(*, deprecated, renamed: "fileManagerUnmountBusy")
public static var fileManagerUnmountBusyError: CocoaError.Code {
return CocoaError.Code(rawValue: 769)
}
@available(*, deprecated, renamed: "keyValueValidation")
public static var keyValueValidationError: CocoaError.Code {
return CocoaError.Code(rawValue: 1024)
}
@available(*, deprecated, renamed: "formatting")
public static var formattingError: CocoaError.Code {
return CocoaError.Code(rawValue: 2048)
}
@available(*, deprecated, renamed: "userCancelled")
public static var userCancelledError: CocoaError.Code {
return CocoaError.Code(rawValue: 3072)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
@available(*, deprecated, renamed: "featureUnsupported")
public static var featureUnsupportedError: CocoaError.Code {
return CocoaError.Code(rawValue: 3328)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableNotLoadable")
public static var executableNotLoadableError: CocoaError.Code {
return CocoaError.Code(rawValue: 3584)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableArchitectureMismatch")
public static var executableArchitectureMismatchError: CocoaError.Code {
return CocoaError.Code(rawValue: 3585)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableRuntimeMismatch")
public static var executableRuntimeMismatchError: CocoaError.Code {
return CocoaError.Code(rawValue: 3586)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableLoad")
public static var executableLoadError: CocoaError.Code {
return CocoaError.Code(rawValue: 3587)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableLink")
public static var executableLinkError: CocoaError.Code {
return CocoaError.Code(rawValue: 3588)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListReadCorrupt")
public static var propertyListReadCorruptError: CocoaError.Code {
return CocoaError.Code(rawValue: 3840)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListReadUnknownVersion")
public static var propertyListReadUnknownVersionError: CocoaError.Code {
return CocoaError.Code(rawValue: 3841)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListReadStream")
public static var propertyListReadStreamError: CocoaError.Code {
return CocoaError.Code(rawValue: 3842)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListWriteStream")
public static var propertyListWriteStreamError: CocoaError.Code {
return CocoaError.Code(rawValue: 3851)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "propertyListWriteInvalid")
public static var propertyListWriteInvalidError: CocoaError.Code {
return CocoaError.Code(rawValue: 3852)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
@available(*, deprecated, renamed: "ubiquitousFileUnavailable")
public static var ubiquitousFileUnavailableError: CocoaError.Code {
return CocoaError.Code(rawValue: 4353)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
@available(*, deprecated, renamed: "ubiquitousFileNotUploadedDueToQuota")
public static var ubiquitousFileNotUploadedDueToQuotaError: CocoaError.Code {
return CocoaError.Code(rawValue: 4354)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityHandoffFailed")
public static var userActivityHandoffFailedError: CocoaError.Code {
return CocoaError.Code(rawValue: 4608)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityConnectionUnavailable")
public static var userActivityConnectionUnavailableError: CocoaError.Code {
return CocoaError.Code(rawValue: 4609)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityRemoteApplicationTimedOut")
public static var userActivityRemoteApplicationTimedOutError: CocoaError.Code {
return CocoaError.Code(rawValue: 4610)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityHandoffUserInfoTooLarge")
public static var userActivityHandoffUserInfoTooLargeError: CocoaError.Code {
return CocoaError.Code(rawValue: 4611)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
@available(*, deprecated, renamed: "coderReadCorrupt")
public static var coderReadCorruptError: CocoaError.Code {
return CocoaError.Code(rawValue: 4864)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
@available(*, deprecated, renamed: "coderValueNotFound")
public static var coderValueNotFoundError: CocoaError.Code {
return CocoaError.Code(rawValue: 4865)
}
}
extension CocoaError {
public static var fileNoSuchFile: CocoaError.Code {
return CocoaError.Code(rawValue: 4)
}
public static var fileLocking: CocoaError.Code {
return CocoaError.Code(rawValue: 255)
}
public static var fileReadUnknown: CocoaError.Code {
return CocoaError.Code(rawValue: 256)
}
public static var fileReadNoPermission: CocoaError.Code {
return CocoaError.Code(rawValue: 257)
}
public static var fileReadInvalidFileName: CocoaError.Code {
return CocoaError.Code(rawValue: 258)
}
public static var fileReadCorruptFile: CocoaError.Code {
return CocoaError.Code(rawValue: 259)
}
public static var fileReadNoSuchFile: CocoaError.Code {
return CocoaError.Code(rawValue: 260)
}
public static var fileReadInapplicableStringEncoding: CocoaError.Code {
return CocoaError.Code(rawValue: 261)
}
public static var fileReadUnsupportedScheme: CocoaError.Code {
return CocoaError.Code(rawValue: 262)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var fileReadTooLarge: CocoaError.Code {
return CocoaError.Code(rawValue: 263)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var fileReadUnknownStringEncoding: CocoaError.Code {
return CocoaError.Code(rawValue: 264)
}
public static var fileWriteUnknown: CocoaError.Code {
return CocoaError.Code(rawValue: 512)
}
public static var fileWriteNoPermission: CocoaError.Code {
return CocoaError.Code(rawValue: 513)
}
public static var fileWriteInvalidFileName: CocoaError.Code {
return CocoaError.Code(rawValue: 514)
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0)
public static var fileWriteFileExists: CocoaError.Code {
return CocoaError.Code(rawValue: 516)
}
public static var fileWriteInapplicableStringEncoding: CocoaError.Code {
return CocoaError.Code(rawValue: 517)
}
public static var fileWriteUnsupportedScheme: CocoaError.Code {
return CocoaError.Code(rawValue: 518)
}
public static var fileWriteOutOfSpace: CocoaError.Code {
return CocoaError.Code(rawValue: 640)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var fileWriteVolumeReadOnly: CocoaError.Code {
return CocoaError.Code(rawValue: 642)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
public static var fileManagerUnmountUnknown: CocoaError.Code {
return CocoaError.Code(rawValue: 768)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
public static var fileManagerUnmountBusy: CocoaError.Code {
return CocoaError.Code(rawValue: 769)
}
public static var keyValueValidation: CocoaError.Code {
return CocoaError.Code(rawValue: 1024)
}
public static var formatting: CocoaError.Code {
return CocoaError.Code(rawValue: 2048)
}
public static var userCancelled: CocoaError.Code {
return CocoaError.Code(rawValue: 3072)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var featureUnsupported: CocoaError.Code {
return CocoaError.Code(rawValue: 3328)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableNotLoadable: CocoaError.Code {
return CocoaError.Code(rawValue: 3584)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableArchitectureMismatch: CocoaError.Code {
return CocoaError.Code(rawValue: 3585)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableRuntimeMismatch: CocoaError.Code {
return CocoaError.Code(rawValue: 3586)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableLoad: CocoaError.Code {
return CocoaError.Code(rawValue: 3587)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public static var executableLink: CocoaError.Code {
return CocoaError.Code(rawValue: 3588)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListReadCorrupt: CocoaError.Code {
return CocoaError.Code(rawValue: 3840)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListReadUnknownVersion: CocoaError.Code {
return CocoaError.Code(rawValue: 3841)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListReadStream: CocoaError.Code {
return CocoaError.Code(rawValue: 3842)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public static var propertyListWriteStream: CocoaError.Code {
return CocoaError.Code(rawValue: 3851)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var propertyListWriteInvalid: CocoaError.Code {
return CocoaError.Code(rawValue: 3852)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var xpcConnectionInterrupted: CocoaError.Code {
return CocoaError.Code(rawValue: 4097)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var xpcConnectionInvalid: CocoaError.Code {
return CocoaError.Code(rawValue: 4099)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public static var xpcConnectionReplyInvalid: CocoaError.Code {
return CocoaError.Code(rawValue: 4101)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public static var ubiquitousFileUnavailable: CocoaError.Code {
return CocoaError.Code(rawValue: 4353)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public static var ubiquitousFileNotUploadedDueToQuota: CocoaError.Code {
return CocoaError.Code(rawValue: 4354)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public static var ubiquitousFileUbiquityServerNotAvailable: CocoaError.Code {
return CocoaError.Code(rawValue: 4355)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityHandoffFailed: CocoaError.Code {
return CocoaError.Code(rawValue: 4608)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityConnectionUnavailable: CocoaError.Code {
return CocoaError.Code(rawValue: 4609)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityRemoteApplicationTimedOut: CocoaError.Code {
return CocoaError.Code(rawValue: 4610)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var userActivityHandoffUserInfoTooLarge: CocoaError.Code {
return CocoaError.Code(rawValue: 4611)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
public static var coderReadCorrupt: CocoaError.Code {
return CocoaError.Code(rawValue: 4864)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
public static var coderValueNotFound: CocoaError.Code {
return CocoaError.Code(rawValue: 4865)
}
}
extension CocoaError {
@available(*, deprecated, renamed: "fileNoSuchFile")
public static var fileNoSuchFileError: CocoaError.Code {
return CocoaError.Code(rawValue: 4)
}
@available(*, deprecated, renamed: "fileLocking")
public static var fileLockingError: CocoaError.Code {
return CocoaError.Code(rawValue: 255)
}
@available(*, deprecated, renamed: "fileReadUnknown")
public static var fileReadUnknownError: CocoaError.Code {
return CocoaError.Code(rawValue: 256)
}
@available(*, deprecated, renamed: "fileReadNoPermission")
public static var fileReadNoPermissionError: CocoaError.Code {
return CocoaError.Code(rawValue: 257)
}
@available(*, deprecated, renamed: "fileReadInvalidFileName")
public static var fileReadInvalidFileNameError: CocoaError.Code {
return CocoaError.Code(rawValue: 258)
}
@available(*, deprecated, renamed: "fileReadCorruptFile")
public static var fileReadCorruptFileError: CocoaError.Code {
return CocoaError.Code(rawValue: 259)
}
@available(*, deprecated, renamed: "fileReadNoSuchFile")
public static var fileReadNoSuchFileError: CocoaError.Code {
return CocoaError.Code(rawValue: 260)
}
@available(*, deprecated, renamed: "fileReadInapplicableStringEncoding")
public static var fileReadInapplicableStringEncodingError: CocoaError.Code {
return CocoaError.Code(rawValue: 261)
}
@available(*, deprecated, renamed: "fileReadUnsupportedScheme")
public static var fileReadUnsupportedSchemeError: CocoaError.Code {
return CocoaError.Code(rawValue: 262)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "fileReadTooLarge")
public static var fileReadTooLargeError: CocoaError.Code {
return CocoaError.Code(rawValue: 263)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "fileReadUnknownStringEncoding")
public static var fileReadUnknownStringEncodingError: CocoaError.Code {
return CocoaError.Code(rawValue: 264)
}
@available(*, deprecated, renamed: "fileWriteUnknown")
public static var fileWriteUnknownError: CocoaError.Code {
return CocoaError.Code(rawValue: 512)
}
@available(*, deprecated, renamed: "fileWriteNoPermission")
public static var fileWriteNoPermissionError: CocoaError.Code {
return CocoaError.Code(rawValue: 513)
}
@available(*, deprecated, renamed: "fileWriteInvalidFileName")
public static var fileWriteInvalidFileNameError: CocoaError.Code {
return CocoaError.Code(rawValue: 514)
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0)
@available(*, deprecated, renamed: "fileWriteFileExists")
public static var fileWriteFileExistsError: CocoaError.Code {
return CocoaError.Code(rawValue: 516)
}
@available(*, deprecated, renamed: "fileWriteInapplicableStringEncoding")
public static var fileWriteInapplicableStringEncodingError: CocoaError.Code {
return CocoaError.Code(rawValue: 517)
}
@available(*, deprecated, renamed: "fileWriteUnsupportedScheme")
public static var fileWriteUnsupportedSchemeError: CocoaError.Code {
return CocoaError.Code(rawValue: 518)
}
@available(*, deprecated, renamed: "fileWriteOutOfSpace")
public static var fileWriteOutOfSpaceError: CocoaError.Code {
return CocoaError.Code(rawValue: 640)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "fileWriteVolumeReadOnly")
public static var fileWriteVolumeReadOnlyError: CocoaError.Code {
return CocoaError.Code(rawValue: 642)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
@available(*, deprecated, renamed: "fileManagerUnmountUnknown")
public static var fileManagerUnmountUnknownError: CocoaError.Code {
return CocoaError.Code(rawValue: 768)
}
@available(OSX, introduced: 10.11) @available(iOS, unavailable)
@available(*, deprecated, renamed: "fileManagerUnmountBusy")
public static var fileManagerUnmountBusyError: CocoaError.Code {
return CocoaError.Code(rawValue: 769)
}
@available(*, deprecated, renamed: "keyValueValidation")
public static var keyValueValidationError: CocoaError.Code {
return CocoaError.Code(rawValue: 1024)
}
@available(*, deprecated, renamed: "formatting")
public static var formattingError: CocoaError.Code {
return CocoaError.Code(rawValue: 2048)
}
@available(*, deprecated, renamed: "userCancelled")
public static var userCancelledError: CocoaError.Code {
return CocoaError.Code(rawValue: 3072)
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
@available(*, deprecated, renamed: "featureUnsupported")
public static var featureUnsupportedError: CocoaError.Code {
return CocoaError.Code(rawValue: 3328)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableNotLoadable")
public static var executableNotLoadableError: CocoaError.Code {
return CocoaError.Code(rawValue: 3584)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableArchitectureMismatch")
public static var executableArchitectureMismatchError: CocoaError.Code {
return CocoaError.Code(rawValue: 3585)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableRuntimeMismatch")
public static var executableRuntimeMismatchError: CocoaError.Code {
return CocoaError.Code(rawValue: 3586)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableLoad")
public static var executableLoadError: CocoaError.Code {
return CocoaError.Code(rawValue: 3587)
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
@available(*, deprecated, renamed: "executableLink")
public static var executableLinkError: CocoaError.Code {
return CocoaError.Code(rawValue: 3588)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListReadCorrupt")
public static var propertyListReadCorruptError: CocoaError.Code {
return CocoaError.Code(rawValue: 3840)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListReadUnknownVersion")
public static var propertyListReadUnknownVersionError: CocoaError.Code {
return CocoaError.Code(rawValue: 3841)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListReadStream")
public static var propertyListReadStreamError: CocoaError.Code {
return CocoaError.Code(rawValue: 3842)
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
@available(*, deprecated, renamed: "propertyListWriteStream")
public static var propertyListWriteStreamError: CocoaError.Code {
return CocoaError.Code(rawValue: 3851)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "propertyListWriteInvalid")
public static var propertyListWriteInvalidError: CocoaError.Code {
return CocoaError.Code(rawValue: 3852)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
@available(*, deprecated, renamed: "ubiquitousFileUnavailable")
public static var ubiquitousFileUnavailableError: CocoaError.Code {
return CocoaError.Code(rawValue: 4353)
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
@available(*, deprecated, renamed: "ubiquitousFileNotUploadedDueToQuota")
public static var ubiquitousFileNotUploadedDueToQuotaError: CocoaError.Code {
return CocoaError.Code(rawValue: 4354)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityHandoffFailed")
public static var userActivityHandoffFailedError: CocoaError.Code {
return CocoaError.Code(rawValue: 4608)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityConnectionUnavailable")
public static var userActivityConnectionUnavailableError: CocoaError.Code {
return CocoaError.Code(rawValue: 4609)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityRemoteApplicationTimedOut")
public static var userActivityRemoteApplicationTimedOutError: CocoaError.Code {
return CocoaError.Code(rawValue: 4610)
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
@available(*, deprecated, renamed: "userActivityHandoffUserInfoTooLarge")
public static var userActivityHandoffUserInfoTooLargeError: CocoaError.Code {
return CocoaError.Code(rawValue: 4611)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
@available(*, deprecated, renamed: "coderReadCorrupt")
public static var coderReadCorruptError: CocoaError.Code {
return CocoaError.Code(rawValue: 4864)
}
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
@available(*, deprecated, renamed: "coderValueNotFound")
public static var coderValueNotFoundError: CocoaError.Code {
return CocoaError.Code(rawValue: 4865)
}
}
extension CocoaError {
@available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0)
public var isCoderError: Bool {
return code.rawValue >= 4864 && code.rawValue <= 4991
}
@available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0)
public var isExecutableError: Bool {
return code.rawValue >= 3584 && code.rawValue <= 3839
}
public var isFileError: Bool {
return code.rawValue >= 0 && code.rawValue <= 1023
}
public var isFormattingError: Bool {
return code.rawValue >= 2048 && code.rawValue <= 2559
}
@available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0)
public var isPropertyListError: Bool {
return code.rawValue >= 3840 && code.rawValue <= 4095
}
@available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0)
public var isUbiquitousFileError: Bool {
return code.rawValue >= 4352 && code.rawValue <= 4607
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public var isUserActivityError: Bool {
return code.rawValue >= 4608 && code.rawValue <= 4863
}
public var isValidationError: Bool {
return code.rawValue >= 1024 && code.rawValue <= 2047
}
@available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0)
public var isXPCConnectionError: Bool {
return code.rawValue >= 4096 && code.rawValue <= 4224
}
}
extension CocoaError.Code {
@available(*, unavailable, renamed: "fileNoSuchFile")
public static var FileNoSuchFileError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileLocking")
public static var FileLockingError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadUnknown")
public static var FileReadUnknownError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadNoPermission")
public static var FileReadNoPermissionError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadInvalidFileName")
public static var FileReadInvalidFileNameError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadCorruptFile")
public static var FileReadCorruptFileError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadNoSuchFile")
public static var FileReadNoSuchFileError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadInapplicableStringEncoding")
public static var FileReadInapplicableStringEncodingError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadUnsupportedScheme")
public static var FileReadUnsupportedSchemeError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadTooLarge")
public static var FileReadTooLargeError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileReadUnknownStringEncoding")
public static var FileReadUnknownStringEncodingError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteUnknown")
public static var FileWriteUnknownError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteNoPermission")
public static var FileWriteNoPermissionError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteInvalidFileName")
public static var FileWriteInvalidFileNameError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteFileExists")
public static var FileWriteFileExistsError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteInapplicableStringEncoding")
public static var FileWriteInapplicableStringEncodingError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteUnsupportedScheme")
public static var FileWriteUnsupportedSchemeError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteOutOfSpace")
public static var FileWriteOutOfSpaceError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileWriteVolumeReadOnly")
public static var FileWriteVolumeReadOnlyError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileManagerUnmountUnknown")
public static var FileManagerUnmountUnknownError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileManagerUnmountBusy")
public static var FileManagerUnmountBusyError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "keyValueValidation")
public static var KeyValueValidationError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "formatting")
public static var FormattingError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userCancelled")
public static var UserCancelledError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "featureUnsupported")
public static var FeatureUnsupportedError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "executableNotLoadable")
public static var ExecutableNotLoadableError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "executableArchitectureMismatch")
public static var ExecutableArchitectureMismatchError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "executableRuntimeMismatch")
public static var ExecutableRuntimeMismatchError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "executableLoad")
public static var ExecutableLoadError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "executableLink")
public static var ExecutableLinkError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "propertyListReadCorrupt")
public static var PropertyListReadCorruptError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "propertyListReadUnknownVersion")
public static var PropertyListReadUnknownVersionError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "propertyListReadStream")
public static var PropertyListReadStreamError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "propertyListWriteStream")
public static var PropertyListWriteStreamError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "propertyListWriteInvalid")
public static var PropertyListWriteInvalidError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "xpcConnectionInterrupted")
public static var XPCConnectionInterrupted: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "xpcConnectionInvalid")
public static var XPCConnectionInvalid: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "xpcConnectionReplyInvalid")
public static var XPCConnectionReplyInvalid: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "ubiquitousFileUnavailable")
public static var UbiquitousFileUnavailableError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "ubiquitousFileNotUploadedDueToQuota")
public static var UbiquitousFileNotUploadedDueToQuotaError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "ubiquitousFileUbiquityServerNotAvailable")
public static var UbiquitousFileUbiquityServerNotAvailable: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userActivityHandoffFailed")
public static var UserActivityHandoffFailedError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userActivityConnectionUnavailable")
public static var UserActivityConnectionUnavailableError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userActivityRemoteApplicationTimedOut")
public static var UserActivityRemoteApplicationTimedOutError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userActivityHandoffUserInfoTooLarge")
public static var UserActivityHandoffUserInfoTooLargeError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "coderReadCorrupt")
public static var CoderReadCorruptError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "coderValueNotFound")
public static var CoderValueNotFoundError: CocoaError.Code {
fatalError("unavailable accessor can't be called")
}
}
/// Describes errors in the URL error domain.
public struct URLError : _BridgedStoredNSError {
public let _nsError: NSError
public init(_nsError error: NSError) {
precondition(error.domain == NSURLErrorDomain)
self._nsError = error
}
public static var _nsErrorDomain: String { return NSURLErrorDomain }
@objc public enum Code : Int, _ErrorCodeProtocol {
public typealias _ErrorType = URLError
case unknown = -1
case cancelled = -999
case badURL = -1000
case timedOut = -1001
case unsupportedURL = -1002
case cannotFindHost = -1003
case cannotConnectToHost = -1004
case networkConnectionLost = -1005
case dnsLookupFailed = -1006
case httpTooManyRedirects = -1007
case resourceUnavailable = -1008
case notConnectedToInternet = -1009
case redirectToNonExistentLocation = -1010
case badServerResponse = -1011
case userCancelledAuthentication = -1012
case userAuthenticationRequired = -1013
case zeroByteResource = -1014
case cannotDecodeRawData = -1015
case cannotDecodeContentData = -1016
case cannotParseResponse = -1017
case fileDoesNotExist = -1100
case fileIsDirectory = -1101
case noPermissionsToReadFile = -1102
case secureConnectionFailed = -1200
case serverCertificateHasBadDate = -1201
case serverCertificateUntrusted = -1202
case serverCertificateHasUnknownRoot = -1203
case serverCertificateNotYetValid = -1204
case clientCertificateRejected = -1205
case clientCertificateRequired = -1206
case cannotLoadFromNetwork = -2000
case cannotCreateFile = -3000
case cannotOpenFile = -3001
case cannotCloseFile = -3002
case cannotWriteToFile = -3003
case cannotRemoveFile = -3004
case cannotMoveFile = -3005
case downloadDecodingFailedMidStream = -3006
case downloadDecodingFailedToComplete = -3007
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
case internationalRoamingOff = -1018
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
case callIsActive = -1019
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
case dataNotAllowed = -1020
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
case requestBodyStreamExhausted = -1021
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
static var backgroundSessionRequiresSharedContainer: Code {
return Code(rawValue: -995)!
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
static var backgroundSessionInUseByAnotherProcess: Code {
return Code(rawValue: -996)!
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
static var backgroundSessionWasDisconnected: Code {
return Code(rawValue: -997)!
}
}
}
public extension URLError {
private var _nsUserInfo: [AnyHashable : Any] {
return (self as NSError).userInfo
}
/// The URL which caused a load to fail.
public var failingURL: URL? {
return _nsUserInfo[NSURLErrorFailingURLErrorKey as NSString] as? URL
}
/// The string for the URL which caused a load to fail.
public var failureURLString: String? {
return _nsUserInfo[NSURLErrorFailingURLStringErrorKey as NSString] as? String
}
/// The state of a failed SSL handshake.
public var failureURLPeerTrust: SecTrust? {
if let secTrust = _nsUserInfo[NSURLErrorFailingURLPeerTrustErrorKey as NSString] {
return (secTrust as! SecTrust)
}
return nil
}
}
public extension URLError {
public static var unknown: URLError.Code {
return .unknown
}
public static var cancelled: URLError.Code {
return .cancelled
}
public static var badURL: URLError.Code {
return .badURL
}
public static var timedOut: URLError.Code {
return .timedOut
}
public static var unsupportedURL: URLError.Code {
return .unsupportedURL
}
public static var cannotFindHost: URLError.Code {
return .cannotFindHost
}
public static var cannotConnectToHost: URLError.Code {
return .cannotConnectToHost
}
public static var networkConnectionLost: URLError.Code {
return .networkConnectionLost
}
public static var dnsLookupFailed: URLError.Code {
return .dnsLookupFailed
}
public static var httpTooManyRedirects: URLError.Code {
return .httpTooManyRedirects
}
public static var resourceUnavailable: URLError.Code {
return .resourceUnavailable
}
public static var notConnectedToInternet: URLError.Code {
return .notConnectedToInternet
}
public static var redirectToNonExistentLocation: URLError.Code {
return .redirectToNonExistentLocation
}
public static var badServerResponse: URLError.Code {
return .badServerResponse
}
public static var userCancelledAuthentication: URLError.Code {
return .userCancelledAuthentication
}
public static var userAuthenticationRequired: URLError.Code {
return .userAuthenticationRequired
}
public static var zeroByteResource: URLError.Code {
return .zeroByteResource
}
public static var cannotDecodeRawData: URLError.Code {
return .cannotDecodeRawData
}
public static var cannotDecodeContentData: URLError.Code {
return .cannotDecodeContentData
}
public static var cannotParseResponse: URLError.Code {
return .cannotParseResponse
}
public static var fileDoesNotExist: URLError.Code {
return .fileDoesNotExist
}
public static var fileIsDirectory: URLError.Code {
return .fileIsDirectory
}
public static var noPermissionsToReadFile: URLError.Code {
return .noPermissionsToReadFile
}
public static var secureConnectionFailed: URLError.Code {
return .secureConnectionFailed
}
public static var serverCertificateHasBadDate: URLError.Code {
return .serverCertificateHasBadDate
}
public static var serverCertificateUntrusted: URLError.Code {
return .serverCertificateUntrusted
}
public static var serverCertificateHasUnknownRoot: URLError.Code {
return .serverCertificateHasUnknownRoot
}
public static var serverCertificateNotYetValid: URLError.Code {
return .serverCertificateNotYetValid
}
public static var clientCertificateRejected: URLError.Code {
return .clientCertificateRejected
}
public static var clientCertificateRequired: URLError.Code {
return .clientCertificateRequired
}
public static var cannotLoadFromNetwork: URLError.Code {
return .cannotLoadFromNetwork
}
public static var cannotCreateFile: URLError.Code {
return .cannotCreateFile
}
public static var cannotOpenFile: URLError.Code {
return .cannotOpenFile
}
public static var cannotCloseFile: URLError.Code {
return .cannotCloseFile
}
public static var cannotWriteToFile: URLError.Code {
return .cannotWriteToFile
}
public static var cannotRemoveFile: URLError.Code {
return .cannotRemoveFile
}
public static var cannotMoveFile: URLError.Code {
return .cannotMoveFile
}
public static var downloadDecodingFailedMidStream: URLError.Code {
return .downloadDecodingFailedMidStream
}
public static var downloadDecodingFailedToComplete: URLError.Code {
return .downloadDecodingFailedToComplete
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
public static var internationalRoamingOff: URLError.Code {
return .internationalRoamingOff
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
public static var callIsActive: URLError.Code {
return .callIsActive
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
public static var dataNotAllowed: URLError.Code {
return .dataNotAllowed
}
@available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0)
public static var requestBodyStreamExhausted: URLError.Code {
return .requestBodyStreamExhausted
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var backgroundSessionRequiresSharedContainer: Code {
return .backgroundSessionRequiresSharedContainer
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var backgroundSessionInUseByAnotherProcess: Code {
return .backgroundSessionInUseByAnotherProcess
}
@available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0)
public static var backgroundSessionWasDisconnected: Code {
return .backgroundSessionWasDisconnected
}
}
extension URLError {
@available(*, unavailable, renamed: "unknown")
public static var Unknown: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cancelled")
public static var Cancelled: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "badURL")
public static var BadURL: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "timedOut")
public static var TimedOut: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "unsupportedURL")
public static var UnsupportedURL: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotFindHost")
public static var CannotFindHost: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotConnectToHost")
public static var CannotConnectToHost: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "networkConnectionLost")
public static var NetworkConnectionLost: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "dnsLookupFailed")
public static var DNSLookupFailed: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "httpTooManyRedirects")
public static var HTTPTooManyRedirects: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "resourceUnavailable")
public static var ResourceUnavailable: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "notConnectedToInternet")
public static var NotConnectedToInternet: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "redirectToNonExistentLocation")
public static var RedirectToNonExistentLocation: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "badServerResponse")
public static var BadServerResponse: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userCancelledAuthentication")
public static var UserCancelledAuthentication: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "userAuthenticationRequired")
public static var UserAuthenticationRequired: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "zeroByteResource")
public static var ZeroByteResource: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotDecodeRawData")
public static var CannotDecodeRawData: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotDecodeContentData")
public static var CannotDecodeContentData: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotParseResponse")
public static var CannotParseResponse: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileDoesNotExist")
public static var FileDoesNotExist: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "fileIsDirectory")
public static var FileIsDirectory: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "noPermissionsToReadFile")
public static var NoPermissionsToReadFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "secureConnectionFailed")
public static var SecureConnectionFailed: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "serverCertificateHasBadDate")
public static var ServerCertificateHasBadDate: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "serverCertificateUntrusted")
public static var ServerCertificateUntrusted: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "serverCertificateHasUnknownRoot")
public static var ServerCertificateHasUnknownRoot: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "serverCertificateNotYetValid")
public static var ServerCertificateNotYetValid: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "clientCertificateRejected")
public static var ClientCertificateRejected: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "clientCertificateRequired")
public static var ClientCertificateRequired: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotLoadFromNetwork")
public static var CannotLoadFromNetwork: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotCreateFile")
public static var CannotCreateFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotOpenFile")
public static var CannotOpenFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotCloseFile")
public static var CannotCloseFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotWriteToFile")
public static var CannotWriteToFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotRemoveFile")
public static var CannotRemoveFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "cannotMoveFile")
public static var CannotMoveFile: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "downloadDecodingFailedMidStream")
public static var DownloadDecodingFailedMidStream: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "downloadDecodingFailedToComplete")
public static var DownloadDecodingFailedToComplete: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "internationalRoamingOff")
public static var InternationalRoamingOff: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "callIsActive")
public static var CallIsActive: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "dataNotAllowed")
public static var DataNotAllowed: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "requestBodyStreamExhausted")
public static var RequestBodyStreamExhausted: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "backgroundSessionRequiresSharedContainer")
public static var BackgroundSessionRequiresSharedContainer: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "backgroundSessionInUseByAnotherProcess")
public static var BackgroundSessionInUseByAnotherProcess: URLError.Code {
fatalError("unavailable accessor can't be called")
}
@available(*, unavailable, renamed: "backgroundSessionWasDisconnected")
public static var BackgroundSessionWasDisconnected: URLError.Code {
fatalError("unavailable accessor can't be called")
}
}
/// Describes an error in the POSIX error domain.
public struct POSIXError : _BridgedStoredNSError {
public let _nsError: NSError
public init(_nsError error: NSError) {
precondition(error.domain == NSPOSIXErrorDomain)
self._nsError = error
}
public static var _nsErrorDomain: String { return NSPOSIXErrorDomain }
public typealias Code = POSIXErrorCode
}
extension POSIXErrorCode : _ErrorCodeProtocol {
public typealias _ErrorType = POSIXError
}
extension POSIXError {
public static var EPERM: POSIXErrorCode {
return .EPERM
}
/// No such file or directory.
public static var ENOENT: POSIXErrorCode {
return .ENOENT
}
/// No such process.
public static var ESRCH: POSIXErrorCode {
return .ESRCH
}
/// Interrupted system call.
public static var EINTR: POSIXErrorCode {
return .EINTR
}
/// Input/output error.
public static var EIO: POSIXErrorCode {
return .EIO
}
/// Device not configured.
public static var ENXIO: POSIXErrorCode {
return .ENXIO
}
/// Argument list too long.
public static var E2BIG: POSIXErrorCode {
return .E2BIG
}
/// Exec format error.
public static var ENOEXEC: POSIXErrorCode {
return .ENOEXEC
}
/// Bad file descriptor.
public static var EBADF: POSIXErrorCode {
return .EBADF
}
/// No child processes.
public static var ECHILD: POSIXErrorCode {
return .ECHILD
}
/// Resource deadlock avoided.
public static var EDEADLK: POSIXErrorCode {
return .EDEADLK
}
/// Cannot allocate memory.
public static var ENOMEM: POSIXErrorCode {
return .ENOMEM
}
/// Permission denied.
public static var EACCES: POSIXErrorCode {
return .EACCES
}
/// Bad address.
public static var EFAULT: POSIXErrorCode {
return .EFAULT
}
/// Block device required.
public static var ENOTBLK: POSIXErrorCode {
return .ENOTBLK
}
/// Device / Resource busy.
public static var EBUSY: POSIXErrorCode {
return .EBUSY
}
/// File exists.
public static var EEXIST: POSIXErrorCode {
return .EEXIST
}
/// Cross-device link.
public static var EXDEV: POSIXErrorCode {
return .EXDEV
}
/// Operation not supported by device.
public static var ENODEV: POSIXErrorCode {
return .ENODEV
}
/// Not a directory.
public static var ENOTDIR: POSIXErrorCode {
return .ENOTDIR
}
/// Is a directory.
public static var EISDIR: POSIXErrorCode {
return .EISDIR
}
/// Invalid argument.
public static var EINVAL: POSIXErrorCode {
return .EINVAL
}
/// Too many open files in system.
public static var ENFILE: POSIXErrorCode {
return .ENFILE
}
/// Too many open files.
public static var EMFILE: POSIXErrorCode {
return .EMFILE
}
/// Inappropriate ioctl for device.
public static var ENOTTY: POSIXErrorCode {
return .ENOTTY
}
/// Text file busy.
public static var ETXTBSY: POSIXErrorCode {
return .ETXTBSY
}
/// File too large.
public static var EFBIG: POSIXErrorCode {
return .EFBIG
}
/// No space left on device.
public static var ENOSPC: POSIXErrorCode {
return .ENOSPC
}
/// Illegal seek.
public static var ESPIPE: POSIXErrorCode {
return .ESPIPE
}
/// Read-only file system.
public static var EROFS: POSIXErrorCode {
return .EROFS
}
/// Too many links.
public static var EMLINK: POSIXErrorCode {
return .EMLINK
}
/// Broken pipe.
public static var EPIPE: POSIXErrorCode {
return .EPIPE
}
/// math software.
/// Numerical argument out of domain.
public static var EDOM: POSIXErrorCode {
return .EDOM
}
/// Result too large.
public static var ERANGE: POSIXErrorCode {
return .ERANGE
}
/// non-blocking and interrupt i/o.
/// Resource temporarily unavailable.
public static var EAGAIN: POSIXErrorCode {
return .EAGAIN
}
/// Operation would block.
public static var EWOULDBLOCK: POSIXErrorCode {
return .EWOULDBLOCK
}
/// Operation now in progress.
public static var EINPROGRESS: POSIXErrorCode {
return .EINPROGRESS
}
/// Operation already in progress.
public static var EALREADY: POSIXErrorCode {
return .EALREADY
}
/// ipc/network software -- argument errors.
/// Socket operation on non-socket.
public static var ENOTSOCK: POSIXErrorCode {
return .ENOTSOCK
}
/// Destination address required.
public static var EDESTADDRREQ: POSIXErrorCode {
return .EDESTADDRREQ
}
/// Message too long.
public static var EMSGSIZE: POSIXErrorCode {
return .EMSGSIZE
}
/// Protocol wrong type for socket.
public static var EPROTOTYPE: POSIXErrorCode {
return .EPROTOTYPE
}
/// Protocol not available.
public static var ENOPROTOOPT: POSIXErrorCode {
return .ENOPROTOOPT
}
/// Protocol not supported.
public static var EPROTONOSUPPORT: POSIXErrorCode {
return .EPROTONOSUPPORT
}
/// Socket type not supported.
public static var ESOCKTNOSUPPORT: POSIXErrorCode {
return .ESOCKTNOSUPPORT
}
/// Operation not supported.
public static var ENOTSUP: POSIXErrorCode {
return .ENOTSUP
}
/// Protocol family not supported.
public static var EPFNOSUPPORT: POSIXErrorCode {
return .EPFNOSUPPORT
}
/// Address family not supported by protocol family.
public static var EAFNOSUPPORT: POSIXErrorCode {
return .EAFNOSUPPORT
}
/// Address already in use.
public static var EADDRINUSE: POSIXErrorCode {
return .EADDRINUSE
}
/// Can't assign requested address.
public static var EADDRNOTAVAIL: POSIXErrorCode {
return .EADDRNOTAVAIL
}
/// ipc/network software -- operational errors
/// Network is down.
public static var ENETDOWN: POSIXErrorCode {
return .ENETDOWN
}
/// Network is unreachable.
public static var ENETUNREACH: POSIXErrorCode {
return .ENETUNREACH
}
/// Network dropped connection on reset.
public static var ENETRESET: POSIXErrorCode {
return .ENETRESET
}
/// Software caused connection abort.
public static var ECONNABORTED: POSIXErrorCode {
return .ECONNABORTED
}
/// Connection reset by peer.
public static var ECONNRESET: POSIXErrorCode {
return .ECONNRESET
}
/// No buffer space available.
public static var ENOBUFS: POSIXErrorCode {
return .ENOBUFS
}
/// Socket is already connected.
public static var EISCONN: POSIXErrorCode {
return .EISCONN
}
/// Socket is not connected.
public static var ENOTCONN: POSIXErrorCode {
return .ENOTCONN
}
/// Can't send after socket shutdown.
public static var ESHUTDOWN: POSIXErrorCode {
return .ESHUTDOWN
}
/// Too many references: can't splice.
public static var ETOOMANYREFS: POSIXErrorCode {
return .ETOOMANYREFS
}
/// Operation timed out.
public static var ETIMEDOUT: POSIXErrorCode {
return .ETIMEDOUT
}
/// Connection refused.
public static var ECONNREFUSED: POSIXErrorCode {
return .ECONNREFUSED
}
/// Too many levels of symbolic links.
public static var ELOOP: POSIXErrorCode {
return .ELOOP
}
/// File name too long.
public static var ENAMETOOLONG: POSIXErrorCode {
return .ENAMETOOLONG
}
/// Host is down.
public static var EHOSTDOWN: POSIXErrorCode {
return .EHOSTDOWN
}
/// No route to host.
public static var EHOSTUNREACH: POSIXErrorCode {
return .EHOSTUNREACH
}
/// Directory not empty.
public static var ENOTEMPTY: POSIXErrorCode {
return .ENOTEMPTY
}
/// quotas & mush.
/// Too many processes.
public static var EPROCLIM: POSIXErrorCode {
return .EPROCLIM
}
/// Too many users.
public static var EUSERS: POSIXErrorCode {
return .EUSERS
}
/// Disc quota exceeded.
public static var EDQUOT: POSIXErrorCode {
return .EDQUOT
}
/// Network File System.
/// Stale NFS file handle.
public static var ESTALE: POSIXErrorCode {
return .ESTALE
}
/// Too many levels of remote in path.
public static var EREMOTE: POSIXErrorCode {
return .EREMOTE
}
/// RPC struct is bad.
public static var EBADRPC: POSIXErrorCode {
return .EBADRPC
}
/// RPC version wrong.
public static var ERPCMISMATCH: POSIXErrorCode {
return .ERPCMISMATCH
}
/// RPC prog. not avail.
public static var EPROGUNAVAIL: POSIXErrorCode {
return .EPROGUNAVAIL
}
/// Program version wrong.
public static var EPROGMISMATCH: POSIXErrorCode {
return .EPROGMISMATCH
}
/// Bad procedure for program.
public static var EPROCUNAVAIL: POSIXErrorCode {
return .EPROCUNAVAIL
}
/// No locks available.
public static var ENOLCK: POSIXErrorCode {
return .ENOLCK
}
/// Function not implemented.
public static var ENOSYS: POSIXErrorCode {
return .ENOSYS
}
/// Inappropriate file type or format.
public static var EFTYPE: POSIXErrorCode {
return .EFTYPE
}
/// Authentication error.
public static var EAUTH: POSIXErrorCode {
return .EAUTH
}
/// Need authenticator.
public static var ENEEDAUTH: POSIXErrorCode {
return .ENEEDAUTH
}
/// Intelligent device errors.
/// Device power is off.
public static var EPWROFF: POSIXErrorCode {
return .EPWROFF
}
/// Device error, e.g. paper out.
public static var EDEVERR: POSIXErrorCode {
return .EDEVERR
}
/// Value too large to be stored in data type.
public static var EOVERFLOW: POSIXErrorCode {
return .EOVERFLOW
}
/// Program loading errors.
/// Bad executable.
public static var EBADEXEC: POSIXErrorCode {
return .EBADEXEC
}
/// Bad CPU type in executable.
public static var EBADARCH: POSIXErrorCode {
return .EBADARCH
}
/// Shared library version mismatch.
public static var ESHLIBVERS: POSIXErrorCode {
return .ESHLIBVERS
}
/// Malformed Macho file.
public static var EBADMACHO: POSIXErrorCode {
return .EBADMACHO
}
/// Operation canceled.
public static var ECANCELED: POSIXErrorCode {
return .ECANCELED
}
/// Identifier removed.
public static var EIDRM: POSIXErrorCode {
return .EIDRM
}
/// No message of desired type.
public static var ENOMSG: POSIXErrorCode {
return .ENOMSG
}
/// Illegal byte sequence.
public static var EILSEQ: POSIXErrorCode {
return .EILSEQ
}
/// Attribute not found.
public static var ENOATTR: POSIXErrorCode {
return .ENOATTR
}
/// Bad message.
public static var EBADMSG: POSIXErrorCode {
return .EBADMSG
}
/// Reserved.
public static var EMULTIHOP: POSIXErrorCode {
return .EMULTIHOP
}
/// No message available on STREAM.
public static var ENODATA: POSIXErrorCode {
return .ENODATA
}
/// Reserved.
public static var ENOLINK: POSIXErrorCode {
return .ENOLINK
}
/// No STREAM resources.
public static var ENOSR: POSIXErrorCode {
return .ENOSR
}
/// Not a STREAM.
public static var ENOSTR: POSIXErrorCode {
return .ENOSTR
}
/// Protocol error.
public static var EPROTO: POSIXErrorCode {
return .EPROTO
}
/// STREAM ioctl timeout.
public static var ETIME: POSIXErrorCode {
return .ETIME
}
/// No such policy registered.
public static var ENOPOLICY: POSIXErrorCode {
return .ENOPOLICY
}
/// State not recoverable.
public static var ENOTRECOVERABLE: POSIXErrorCode {
return .ENOTRECOVERABLE
}
/// Previous owner died.
public static var EOWNERDEAD: POSIXErrorCode {
return .EOWNERDEAD
}
/// Interface output queue is full.
public static var EQFULL: POSIXErrorCode {
return .EQFULL
}
}
/// Describes an error in the Mach error domain.
public struct MachError : _BridgedStoredNSError {
public let _nsError: NSError
public init(_nsError error: NSError) {
precondition(error.domain == NSMachErrorDomain)
self._nsError = error
}
public static var _nsErrorDomain: String { return NSMachErrorDomain }
public typealias Code = MachErrorCode
}
extension MachErrorCode : _ErrorCodeProtocol {
public typealias _ErrorType = MachError
}
extension MachError {
public static var success: MachError.Code {
return .success
}
/// Specified address is not currently valid.
public static var invalidAddress: MachError.Code {
return .invalidAddress
}
/// Specified memory is valid, but does not permit the required
/// forms of access.
public static var protectionFailure: MachError.Code {
return .protectionFailure
}
/// The address range specified is already in use, or no address
/// range of the size specified could be found.
public static var noSpace: MachError.Code {
return .noSpace
}
/// The function requested was not applicable to this type of
/// argument, or an argument is invalid.
public static var invalidArgument: MachError.Code {
return .invalidArgument
}
/// The function could not be performed. A catch-all.
public static var failure: MachError.Code {
return .failure
}
/// A system resource could not be allocated to fulfill this
/// request. This failure may not be permanent.
public static var resourceShortage: MachError.Code {
return .resourceShortage
}
/// The task in question does not hold receive rights for the port
/// argument.
public static var notReceiver: MachError.Code {
return .notReceiver
}
/// Bogus access restriction.
public static var noAccess: MachError.Code {
return .noAccess
}
/// During a page fault, the target address refers to a memory
/// object that has been destroyed. This failure is permanent.
public static var memoryFailure: MachError.Code {
return .memoryFailure
}
/// During a page fault, the memory object indicated that the data
/// could not be returned. This failure may be temporary; future
/// attempts to access this same data may succeed, as defined by the
/// memory object.
public static var memoryError: MachError.Code {
return .memoryError
}
/// The receive right is already a member of the portset.
public static var alreadyInSet: MachError.Code {
return .alreadyInSet
}
/// The receive right is not a member of a port set.
public static var notInSet: MachError.Code {
return .notInSet
}
/// The name already denotes a right in the task.
public static var nameExists: MachError.Code {
return .nameExists
}
/// The operation was aborted. Ipc code will catch this and reflect
/// it as a message error.
public static var aborted: MachError.Code {
return .aborted
}
/// The name doesn't denote a right in the task.
public static var invalidName: MachError.Code {
return .invalidName
}
/// Target task isn't an active task.
public static var invalidTask: MachError.Code {
return .invalidTask
}
/// The name denotes a right, but not an appropriate right.
public static var invalidRight: MachError.Code {
return .invalidRight
}
/// A blatant range error.
public static var invalidValue: MachError.Code {
return .invalidValue
}
/// Operation would overflow limit on user-references.
public static var userReferencesOverflow: MachError.Code {
return .userReferencesOverflow
}
/// The supplied (port) capability is improper.
public static var invalidCapability: MachError.Code {
return .invalidCapability
}
/// The task already has send or receive rights for the port under
/// another name.
public static var rightExists: MachError.Code {
return .rightExists
}
/// Target host isn't actually a host.
public static var invalidHost: MachError.Code {
return .invalidHost
}
/// An attempt was made to supply "precious" data for memory that is
/// already present in a memory object.
public static var memoryPresent: MachError.Code {
return .memoryPresent
}
/// A page was requested of a memory manager via
/// memory_object_data_request for an object using a
/// MEMORY_OBJECT_COPY_CALL strategy, with the VM_PROT_WANTS_COPY
/// flag being used to specify that the page desired is for a copy
/// of the object, and the memory manager has detected the page was
/// pushed into a copy of the object while the kernel was walking
/// the shadow chain from the copy to the object. This error code is
/// delivered via memory_object_data_error and is handled by the
/// kernel (it forces the kernel to restart the fault). It will not
/// be seen by users.
public static var memoryDataMoved: MachError.Code {
return .memoryDataMoved
}
/// A strategic copy was attempted of an object upon which a quicker
/// copy is now possible. The caller should retry the copy using
/// vm_object_copy_quickly. This error code is seen only by the
/// kernel.
public static var memoryRestartCopy: MachError.Code {
return .memoryRestartCopy
}
/// An argument applied to assert processor set privilege was not a
/// processor set control port.
public static var invalidProcessorSet: MachError.Code {
return .invalidProcessorSet
}
/// The specified scheduling attributes exceed the thread's limits.
public static var policyLimit: MachError.Code {
return .policyLimit
}
/// The specified scheduling policy is not currently enabled for the
/// processor set.
public static var invalidPolicy: MachError.Code {
return .invalidPolicy
}
/// The external memory manager failed to initialize the memory object.
public static var invalidObject: MachError.Code {
return .invalidObject
}
/// A thread is attempting to wait for an event for which there is
/// already a waiting thread.
public static var alreadyWaiting: MachError.Code {
return .alreadyWaiting
}
/// An attempt was made to destroy the default processor set.
public static var defaultSet: MachError.Code {
return .defaultSet
}
/// An attempt was made to fetch an exception port that is
/// protected, or to abort a thread while processing a protected
/// exception.
public static var exceptionProtected: MachError.Code {
return .exceptionProtected
}
/// A ledger was required but not supplied.
public static var invalidLedger: MachError.Code {
return .invalidLedger
}
/// The port was not a memory cache control port.
public static var invalidMemoryControl: MachError.Code {
return .invalidMemoryControl
}
/// An argument supplied to assert security privilege was not a host
/// security port.
public static var invalidSecurity: MachError.Code {
return .invalidSecurity
}
/// thread_depress_abort was called on a thread which was not
/// currently depressed.
public static var notDepressed: MachError.Code {
return .notDepressed
}
/// Object has been terminated and is no longer available.
public static var terminated: MachError.Code {
return .terminated
}
/// Lock set has been destroyed and is no longer available.
public static var lockSetDestroyed: MachError.Code {
return .lockSetDestroyed
}
/// The thread holding the lock terminated before releasing the lock.
public static var lockUnstable: MachError.Code {
return .lockUnstable
}
/// The lock is already owned by another thread.
public static var lockOwned: MachError.Code {
return .lockOwned
}
/// The lock is already owned by the calling thread.
public static var lockOwnedSelf: MachError.Code {
return .lockOwnedSelf
}
/// Semaphore has been destroyed and is no longer available.
public static var semaphoreDestroyed: MachError.Code {
return .semaphoreDestroyed
}
/// Return from RPC indicating the target server was terminated
/// before it successfully replied.
public static var rpcServerTerminated: MachError.Code {
return .rpcServerTerminated
}
/// Terminate an orphaned activation.
public static var rpcTerminateOrphan: MachError.Code {
return .rpcTerminateOrphan
}
/// Allow an orphaned activation to continue executing.
public static var rpcContinueOrphan: MachError.Code {
return .rpcContinueOrphan
}
/// Empty thread activation (No thread linked to it).
public static var notSupported: MachError.Code {
return .notSupported
}
/// Remote node down or inaccessible.
public static var nodeDown: MachError.Code {
return .nodeDown
}
/// A signalled thread was not actually waiting.
public static var notWaiting: MachError.Code {
return .notWaiting
}
/// Some thread-oriented operation (semaphore_wait) timed out.
public static var operationTimedOut: MachError.Code {
return .operationTimedOut
}
/// During a page fault, indicates that the page was rejected as a
/// result of a signature check.
public static var codesignError: MachError.Code {
return .codesignError
}
/// The requested property cannot be changed at this time.
public static var policyStatic: MachError.Code {
return .policyStatic
}
}
public struct ErrorUserInfoKey : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable, _ObjectiveCBridgeable {
public init(rawValue: String) { self.rawValue = rawValue }
public var rawValue: String
}
public extension ErrorUserInfoKey {
@available(*, deprecated, renamed: "NSUnderlyingErrorKey")
static let underlyingErrorKey = ErrorUserInfoKey(rawValue: NSUnderlyingErrorKey)
@available(*, deprecated, renamed: "NSLocalizedDescriptionKey")
static let localizedDescriptionKey = ErrorUserInfoKey(rawValue: NSLocalizedDescriptionKey)
@available(*, deprecated, renamed: "NSLocalizedFailureReasonErrorKey")
static let localizedFailureReasonErrorKey = ErrorUserInfoKey(rawValue: NSLocalizedFailureReasonErrorKey)
@available(*, deprecated, renamed: "NSLocalizedRecoverySuggestionErrorKey")
static let localizedRecoverySuggestionErrorKey = ErrorUserInfoKey(rawValue: NSLocalizedRecoverySuggestionErrorKey)
@available(*, deprecated, renamed: "NSLocalizedRecoveryOptionsErrorKey")
static let localizedRecoveryOptionsErrorKey = ErrorUserInfoKey(rawValue: NSLocalizedRecoveryOptionsErrorKey)
@available(*, deprecated, renamed: "NSRecoveryAttempterErrorKey")
static let recoveryAttempterErrorKey = ErrorUserInfoKey(rawValue: NSRecoveryAttempterErrorKey)
@available(*, deprecated, renamed: "NSHelpAnchorErrorKey")
static let helpAnchorErrorKey = ErrorUserInfoKey(rawValue: NSHelpAnchorErrorKey)
@available(*, deprecated, renamed: "NSStringEncodingErrorKey")
static let stringEncodingErrorKey = ErrorUserInfoKey(rawValue: NSStringEncodingErrorKey)
@available(*, deprecated, renamed: "NSURLErrorKey")
static let NSURLErrorKey = ErrorUserInfoKey(rawValue: Foundation.NSURLErrorKey)
@available(*, deprecated, renamed: "NSFilePathErrorKey")
static let filePathErrorKey = ErrorUserInfoKey(rawValue: NSFilePathErrorKey)
}
| dc7d81db04b1f681c76de366faadbcf6 | 31.870744 | 117 | 0.731015 | false | false | false | false |
Eonil/HomeworkApp1 | refs/heads/master | Driver/Workbench1/VC3.swift | mit | 1 | //
// VC1.swift
// HomeworkApp1
//
// Created by Hoon H. on 2015/02/26.
//
//
import Foundation
import UIKit
func makeVC() -> UIViewController {
let vc = UIViewController()
vc.view.backgroundColor = UIColor.brownColor()
return vc
}
func makeVC1() -> UIViewController {
let vc = UIViewController()
vc.view.backgroundColor = UIColor.magentaColor()
return vc
}
class VC3: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(pageVC.view)
self.addChildViewController(pageVC)
self.view.addConstraints([
NSLayoutConstraint(item: pageVC.view, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0),
NSLayoutConstraint(item: pageVC.view, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0),
NSLayoutConstraint(item: pageVC.view, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: pageVC.view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0),
])
pageVC.dataSource = reactions
pageVC.setViewControllers([reactions.vcs.first!], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
for g in pageVC.gestureRecognizers {
self.view.addGestureRecognizer(g as! UIGestureRecognizer)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
}
////
private let pageVC = UIPageViewController(transitionStyle: UIPageViewControllerTransitionStyle.Scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.Horizontal, options: nil)
private let reactions = ReactionController()
}
private final class ReactionController: NSObject, UIPageViewControllerDataSource {
let vcs = [
makeVC(),
makeVC1(),
makeVC(),
makeVC1(),
makeVC(),
]
@objc
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return vcs.count
}
@objc
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
@objc
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
if let idx = find(vcs, viewController) {
if idx > 0 {
return vcs[idx-1]
}
}
return nil
}
@objc
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
if let idx = find(vcs, viewController) {
if idx < (vcs.count-1) {
return vcs[idx+1]
}
}
return nil
}
}
| b884b34465999d7f7be317de0e4b4c94 | 28.803922 | 197 | 0.763158 | false | false | false | false |
austinzheng/swift | refs/heads/master | test/SILOptimizer/access_enforcement_noescape.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -module-name access_enforcement_noescape -enable-sil-ownership -enforce-exclusivity=checked -Onone -emit-sil -swift-version 4 -parse-as-library %s | %FileCheck %s
// This tests SILGen and AccessEnforcementSelection as a single set of tests.
// (Some static/dynamic enforcement selection is done in SILGen, and some is
// deferred. That may change over time but we want the outcome to be the same).
//
// These tests attempt to fully cover the possibilities of reads and
// modifications to captures along with `inout` arguments on both the caller and
// callee side.
//
// Tests that result in a compile-time error have been commented out
// here so we can FileCheck this output. Instead, copies of these
// tests are compiled access_enforcement_noescape_error.swift to check
// the compiler diagnostics.
// Helper
func doOne(_ f: () -> ()) {
f()
}
// Helper
func doTwo(_: ()->(), _: ()->()) {}
// Helper
func doOneInout(_: ()->(), _: inout Int) {}
// Error: Cannot capture nonescaping closure.
// This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift.
// func reentrantCapturedNoescape(fn: (() -> ()) -> ()) {
// let c = { fn {} }
// fn(c)
// }
// Helper
struct Frob {
mutating func outerMut() { doOne { innerMut() } }
mutating func innerMut() {}
}
// Allow nested mutable access via closures.
func nestedNoEscape(f: inout Frob) {
doOne { f.outerMut() }
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tF : $@convention(thin) (@inout Frob) -> () {
// CHECK-NOT: begin_access
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tF'
// closure #1 in nestedNoEscape(f:)
// CHECK-LABEL: sil private @$s27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Frob) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Frob
// CHECK: %{{.*}} = apply %{{.*}}([[ACCESS]]) : $@convention(method) (@inout Frob) -> ()
// CHECK: end_access [[ACCESS]] : $*Frob
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tFyyXEfU_'
// Allow aliased noescape reads.
func readRead() {
var x = 3
// Inside each closure: [read] [static]
doTwo({ _ = x }, { _ = x })
x = 42
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape8readReadyyF : $@convention(thin) () -> () {
// CHECK: [[ALLOC:%.*]] = alloc_stack $Int, var, name "x"
// CHECK-NOT: begin_access
// CHECK: apply
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape8readReadyyF'
// closure #1 in readRead()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape8readReadyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK-NOT: begin_access [read] [dynamic]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape8readReadyyFyyXEfU_'
// closure #2 in readRead()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape8readReadyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK-NOT: begin_access [read] [dynamic]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape8readReadyyFyyXEfU0_'
// Allow aliased noescape reads of an `inout` arg.
func inoutReadRead(x: inout Int) {
// Inside each closure: [read] [static]
doTwo({ _ = x }, { _ = x })
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape09inoutReadE01xySiz_tF : $@convention(thin) (@inout Int) -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape09inoutReadE01xySiz_tF'
// closure #1 in inoutReadRead(x:)
// CHECK-LABEL: sil private @$s27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK-NOT: begin_access [read] [dynamic]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU_'
// closure #2 in inoutReadRead(x:)
// CHECK-LABEL: sil private @$s27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK-NOT: begin_access [read] [dynamic]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU0_'
// Allow aliased noescape read + boxed read.
func readBoxRead() {
var x = 3
let c = { _ = x }
// Inside may-escape closure `c`: [read] [dynamic]
// Inside never-escape closure: [read] [dynamic]
doTwo(c, { _ = x })
x = 42
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape11readBoxReadyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape11readBoxReadyyF'
// closure #1 in readBoxRead()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape11readBoxReadyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape11readBoxReadyyFyycfU_'
// closure #2 in readBoxRead()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape11readBoxReadyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape11readBoxReadyyFyyXEfU0_'
// Error: cannout capture inout.
//
// func inoutReadReadBox(x: inout Int) {
// let c = { _ = x }
// doTwo({ _ = x }, c)
// }
// Allow aliased noescape read + write.
func readWrite() {
var x = 3
// Inside closure 1: [read] [static]
// Inside closure 2: [modify] [static]
doTwo({ _ = x }, { x = 42 })
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape9readWriteyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape9readWriteyyF'
// closure #1 in readWrite()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape9readWriteyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape9readWriteyyFyyXEfU_'
// closure #2 in readWrite()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape9readWriteyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic]
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape9readWriteyyFyyXEfU0_'
// Allow aliased noescape read + write of an `inout` arg.
func inoutReadWrite(x: inout Int) {
// Inside closure 1: [read] [static]
// Inside closure 2: [modify] [static]
// Compile time error: see access_enforcement_noescape_error.swift.
// doTwo({ _ = x }, { x = 3 })
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape14inoutReadWrite1xySiz_tF : $@convention(thin) (@inout Int) -> () {
func readBoxWrite() {
var x = 3
let c = { _ = x }
// Inside may-escape closure `c`: [read] [dynamic]
// Inside never-escape closure: [modify] [dynamic]
doTwo(c, { x = 42 })
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape12readBoxWriteyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readBoxWriteyyF'
// closure #1 in readBoxWrite()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape12readBoxWriteyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readBoxWriteyyFyycfU_'
// closure #2 in readBoxWrite()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape12readBoxWriteyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readBoxWriteyyFyyXEfU0_'
// Error: cannout capture inout.
// func inoutReadBoxWrite(x: inout Int) {
// let c = { _ = x }
// doTwo({ x = 42 }, c)
// }
func readWriteBox() {
var x = 3
let c = { x = 42 }
// Inside may-escape closure `c`: [modify] [dynamic]
// Inside never-escape closure: [read] [dynamic]
doTwo({ _ = x }, c)
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape12readWriteBoxyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT2]], [[CVT1]])
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readWriteBoxyyF'
// closure #1 in readWriteBox()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape12readWriteBoxyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readWriteBoxyyFyycfU_'
// closure #2 in readWriteBox()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape12readWriteBoxyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readWriteBoxyyFyyXEfU0_'
// Error: cannout capture inout.
// func inoutReadWriteBox(x: inout Int) {
// let c = { x = 42 }
// doTwo({ _ = x }, c)
// }
// Error: noescape read + write inout.
func readWriteInout() {
var x = 3
// Around the call: [modify] [static]
// Inside closure: [modify] [static]
// Compile time error: see access_enforcement_noescape_error.swift.
// doOneInout({ _ = x }, &x)
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape14readWriteInoutyyF : $@convention(thin) () -> () {
// Error: noescape read + write inout of an inout.
func inoutReadWriteInout(x: inout Int) {
// Around the call: [modify] [static]
// Inside closure: [modify] [static]
// Compile time error: see access_enforcement_noescape_error.swift.
// doOneInout({ _ = x }, &x)
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape19inoutReadWriteInout1xySiz_tF : $@convention(thin) (@inout Int) -> () {
// Traps on boxed read + write inout.
// Covered by Interpreter/enforce_exclusive_access.swift.
func readBoxWriteInout() {
var x = 3
let c = { _ = x }
// Around the call: [modify] [dynamic]
// Inside closure: [read] [dynamic]
doOneInout(c, &x)
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape17readBoxWriteInoutyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %1 : $*Int
// CHECK: apply %{{.*}}([[CVT]], [[ACCESS]])
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape17readBoxWriteInoutyyF'
// closure #1 in readBoxWriteInout()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape17readBoxWriteInoutyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0
// CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape17readBoxWriteInoutyyFyycfU_'
// Error: inout cannot be captured.
// This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift.
// func inoutReadBoxWriteInout(x: inout Int) {
// let c = { _ = x }
// doOneInout(c, &x)
// }
// Allow aliased noescape write + write.
func writeWrite() {
var x = 3
// Inside closure 1: [modify] [static]
// Inside closure 2: [modify] [static]
doTwo({ x = 42 }, { x = 87 })
_ = x
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape10writeWriteyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape10writeWriteyyF'
// closure #1 in writeWrite()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape10writeWriteyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape10writeWriteyyFyyXEfU_'
// closure #2 in writeWrite()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape10writeWriteyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape10writeWriteyyFyyXEfU0_'
// Allow aliased noescape write + write of an `inout` arg.
func inoutWriteWrite(x: inout Int) {
// Inside closure 1: [modify] [static]
// Inside closure 2: [modify] [static]
doTwo({ x = 42}, { x = 87 })
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape010inoutWriteE01xySiz_tF : $@convention(thin) (@inout Int) -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape010inoutWriteE01xySiz_tF'
// closure #1 in inoutWriteWrite(x:)
// CHECK-LABEL: sil private @$s27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU_'
// closure #2 in inoutWriteWrite(x:)
// CHECK-LABEL: sil private @$s27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU0_'
// Traps on aliased boxed write + noescape write.
// Covered by Interpreter/enforce_exclusive_access.swift.
func writeWriteBox() {
var x = 3
let c = { x = 87 }
// Inside may-escape closure `c`: [modify] [dynamic]
// Inside never-escape closure: [modify] [dynamic]
doTwo({ x = 42 }, c)
_ = x
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape13writeWriteBoxyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK-NOT: begin_access
// CHECK: apply %{{.*}}([[CVT2]], [[CVT1]])
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape13writeWriteBoxyyF'
// closure #1 in writeWriteBox()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape13writeWriteBoxyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape13writeWriteBoxyyFyycfU_'
// closure #2 in writeWriteBox()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape13writeWriteBoxyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %0 : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape13writeWriteBoxyyFyyXEfU0_'
// Error: inout cannot be captured.
// func inoutWriteWriteBox(x: inout Int) {
// let c = { x = 87 }
// doTwo({ x = 42 }, c)
// }
// Error: on noescape write + write inout.
func writeWriteInout() {
var x = 3
// Around the call: [modify] [static]
// Inside closure: [modify] [static]
// Compile time error: see access_enforcement_noescape_error.swift.
// doOneInout({ x = 42 }, &x)
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape15writeWriteInoutyyF : $@convention(thin) () -> () {
// Error: on noescape write + write inout.
func inoutWriteWriteInout(x: inout Int) {
// Around the call: [modify] [static]
// Inside closure: [modify] [static]
// Compile time error: see access_enforcement_noescape_error.swift.
// doOneInout({ x = 42 }, &x)
}
// inoutWriteWriteInout(x:)
// Traps on boxed write + write inout.
// Covered by Interpreter/enforce_exclusive_access.swift.
func writeBoxWriteInout() {
var x = 3
let c = { x = 42 }
// Around the call: [modify] [dynamic]
// Inside closure: [modify] [dynamic]
doOneInout(c, &x)
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape18writeBoxWriteInoutyyF : $@convention(thin) () -> () {
// CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %1 : $*Int
// CHECK: apply %{{.*}}([[CVT]], [[ACCESS]])
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape18writeBoxWriteInoutyyF'
// closure #1 in writeBoxWriteInout()
// CHECK-LABEL: sil private @$s27access_enforcement_noescape18writeBoxWriteInoutyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int
// CHECK: end_access [[ACCESS]]
// CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape18writeBoxWriteInoutyyFyycfU_'
// Error: Cannot capture inout
// This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift.
// func inoutWriteBoxWriteInout(x: inout Int) {
// let c = { x = 42 }
// doOneInout(c, &x)
// }
// Helper
func doBlockInout(_: @convention(block) ()->(), _: inout Int) {}
func readBlockWriteInout() {
var x = 3
// Around the call: [modify] [static]
// Inside closure: [read] [static]
// Compile time error: see access_enforcement_noescape_error.swift.
// doBlockInout({ _ = x }, &x)
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape19readBlockWriteInoutyyF : $@convention(thin) () -> () {
// Test AccessSummaryAnalysis.
//
// The captured @inout_aliasable argument to `doOne` is re-partially applied,
// then stored is a box before passing it to doBlockInout.
func noEscapeBlock() {
var x = 3
doOne {
// Compile time error: see access_enforcement_noescape_error.swift.
// doBlockInout({ _ = x }, &x)
}
}
// CHECK-LABEL: sil hidden @$s27access_enforcement_noescape13noEscapeBlockyyF : $@convention(thin) () -> () {
| 5963141bca01ebfe5a484c15ffaba428 | 46.135524 | 193 | 0.656763 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | refs/heads/master | Pods/HXPHPicker/Sources/HXPHPicker/Editor/View/EditorStickerContentView.swift | mit | 1 | //
// EditorStickerContentView.swift
// HXPHPicker
//
// Created by Slience on 2021/7/20.
//
import UIKit
#if canImport(Kingfisher)
import Kingfisher
#endif
struct EditorStickerText {
let image: UIImage
let text: String
let textColor: UIColor
let showBackgroud: Bool
}
struct EditorStickerItem {
let image: UIImage
let imageData: Data?
let text: EditorStickerText?
let music: VideoEditorMusic?
var frame: CGRect {
var width = UIScreen.main.bounds.width - 80
if music != nil {
let height: CGFloat = 60
width = UIScreen.main.bounds.width - 40
return CGRect(origin: .zero, size: CGSize(width: width, height: height))
}
if text != nil {
width = UIScreen.main.bounds.width - 30
}
let height = width
var itemWidth: CGFloat = 0
var itemHeight: CGFloat = 0
let imageWidth = image.width
var imageHeight = image.height
if imageWidth > width {
imageHeight = width / imageWidth * imageHeight
}
if imageHeight > height {
itemWidth = height / image.height * imageWidth
itemHeight = height
}else {
if imageWidth > width {
itemWidth = width
}else {
itemWidth = imageWidth
}
itemHeight = imageHeight
}
return CGRect(x: 0, y: 0, width: itemWidth, height: itemHeight)
}
init(image: UIImage,
imageData: Data?,
text: EditorStickerText?,
music: VideoEditorMusic? = nil,
videoSize: CGSize? = nil) {
self.image = image
self.imageData = imageData
self.text = text
self.music = music
}
}
extension EditorStickerText: Codable {
enum CodingKeys: CodingKey {
case image
case text
case textColor
case showBackgroud
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let imageData = try container.decode(Data.self, forKey: .image)
image = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(imageData) as! UIImage
text = try container.decode(String.self, forKey: .text)
let colorData = try container.decode(Data.self, forKey: .textColor)
textColor = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(colorData) as! UIColor
showBackgroud = try container.decode(Bool.self, forKey: .showBackgroud)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if #available(iOS 11.0, *) {
let imageData = try NSKeyedArchiver.archivedData(withRootObject: image, requiringSecureCoding: false)
try container.encode(imageData, forKey: .image)
let colorData = try NSKeyedArchiver.archivedData(withRootObject: textColor, requiringSecureCoding: false)
try container.encode(colorData, forKey: .textColor)
} else {
let imageData = NSKeyedArchiver.archivedData(withRootObject: image)
try container.encode(imageData, forKey: .image)
let colorData = NSKeyedArchiver.archivedData(withRootObject: textColor)
try container.encode(colorData, forKey: .textColor)
}
try container.encode(text, forKey: .text)
try container.encode(showBackgroud, forKey: .showBackgroud)
}
}
extension EditorStickerItem: Codable {
enum CodingKeys: CodingKey {
case image
case imageData
case text
case music
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let imageData = try container.decode(Data.self, forKey: .image)
var image = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(imageData) as! UIImage
if let data = try container.decodeIfPresent(Data.self, forKey: .imageData) {
self.imageData = data
#if canImport(Kingfisher)
if data.kf.imageFormat == .GIF {
if let gifImage = DefaultImageProcessor.default.process(item: .data(imageData), options: .init([])) {
image = gifImage
}
}
#endif
}else {
self.imageData = nil
}
self.image = image
text = try container.decodeIfPresent(EditorStickerText.self, forKey: .text)
music = try container.decodeIfPresent(VideoEditorMusic.self, forKey: .music)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if #available(iOS 11.0, *) {
let imageData = try NSKeyedArchiver.archivedData(withRootObject: image, requiringSecureCoding: false)
try container.encode(imageData, forKey: .image)
} else {
let imageData = NSKeyedArchiver.archivedData(withRootObject: image)
try container.encode(imageData, forKey: .image)
}
if let data = imageData {
try container.encodeIfPresent(data, forKey: .imageData)
}else {
#if canImport(Kingfisher)
if let data = image.kf.gifRepresentation() {
try container.encodeIfPresent(data, forKey: .imageData)
}
#endif
}
try container.encodeIfPresent(text, forKey: .text)
try container.encodeIfPresent(music, forKey: .music)
}
}
class EditorStickerContentView: UIView {
lazy var animationView: VideoEditorMusicAnimationView = {
let view = VideoEditorMusicAnimationView(hexColor: "#ffffff")
view.startAnimation()
return view
}()
lazy var textLayer: CATextLayer = {
let textLayer = CATextLayer()
let fontSize: CGFloat = 25
let font = UIFont.boldSystemFont(ofSize: fontSize)
textLayer.font = font
textLayer.fontSize = fontSize
textLayer.foregroundColor = UIColor.white.cgColor
textLayer.truncationMode = .end
textLayer.contentsScale = UIScreen.main.scale
textLayer.alignmentMode = .left
textLayer.isWrapped = true
return textLayer
}()
lazy var imageView: ImageView = {
let view = ImageView()
if let imageData = item.imageData {
view.setImageData(imageData)
}else {
view.image = item.image
}
return view
}()
var scale: CGFloat = 1
var item: EditorStickerItem
weak var timer: Timer?
init(item: EditorStickerItem) {
self.item = item
super.init(frame: item.frame)
if item.music != nil {
addSubview(animationView)
layer.addSublayer(textLayer)
CATransaction.begin()
CATransaction.setDisableActions(true)
if let player = PhotoManager.shared.audioPlayer {
textLayer.string = item.music?.lyric(atTime: player.currentTime)?.lyric
}else {
textLayer.string = item.music?.lyric(atTime: 0)?.lyric
}
CATransaction.commit()
updateText()
startTimer()
}else {
if item.text != nil {
imageView.layer.shadowColor = UIColor.black.withAlphaComponent(0.8).cgColor
}
addSubview(imageView)
}
layer.shadowOpacity = 0.4
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
func startTimer() {
invalidateTimer()
let timer = Timer.scheduledTimer(
withTimeInterval: 0.5,
repeats: true, block: { [weak self] timer in
if let player = PhotoManager.shared.audioPlayer {
let lyric = self?.item.music?.lyric(atTime: player.currentTime)
if let str = self?.textLayer.string as? String,
let lyricStr = lyric?.lyric,
str == lyricStr {
return
}
CATransaction.begin()
CATransaction.setDisableActions(true)
self?.textLayer.string = lyric?.lyric
self?.updateText()
CATransaction.commit()
}else {
timer.invalidate()
self?.timer = nil
}
})
self.timer = timer
}
func invalidateTimer() {
self.timer?.invalidate()
self.timer = nil
}
func update(item: EditorStickerItem) {
self.item = item
if !frame.equalTo(item.frame) {
frame = item.frame
}
if imageView.image != item.image {
imageView.image = item.image
}
}
func updateText() {
if var height = (textLayer.string as? String)?.height(
ofFont: textLayer.font as! UIFont, maxWidth: width * scale
) {
height = min(100, height)
if textLayer.frame.height != height {
textLayer.frame = CGRect(origin: .zero, size: CGSize(width: width * scale, height: height))
}
}
animationView.frame = CGRect(x: 2, y: -23, width: 20, height: 15)
}
override func addGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) {
gestureRecognizer.delegate = self
super.addGestureRecognizer(gestureRecognizer)
}
override func layoutSubviews() {
super.layoutSubviews()
if item.music != nil {
updateText()
}else {
imageView.frame = bounds
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// deinit {
// print("deinit: \(self)")
// }
}
extension EditorStickerContentView: UIGestureRecognizerDelegate {
func gestureRecognizer(
_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
) -> Bool {
if otherGestureRecognizer.delegate is PhotoEditorViewController ||
otherGestureRecognizer.delegate is VideoEditorViewController {
return false
}
if otherGestureRecognizer is UITapGestureRecognizer || gestureRecognizer is UITapGestureRecognizer {
return true
}
if let view = gestureRecognizer.view, view == self,
let otherView = otherGestureRecognizer.view, otherView == self {
return true
}
return false
}
}
| f4488db1966daf31f19fb4e1993068b3 | 34.866221 | 117 | 0.596512 | false | false | false | false |
kopto/KRActivityIndicatorView | refs/heads/master | KRActivityIndicatorView/KRActivityIndicatorAnimationBallZigZag.swift | mit | 1 | //
// KRActivityIndicatorAnimationBallZigZag.swift
// KRActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Originally written to work in iOS by Vinh Nguyen in 2016
// Adapted to OSX by Henry Serrano in 2017
// 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 Cocoa
import QuartzCore
class KRActivityIndicatorAnimationBallZigZag: KRActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) {
let circleSize: CGFloat = size.width / 5
let duration: CFTimeInterval = 0.7
let deltaX = size.width / 2 - circleSize / 2
let deltaY = size.height / 2 - circleSize / 2
let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize)
// Circle 1 animation
let animation = CAKeyframeAnimation(keyPath:"transform")
animation.keyTimes = [0.0, 0.33, 0.66, 1.0]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle 1
circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
// Circle 2 animation
animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))]
// Draw circle 2
circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
}
func circleAt(frame: CGRect, layer: CALayer, size: CGSize, color: NSColor, animation: CAAnimation) {
let circle = KRActivityIndicatorShape.circle.layerWith(size: size, color: color)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| f6cedc325608c10fa70d9bc86616a199 | 48.586667 | 160 | 0.686206 | false | false | false | false |
DragonCherry/AssetsPickerViewController | refs/heads/master | Common/AssetsFetchService.swift | mit | 1 | //
// AssetsFetchService.swift
// AssetsPickerViewController
//
// Created by DragonCherry on 2020/07/03.
//
import Photos
// MARK: - Image Fetching IDs
class AssetsFetchService {
var requestMap = [IndexPath: PHImageRequestID]()
func cancelFetching(at indexPath: IndexPath) {
if let requestId = requestMap[indexPath] {
requestMap.removeValue(forKey: indexPath)
if LogConfig.isFetchLogEnabled { logd("Canceled ID: \(requestId) at: \(indexPath.row) (\(self.requestMap.count))") }
AssetsManager.shared.cancelRequest(requestId: requestId)
}
}
func registerFetching(requestId: PHImageRequestID, at indexPath: IndexPath) {
requestMap[indexPath] = requestId
if LogConfig.isFetchLogEnabled { logd("Registered ID: \(requestId) at: \(indexPath.row) (\(self.requestMap.count))") }
}
func removeFetching(indexPath: IndexPath) {
if let requestId = requestMap[indexPath] {
requestMap.removeValue(forKey: indexPath)
if LogConfig.isFetchLogEnabled { logd("Removed ID: \(requestId) at: \(indexPath.row) (\(self.requestMap.count))") }
}
}
func isFetching(indexPath: IndexPath) -> Bool {
if let _ = requestMap[indexPath] {
return true
} else {
return false
}
}
}
| 6cdeafbadd8530e819e7e9ea0baf378e | 30 | 128 | 0.634897 | false | true | false | false |
GreatAndPowerfulKing/Swift-Extensions | refs/heads/master | UIKIt/UITextField+PlaceholderColor.swift | mit | 1 | //
// UITextField+PlaceholderColor.swift
// Swift+Extensions
//
// Created by iKing on 17.05.17.
// Copyright © 2017 iKing. All rights reserved.
//
import UIKit
extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
var range = NSMakeRange(0, (placeholder ?? "").characters.count)
guard let color = attributedPlaceholder?.attribute(NSForegroundColorAttributeName, at: 0, effectiveRange: &range) as? UIColor else {
return UIColor.clear
}
return color
}
set {
let attributedText: NSMutableAttributedString
if let attributedPlaceholder = attributedPlaceholder {
attributedText = NSMutableAttributedString(attributedString: attributedPlaceholder)
} else if let placeholder = placeholder {
attributedText = NSMutableAttributedString(string: placeholder)
} else {
attributedText = NSMutableAttributedString(string: "")
}
let range = NSMakeRange(0, attributedText.length)
attributedText.addAttribute(NSForegroundColorAttributeName, value: newValue, range: range)
attributedPlaceholder = attributedText
}
}
}
| a10d710da90f19c84dc80e09f42f5ea1 | 28.756757 | 135 | 0.742961 | false | false | false | false |
firebase/quickstart-ios | refs/heads/master | storage/LegacyStorageQuickstart/StorageExampleSwift/DownloadViewController.swift | apache-2.0 | 1 | //
// Copyright (c) 2016 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 FirebaseStorage
@objc(DownloadViewController)
class DownloadViewController: UIViewController {
@IBOutlet var imageView: UIImageView!
@IBOutlet var statusTextView: UITextView!
var storageRef: StorageReference!
override func viewDidLoad() {
super.viewDidLoad()
storageRef = Storage.storage().reference()
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let filePath = "file:\(documentsDirectory)/myimage.jpg"
guard let fileURL = URL(string: filePath) else { return }
guard let storagePath = UserDefaults.standard.object(forKey: "storagePath") as? String else {
return
}
// [START downloadimage]
storageRef.child(storagePath).write(toFile: fileURL) { result in
switch result {
case let .success(url):
self.statusTextView.text = "Download Succeeded!"
self.imageView.image = UIImage(contentsOfFile: url.path)
case let .failure(error):
print("Error downloading:\(error)")
self.statusTextView.text = "Download Failed"
}
}
// [END downloadimage]
}
}
| b9617eca342a2d47abc54a33d1637fd6 | 33.647059 | 97 | 0.711941 | false | false | false | false |
ShauryaS/Bookkeeper | refs/heads/master | Pods/SwiftHTTP/Source/Request.swift | apache-2.0 | 4 | //
// Request.swift
// SwiftHTTP
//
// Created by Dalton Cherry on 8/16/15.
// Copyright © 2015 vluxe. All rights reserved.
//
import Foundation
extension String {
/**
A simple extension to the String object to encode it for web request.
:returns: Encoded version of of string it was called as.
*/
var escaped: String? {
let set = NSMutableCharacterSet()
set.formUnion(with: CharacterSet.urlQueryAllowed)
set.removeCharacters(in: "[].:/?&=;+!@#$()',*\"") // remove the HTTP ones from the set.
return self.addingPercentEncoding(withAllowedCharacters: set as CharacterSet)
}
/**
A simple extension to the String object to url encode quotes only.
:returns: string with .
*/
var quoteEscaped: String {
return self.replacingOccurrences(of: "\"", with: "%22").replacingOccurrences(of: "'", with: "%27")
}
}
/**
The standard HTTP Verbs
*/
public enum HTTPVerb: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case HEAD = "HEAD"
case DELETE = "DELETE"
case PATCH = "PATCH"
case OPTIONS = "OPTIONS"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
case UNKNOWN = "UNKNOWN"
}
/**
This is used to create key/value pairs of the parameters
*/
public struct HTTPPair {
var key: String?
let storeVal: AnyObject
/**
Create the object with a possible key and a value
*/
init(key: String?, value: AnyObject) {
self.key = key
self.storeVal = value
}
/**
Computed property of the string representation of the storedVal
*/
var upload: Upload? {
return storeVal as? Upload
}
/**
Computed property of the string representation of the storedVal
*/
var value: String {
if let v = storeVal as? String {
return v
} else if let v = storeVal.description {
return v
}
return ""
}
/**
Computed property of the string representation of the storedVal escaped for URLs
*/
var escapedValue: String {
if let v = value.escaped {
if let k = key {
if let escapedKey = k.escaped {
return "\(escapedKey)=\(v)"
}
}
return v
}
return ""
}
}
/**
Enum used to describe what kind of Parameter is being interacted with.
This allows us to only support an Array or Dictionary and avoid having to use AnyObject
*/
public enum HTTPParamType {
case array
case dictionary
case upload
}
/**
This protocol is used to make the dictionary and array serializable into key/value pairs.
*/
public protocol HTTPParameterProtocol {
func paramType() -> HTTPParamType
func createPairs(_ key: String?) -> Array<HTTPPair>
}
/**
Support for the Dictionary type as an HTTPParameter.
*/
extension Dictionary: HTTPParameterProtocol {
public func paramType() -> HTTPParamType {
return .dictionary
}
public func createPairs(_ key: String?) -> Array<HTTPPair> {
var collect = Array<HTTPPair>()
for (k, v) in self {
if let nestedKey = k as? String {
let useKey = key != nil ? "\(key!)[\(nestedKey)]" : nestedKey
if let subParam = v as? Dictionary { //as? HTTPParameterProtocol <- bug? should work.
collect.append(contentsOf: subParam.createPairs(useKey))
} else if let subParam = v as? Array<AnyObject> {
//collect.appendContentsOf(subParam.createPairs(useKey)) <- bug? should work.
for s in subParam.createPairs(useKey) {
collect.append(s)
}
} else {
collect.append(HTTPPair(key: useKey, value: v as AnyObject))
}
}
}
return collect
}
}
/**
Support for the Array type as an HTTPParameter.
*/
extension Array: HTTPParameterProtocol {
public func paramType() -> HTTPParamType {
return .array
}
public func createPairs(_ key: String?) -> Array<HTTPPair> {
var collect = Array<HTTPPair>()
for v in self {
let useKey = key != nil ? "\(key!)[]" : key
if let subParam = v as? Dictionary<String, AnyObject> {
collect.append(contentsOf: subParam.createPairs(useKey))
} else if let subParam = v as? Array<AnyObject> {
//collect.appendContentsOf(subParam.createPairs(useKey)) <- bug? should work.
for s in subParam.createPairs(useKey) {
collect.append(s)
}
} else {
collect.append(HTTPPair(key: useKey, value: v as AnyObject))
}
}
return collect
}
}
/**
Support for the Upload type as an HTTPParameter.
*/
extension Upload: HTTPParameterProtocol {
public func paramType() -> HTTPParamType {
return .upload
}
public func createPairs(_ key: String?) -> Array<HTTPPair> {
var collect = Array<HTTPPair>()
collect.append(HTTPPair(key: key, value: self))
return collect
}
}
/**
Adds convenience methods to NSMutableURLRequest to make using it with HTTP much simpler.
*/
extension NSMutableURLRequest {
/**
Convenience init to allow init with a string.
-parameter urlString: The string representation of a URL to init with.
*/
public convenience init?(urlString: String) {
if let url = URL(string: urlString) {
self.init(url: url)
} else {
return nil
}
}
/**
Convenience method to avoid having to use strings and allow using an enum
*/
public var verb: HTTPVerb {
set {
httpMethod = newValue.rawValue
}
get {
if let v = HTTPVerb(rawValue: httpMethod) {
return v
}
return .UNKNOWN
}
}
/**
Used to update the content type in the HTTP header as needed
*/
var contentTypeKey: String {
return "Content-Type"
}
/**
append the parameters using the standard HTTP Query model.
This is parameters in the query string of the url (e.g. ?first=one&second=two for GET, HEAD, DELETE.
It uses 'application/x-www-form-urlencoded' for the content type of POST/PUT requests that don't contains files.
If it contains a file it uses `multipart/form-data` for the content type.
-parameter parameters: The container (array or dictionary) to convert and append to the URL or Body
*/
public func appendParameters(_ parameters: HTTPParameterProtocol) throws {
if isURIParam() {
appendParametersAsQueryString(parameters)
} else if containsFile(parameters) {
try appendParametersAsMultiPartFormData(parameters)
} else {
appendParametersAsUrlEncoding(parameters)
}
}
/**
append the parameters as a HTTP Query string. (e.g. domain.com?first=one&second=two)
-parameter parameters: The container (array or dictionary) to convert and append to the URL
*/
public func appendParametersAsQueryString(_ parameters: HTTPParameterProtocol) {
let queryString = parameters.createPairs(nil).map({ (pair) in
return pair.escapedValue
}).joined(separator: "&")
if let u = self.url , queryString.characters.count > 0 {
let para = u.query != nil ? "&" : "?"
self.url = URL(string: "\(u.absoluteString)\(para)\(queryString)")
}
}
/**
append the parameters as a url encoded string. (e.g. in the body of the request as: first=one&second=two)
-parameter parameters: The container (array or dictionary) to convert and append to the HTTP body
*/
public func appendParametersAsUrlEncoding(_ parameters: HTTPParameterProtocol) {
if value(forHTTPHeaderField: contentTypeKey) == nil {
var contentStr = "application/x-www-form-urlencoded"
if let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(String.Encoding.utf8.rawValue)) {
contentStr += "; charset=\(charset)"
}
setValue(contentStr, forHTTPHeaderField:contentTypeKey)
}
let queryString = parameters.createPairs(nil).map({ (pair) in
return pair.escapedValue
}).joined(separator: "&")
httpBody = queryString.data(using: String.Encoding.utf8)
}
/**
append the parameters as a multpart form body. This is the type normally used for file uploads.
-parameter parameters: The container (array or dictionary) to convert and append to the HTTP body
*/
public func appendParametersAsMultiPartFormData(_ parameters: HTTPParameterProtocol) throws {
let boundary = "Boundary+\(arc4random())\(arc4random())"
if value(forHTTPHeaderField: contentTypeKey) == nil {
setValue("multipart/form-data; boundary=\(boundary)",
forHTTPHeaderField:contentTypeKey)
}
let mutData = NSMutableData()
let multiCRLF = "\r\n"
mutData.append("--\(boundary)".data(using: String.Encoding.utf8)!)
for pair in parameters.createPairs(nil) {
guard let key = pair.key else { continue } //this won't happen, but just to properly unwrap
mutData.append("\(multiCRLF)".data(using: String.Encoding.utf8)!)
if let upload = pair.upload {
let data = try upload.getData()
mutData.append(multiFormHeader(key, fileName: upload.fileName,
type: upload.mimeType, multiCRLF: multiCRLF).data(using: String.Encoding.utf8)!)
mutData.append(data as Data)
} else {
let str = "\(multiFormHeader(key, fileName: nil, type: nil, multiCRLF: multiCRLF))\(pair.value)"
mutData.append(str.data(using: String.Encoding.utf8)!)
}
mutData.append("\(multiCRLF)--\(boundary)".data(using: String.Encoding.utf8)!)
}
mutData.append("--\(multiCRLF)".data(using: String.Encoding.utf8)!)
httpBody = mutData as Data
}
/**
Helper method to create the multipart form data
*/
func multiFormHeader(_ name: String, fileName: String?, type: String?, multiCRLF: String) -> String {
var str = "Content-Disposition: form-data; name=\"\(name.quoteEscaped)\""
if let n = fileName {
str += "; filename=\"\(n.quoteEscaped)\""
}
str += multiCRLF
if let t = type {
str += "Content-Type: \(t)\(multiCRLF)"
}
str += multiCRLF
return str
}
/**
send the parameters as a body of JSON
-parameter parameters: The container (array or dictionary) to convert and append to the URL or Body
*/
public func appendParametersAsJSON(_ parameters: HTTPParameterProtocol) throws {
if isURIParam() {
appendParametersAsQueryString(parameters)
} else {
do {
httpBody = try JSONSerialization.data(withJSONObject: parameters as AnyObject, options: JSONSerialization.WritingOptions())
} catch let error {
throw error
}
var contentStr = "application/json"
if let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(String.Encoding.utf8.rawValue)) {
contentStr += "; charset=\(charset)"
}
setValue(contentStr, forHTTPHeaderField: contentTypeKey)
}
}
/**
Check if the request requires the parameters to be appended to the URL
*/
public func isURIParam() -> Bool {
if verb == .GET || verb == .HEAD || verb == .DELETE {
return true
}
return false
}
/**
check if the parameters contain a file object within them
-parameter parameters: The parameters to search through for an upload object
*/
public func containsFile(_ parameters: HTTPParameterProtocol) -> Bool {
for pair in parameters.createPairs(nil) {
if let _ = pair.upload {
return true
}
}
return false
}
}
| 7988596c99ee9c8e612041119a9e914f | 33.206612 | 145 | 0.601595 | false | false | false | false |
narner/AudioKit | refs/heads/master | AudioKit/Common/Nodes/Generators/Noise/Pink Noise/AKPinkNoise.swift | mit | 1 | //
// AKPinkNoise.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// Faust-based pink noise generator
///
open class AKPinkNoise: AKNode, AKToggleable, AKComponent {
public typealias AKAudioUnitType = AKPinkNoiseAudioUnit
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(generator: "pink")
// MARK: - Properties
private var internalAU: AKAudioUnitType?
private var token: AUParameterObserverToken?
private var amplitudeParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
@objc open dynamic var rampTime: Double = AKSettings.rampTime {
willSet {
internalAU?.rampTime = newValue
}
}
/// Amplitude. (Value between 0-1).
@objc open dynamic var amplitude: Double = 1 {
willSet {
if amplitude != newValue {
if let existingToken = token {
amplitudeParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted: Bool {
return internalAU?.isPlaying() ?? false
}
// MARK: - Initialization
/// Initialize this noise node
///
/// - parameter amplitude: Amplitude. (Value between 0-1).
///
@objc public init(amplitude: Double = 1) {
self.amplitude = amplitude
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
self?.avAudioNode = avAudioUnit
self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
}
guard let tree = internalAU?.parameterTree else {
AKLog("Parameter Tree Failed")
return
}
amplitudeParameter = tree["amplitude"]
token = tree.token(byAddingParameterObserver: { [weak self] _, _ in
guard let _ = self else {
AKLog("Unable to create strong reference to self")
return
} // Replace _ with strongSelf if needed
DispatchQueue.main.async {
// This node does not change its own values so we won't add any
// value observing, but if you need to, this is where that goes.
}
})
internalAU?.amplitude = Float(amplitude)
}
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
internalAU?.start()
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
internalAU?.stop()
}
}
| 3eaad8f636628b065381192c6e69868e | 29.638298 | 95 | 0.613194 | false | false | false | false |
huangboju/AsyncDisplay_Study | refs/heads/master | AsyncDisplay/SocialAppLayout/SocialController.swift | mit | 1 | //
// SocialController.swift
// AsyncDisplay
//
// Created by 伯驹 黄 on 2017/4/26.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import AsyncDisplayKit
class SocialController: ASDKViewController<ASTableNode> {
var tableNode: ASTableNode!
var data: [Post] = []
override init() {
tableNode = ASTableNode(style: .plain)
tableNode.inverted = true
super.init(node: tableNode)
tableNode.delegate = self
tableNode.dataSource = self
tableNode.autoresizingMask = [.flexibleWidth, .flexibleHeight]
title = "Timeline"
createSocialAppDataSource()
}
override func viewDidLoad() {
super.viewDidLoad()
tableNode.view.separatorStyle = .none
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let inset: CGFloat = 64
tableNode.contentInset = UIEdgeInsets.init(top: -inset, left: 0, bottom: inset, right: 0)
tableNode.view.scrollIndicatorInsets = UIEdgeInsets.init(top: -inset, left: 0, bottom: inset, right: 0)
}
func createSocialAppDataSource() {
let post1 = Post(
username: "@appleguy",
name: "Apple Guy",
photo: "https://avatars1.githubusercontent.com/u/565251?v=3&s=96",
post: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
time: "3s",
media: "",
via: 0,
likes: Int(arc4random_uniform(74)),
comments: Int(arc4random_uniform(40))
)
let post2 = Post(
username: "@nguyenhuy",
name: "Huy Nguyen",
photo: "https://avatars2.githubusercontent.com/u/587874?v=3&s=96",
post: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
time: "1m",
media: "",
via: 1,
likes: Int(arc4random_uniform(74)),
comments: Int(arc4random_uniform(40))
)
let post3 = Post(
username: "@veryyyylongusername",
name: "Alex Long Name",
photo: "https://avatars1.githubusercontent.com/u/8086633?v=3&s=96",
post: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
time: "3:02",
media: "http://www.ngmag.ru/upload/iblock/f93/f9390efc34151456598077c1ba44a94d.jpg",
via: 2,
likes: Int(arc4random_uniform(74)),
comments: Int(arc4random_uniform(40))
)
let post4 = Post(
username: "@vitalybaev",
name: "Vitaly Baev",
photo: "https://avatars0.githubusercontent.com/u/724423?v=3&s=96",
post: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. https://github.com/facebook/AsyncDisplayKit Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
time: "yesterday",
media: "",
via: 1,
likes: Int(arc4random_uniform(74)),
comments: Int(arc4random_uniform(40))
)
let posts = [post1, post2, post3, post4]
for _ in 0 ..< 100 {
let j = Int(arc4random_uniform(74)) % 4
data.append(posts[j])
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension SocialController: ASTableDataSource {
func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableNode(_ tableNode: ASTableNode, nodeBlockForRowAt indexPath: IndexPath) -> ASCellNodeBlock {
let post = data[indexPath.row]
return {
return PostNode(post: post)
}
}
}
extension SocialController: ASTableDelegate {
func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) {
print(indexPath)
}
}
| a762dba1b26de46926c223e9ce562442 | 34.08209 | 312 | 0.60987 | false | false | false | false |
SrirangaDigital/shankara-android | refs/heads/master | iOS/Advaita Sharada/Advaita Sharada/Bookmark.swift | gpl-2.0 | 1 | //
// Bookmark.swift
//
//
// Created by Amiruddin Nagri on 06/08/15.
//
//
import Foundation
import CoreData
@objc(Bookmark)
class Bookmark: NSManagedObject {
@NSManaged var book_id: NSNumber
@NSManaged var page_id: NSNumber
@NSManaged var bookmark_text: String
@NSManaged var chapter: String
static func isBookmarked(managedObjectContext: NSManagedObjectContext, bookId: NSNumber, pageId: NSNumber) -> Bool {
let request = NSFetchRequest(entityName: "Bookmark")
request.predicate = NSPredicate(format: "book_id == %@ AND page_id == %@", argumentArray: [bookId, pageId])
var error: NSError?
return managedObjectContext.countForFetchRequest(request, error: &error) != 0 && error == nil
}
static func addBookmark(managedObjectContext: NSManagedObjectContext, bookId: NSNumber, currentPage: Link, chapter: String) -> Bool {
if isBookmarked(managedObjectContext, bookId: bookId, pageId: currentPage.page) {
NSLog("Bookmark already present")
return true
}
let bookmark = NSEntityDescription.insertNewObjectForEntityForName("Bookmark", inManagedObjectContext: managedObjectContext) as! Bookmark
bookmark.book_id = bookId
bookmark.page_id = currentPage.page
bookmark.chapter = chapter
bookmark.bookmark_text = currentPage.bookmarkText()
var error: NSError?
managedObjectContext.save(&error)
if error == nil {
NSLog("Bookmark added \(bookmark)")
return true
}
NSLog("Failed to add \(bookmark)")
return false
}
static func removeBookmark(managedObjectContext: NSManagedObjectContext, bookId: NSNumber, pageId: NSNumber) -> Bool {
let request = NSFetchRequest(entityName: "Bookmark")
request.predicate = NSPredicate(format: "book_id == %@ AND page_id == %@", argumentArray: [bookId, pageId])
var error: NSError?
if let results = managedObjectContext.executeFetchRequest(request, error: &error) {
if error == nil && results.count > 0 {
if let bookmark = results[0] as? Bookmark {
managedObjectContext.deleteObject(bookmark)
NSLog("Bookmark removed")
return true
}
}
}
NSLog("Error while removing bookmark \(error)")
return false
}
static func count(managedObjectContext: NSManagedObjectContext, bookId: Int) -> Int {
let request = NSFetchRequest(entityName: "Bookmark")
request.predicate = NSPredicate(format: "book_id == %@", argumentArray: [bookId])
return managedObjectContext.countForFetchRequest(request, error: nil)
}
static func bookmarkAt(managedObjectContext: NSManagedObjectContext, bookId: Int, index: Int) -> Bookmark? {
let request = NSFetchRequest(entityName: "Bookmark")
request.predicate = NSPredicate(format: "book_id == %@", argumentArray: [bookId])
request.fetchLimit = 1
request.fetchOffset = index
request.sortDescriptors = [NSSortDescriptor(key: "page_id", ascending: true)]
var error: NSError?
if let result = managedObjectContext.executeFetchRequest(request, error: &error) {
if result.count > 0 {
return result[0] as? Bookmark
}
}
NSLog("Error while getting bookmark from book \(bookId) at index \(index), error \(error)")
return nil
}
}
| be1986b546e4bdcc70431dbf3cb72cee | 39.067416 | 145 | 0.636848 | false | false | false | false |
shvets/WebAPI | refs/heads/master | Sources/WebAPI/GoogleDocsAPI.swift | mit | 1 | import Foundation
import SwiftSoup
open class GoogleDocsAPI: HttpService {
// let SiteUrl = "http://cyro.se"
// let UserAgent = "Google Docs User Agent"
//
// func available() throws -> Elements {
// let document = try fetchDocument(SiteUrl, headers: getHeaders())
//
// return try document!.select("td.topic_content")
// }
//
// func getMovies(page: Int=1) throws -> ItemsList {
// return try getCategory(category: "movies", page: page)
// }
//
// func getSeries(page: Int=1) throws -> ItemsList {
// return try getCategory(category: "tvseries", page: page)
// }
//
// func getLatestEpisodes(page: Int=1) throws -> ItemsList {
// return try getCategory(category: "episodes", page: page)
// }
//
// func getLatest(page: Int=1) throws -> ItemsList {
// return try getCategory(category: "", page: page)
// }
//
// func getCategory(category: String="", page: Int=1) throws -> ItemsList {
// var data = [Any]()
// var paginationData: ItemsList = [:]
//
// var pagePath: String = ""
//
// if category != "" {
// pagePath = "/\(category)/index.php?" + "page=\(page)"
// }
// else {
// pagePath = "/index.php?show=latest-topics&" + "page=\(page)"
// }
//
// let document = try fetchDocument(SiteUrl + pagePath, headers: getHeaders())
//
// let items = try document!.select("td.topic_content")
//
// for item in items.array() {
// let href = try item.select("div a").attr("href")
//
// var path: String?
//
// if category != "" {
// path = "/\(category)/\(href)"
// }
// else {
// path = "/\(href)"
// }
//
// let name = try item.select("div a img").attr("alt")
// let urlPath = try item.select("div a img").attr("src")
// let thumb = SiteUrl + urlPath
//
// data.append(["path": path!, "thumb": thumb, "name": name])
// }
//
// if items.size() > 0 {
// paginationData = try extractPaginationData(pagePath, page: page)
// }
//
// return ["movies": data, "pagination": paginationData]
// }
//
// func getGenres(page: Int=1) throws -> ItemsList {
// var data = [Any]()
//
// let document = try fetchDocument(SiteUrl + "/movies/genre.php?showC=27", headers: getHeaders())
//
// let items = try document!.select("td.topic_content")
//
// for item in items.array() {
// let href = try item.select("div a").attr("href")
// let src = try item.select("div a img").attr("src")
//
// let path = "/movies/\(href)"
// let thumb = "\(SiteUrl)\(src)"
//
// let fileName = thumb.components(separatedBy: "/").last!
// let index1 = fileName.startIndex
//
// let name = fileName[index1 ..< fileName.find("-")!]
//
// data.append(["path": path, "thumb": thumb, "name": name])
// }
//
// return ["movies": data]
// }
//
// func getGenre(path: String, page: Int=1) throws -> ItemsList {
// var data = [Any]()
// var paginationData: ItemsList = [:]
//
// let response = httpRequest(SiteUrl + getCorrectedPath(path), headers: getHeaders())
//
// let newPath = "\(response!.response!.url!.path)?\(response!.response!.url!.query!)"
//
// let pagePath = newPath + "&page=\(page)"
//
// let document = try fetchDocument(SiteUrl + pagePath, headers: getHeaders())
//
// let items = try document!.select("td.topic_content")
//
// for item in items.array() {
// let href = try item.select("div a").attr("href")
//
// let path = "/movies/" + href
// let name = try item.select("div a img").attr("alt")
// let urlPath = try item.select("div a img").attr("src")
// let thumb = SiteUrl + urlPath
//
// data.append(["path": path, "thumb": thumb, "name": name])
// }
//
// if items.size() > 0 {
// paginationData = try extractPaginationData(pagePath, page: page)
// }
//
// return ["movies": data, "pagination": paginationData]
// }
//
// func getSerie(path: String, page: Int=1) throws -> ItemsList {
// var data = [Any]()
//
// let document = try fetchDocument(SiteUrl + path, headers: getHeaders())
//
// let items = try document!.select("div.titleline h2 a")
//
// for item in items.array() {
// let href = try item.attr("href")
//
// let path = "/forum/" + href
// let name = try item.text()
//
// data.append(["path": path, "name": name])
// }
//
// return ["movies": data]
// }
//
// func getPreviousSeasons(_ path: String) throws -> ItemsList {
// var data = [Any]()
//
// let document = try fetchDocument(SiteUrl + path, headers: getHeaders())
//
// let items = try document!.select("div.titleline h2 a")
//
// for item in items.array() {
// let href = try item.attr("href")
//
// let path = "/forum/" + href
// let name = try item.text()
//
// data.append(["path": path, "name": name])
// }
//
// return ["movies": data]
// }
//
//// func getSeasons(path: String) throws -> ItemsList {
//// let data = try self.getPreviousSeasons(path)
////
////// let currentSeason = try getSeason(path)
//////
////// let firstItemName = currentSeason[0]["name"]
////// let index1 = firstItemName.find("Season")
////// let index2 = firstItemName.find("Episode")
//////
////// let number = first_item_name[index1+6:index2].strip()
//////
////// data.append(["path": path, "name": "Season " + number])
////
//// return data
//// }
//
//// func getSeason(_ path: String) throws -> ItemsList {
//// var data = [Any]()
////
////// let document = try fetchDocument(SiteUrl + getCorrectedPath(path), headers: getHeaders())
//////
////// let items = try document!.select("div.inner h3 a")
//////
////// for item in items.array() {
////// let href = try item.attr("href")
//////
////// let path = "/forum/" + href
////// let name = try item.text()
//////
////// if name.find("Season Download") < 1 {
////// let newName = extractName(name)
//////
////// data.append(["path": path, "name": newName])
////// }
////// }
////
//// return ["movies": data]
//// }
//
// func updateUrls(data: [String: Any], url: String) -> [Any] {
// var urls = data["urls"] as! [Any]
//
// urls.append(url)
//
// return urls
// }
//
// func getMovie(_ id: String) throws -> [String: Any] {
// var data = [String: Any]()
//
// let response = httpRequest(SiteUrl + id, headers: getHeaders())
//
// let url = response!.response!.url!
//
// let document = try fetchDocument(url.absoluteString, headers: getHeaders())
//
// let name = try document!.select("title").text()
//
// data["name"] = extractName(name)
// data["thumb"] = SiteUrl + (try document!.select("img[id='nameimage']").attr("src"))
//
// data["urls"] = []
//
// let frameUrl1 = try document!.select("iframe").attr("src")
//
// if frameUrl1 != "" {
// let data1 = try fetchDocument(SiteUrl + frameUrl1, headers: getHeaders())
//
// let frameUrl2 = try data1!.select("iframe").attr("src")
//
// let data2 = try fetchDocument(SiteUrl + frameUrl2, headers: getHeaders())
//
// let url1 = try data2!.select("iframe").attr("src")
//
// data["urls"] = updateUrls(data: data, url: url1)
//
// let components = frameUrl2.components(separatedBy: ".")
//
// let frameUrl2WithoutExt = components[0...components.count-2].joined(separator: ".")
//
// if !frameUrl2WithoutExt.isEmpty {
// let secondUrlPart2 = frameUrl2WithoutExt + "2.php"
//
// do {
// let data3 = try fetchDocument(SiteUrl + secondUrlPart2, headers: getHeaders())
//
// let url2 = try data3!.select("iframe").attr("src")
//
// data["urls"] = updateUrls(data: data, url: url2)
// }
// catch {
// // suppress
// }
//
// do {
// let secondFrameUrlPart3 = frameUrl2WithoutExt + "3.php"
//
// let data4 = try fetchDocument(SiteUrl + secondFrameUrlPart3, headers: getHeaders())
//
// let url3 = try data4!.select("iframe").attr("src")
//
// if !url3.isEmpty {
// data["urls"] = updateUrls(data: data, url: url3)
// }
// }
// catch {
// // suppress
// }
// }
// }
//
//// if document.select("iframe[contains(@src,'ytid=')]/@src")) > 0 {
//// let el = SiteUrl + document!.xpath("//iframe[contains(@src,'ytid=')]/@src")[0]
////
//// //data["trailer_url"] = el.split("?",1)[0].replace("http://dayt.se/bits/pastube.php", "https://www.youtube.com/watch?v=") + el.split("=",1)[1]
//// }
//
// return data
// }
//
// func extractPaginationData(_ path: String, page: Int) throws -> ItemsList {
//// let document = try fetchDocument(SiteUrl + path, headers: getHeaders())
////
//// var pages = 1
////
//// let paginationRoot = try document?.select("div.mainpagination table tr")
////
//// if paginationRoot != nil {
//// let paginationBlock = paginationRoot!.get(0)
////
//// let items = try paginationBlock.select("td.table a")
////
//// pages = items.size()
//// }
////
//// return [
//// "page": page,
//// "pages": pages,
//// "has_previous": page > 1,
//// "has_next": page < pages
//// ]
//
// return [:]
// }
//
// func getCorrectedPath(_ path: String) -> String {
// let id = getMediaId(path)
//
// let index1 = path.startIndex
// let index21 = path.find("goto-")
//
// return path[index1 ..< index21!] + "view.php?id=\(id)"
// }
//
// func getMediaId(_ path: String) -> String {
// let index11 = path.find("/goto-")
//
// let index1 = path.index(index11!, offsetBy: 6)
//
// let idPart = String(path[index1 ..< path.endIndex])
//
// let index3 = idPart.startIndex
// let index41 = idPart.find("-")
//
// return String(idPart[index3 ..< index41!])
// }
//
// func extractName(_ name: String) -> String {
// //return name.rsplit(" Streaming", 1)[0].rsplit(" Download", 1)[0]
// return name
// }
//
// func getHeaders() -> [String: String] {
// return [
// "User-Agent": UserAgent
// ]
// }
}
| e7ca95d154e36b1d645e06df666fc8cf | 28.075145 | 152 | 0.554076 | false | false | false | false |
simorgh3196/Twifter | refs/heads/master | Sources/Twifter/Crypto/HMAC.swift | mit | 1 | //
// HMAC.swift
// Core
//
// Created by Tomoya Hayakawa on 2020/03/26.
// Copyright © 2020 simorgh3196. All rights reserved.
//
import CommonCrypto
import Foundation
struct HMAC {
let base: String
init(_ base: String) {
self.base = base
}
func data(withKey key: String, algorithm: DigestAlgorithm) -> Data {
let cKey = key.cString(using: .utf8)
let cData = base.cString(using: .utf8)
var result = [CUnsignedChar](repeating: 0, count: algorithm.digestLength)
CCHmac(algorithm.hmacAlgorithm, cKey!, strlen(cKey!), cData!, strlen(cData!), &result)
let hmacData = Data(bytes: result, count: algorithm.digestLength)
return hmacData
}
}
enum DigestAlgorithm {
case md5, sha1, sha224, sha256, sha384, sha512
fileprivate var digestLength: Int {
switch self {
case .md5:
return Int(CC_MD5_DIGEST_LENGTH)
case .sha1:
return Int(CC_SHA1_DIGEST_LENGTH)
case .sha224:
return Int(CC_SHA224_DIGEST_LENGTH)
case .sha256:
return Int(CC_SHA256_DIGEST_LENGTH)
case .sha384:
return Int(CC_SHA384_DIGEST_LENGTH)
case .sha512:
return Int(CC_SHA512_DIGEST_LENGTH)
}
}
fileprivate var hmacAlgorithm: CCHmacAlgorithm {
switch self {
case .md5:
return CCHmacAlgorithm(kCCHmacAlgMD5)
case .sha1:
return CCHmacAlgorithm(kCCHmacAlgSHA1)
case .sha224:
return CCHmacAlgorithm(kCCHmacAlgSHA224)
case .sha256:
return CCHmacAlgorithm(kCCHmacAlgSHA256)
case .sha384:
return CCHmacAlgorithm(kCCHmacAlgSHA384)
case .sha512:
return CCHmacAlgorithm(kCCHmacAlgSHA512)
}
}
}
| 7b0c0a08fbab52cdb56e8b053b190615 | 26.515152 | 94 | 0.60848 | false | false | false | false |
ScoutHarris/WordPress-iOS | refs/heads/develop | WordPress/WordPressTest/Extensions/ArrayTests.swift | gpl-2.0 | 2 | import XCTest
import WordPress
class ArrayTests: XCTestCase {
func testRepeatLast() {
let array = [1, 2, 3]
let repeated = Array(array.repeatingLast().prefix(5))
let expected = [1, 2, 3, 3, 3]
XCTAssertEqual(expected, repeated)
}
func testRepeatLastWithEmptyArray() {
let array = [Int]()
let repeated = Array(array.repeatingLast().prefix(5))
let expected = [Int]()
XCTAssertEqual(expected, repeated)
}
}
| 23fad34d13042eb86220ac0e75568095 | 26 | 61 | 0.609053 | false | true | false | false |
rivetlogic/liferay-mobile-directory-ios | refs/heads/master | Liferay-Screens/Source/DDL/ListScreenlet/ServerOperations/LiferayDDLListPageOperation.swift | gpl-3.0 | 1 | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 Lesser General Public License for more
* details.
*/
import UIKit
public class LiferayDDLListPageOperation: LiferayPaginationOperation {
public var userId: Int64?
public var recordSetId: Int64?
internal var ddlListScreenlet: DDLListScreenlet {
return self.screenlet as! DDLListScreenlet
}
internal var ddlListData: DDLListData {
return screenlet.screenletView as! DDLListData
}
override func validateData() -> Bool {
if recordSetId == nil {
return false
}
if ddlListData.labelFields.count == 0 {
return false
}
return true
}
override internal func doGetPageRowsOperation(#session: LRBatchSession, page: Int) {
let service = LRMobilewidgetsddlrecordService_v62(session: session)
if userId == nil {
service.getDdlRecordsWithDdlRecordSetId(recordSetId!,
locale: NSLocale.currentLocaleString,
start: Int32(ddlListScreenlet.firstRowForPage(page)),
end: Int32(ddlListScreenlet.firstRowForPage(page + 1)),
error: nil)
}
else {
service.getDdlRecordsWithDdlRecordSetId(recordSetId!,
userId: userId!,
locale: NSLocale.currentLocaleString,
start: Int32(ddlListScreenlet.firstRowForPage(page)),
end: Int32(ddlListScreenlet.firstRowForPage(page + 1)),
error: nil)
}
}
override internal func doGetRowCountOperation(#session: LRBatchSession) {
let service = LRMobilewidgetsddlrecordService_v62(session: session)
if userId == nil {
service.getDdlRecordsCountWithDdlRecordSetId(recordSetId!,
error: nil)
}
else {
service.getDdlRecordsCountWithDdlRecordSetId(recordSetId!,
userId: userId!,
error: nil)
}
}
}
| 7d822966c107783a0fcdece0616c0079 | 27.706667 | 85 | 0.747329 | false | false | false | false |
GYLibrary/A_Y_T | refs/heads/master | GYVideo/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationLineScalePulseOut.swift | mit | 2 | //
// NVActivityIndicatorAnimationLineScalePulseOut.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class NVActivityIndicatorAnimationLineScalePulseOut: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let lineSize = size.width / 9
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let duration: CFTimeInterval = 1
let beginTime = CACurrentMediaTime()
let beginTimes = [0.4, 0.2, 0, 0.2, 0.4]
let timingFunction = CAMediaTimingFunction(controlPoints: 0.85, 0.25, 0.37, 0.85)
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform.scale.y")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.4, 1]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw lines
for i in 0 ..< 5 {
let line = NVActivityIndicatorShape.line.layerWith(size: CGSize(width: lineSize, height: size.height), color: color)
let frame = CGRect(x: x + lineSize * 2 * CGFloat(i),
y: y,
width: lineSize,
height: size.height)
animation.beginTime = beginTime + beginTimes[i]
line.frame = frame
line.add(animation, forKey: "animation")
layer.addSublayer(line)
}
}
}
| 92b7221e9b17929740488394ffc9b4fc | 41.784615 | 128 | 0.661992 | false | false | false | false |
PorterHoskins/SlimLogger | refs/heads/master | SlimLogger/SlimLogger.swift | mit | 1 | //
// Created by Mats Melke on 12/02/15.
// Copyright (c) 2015 Baresi. All rights reserved.
//
import Foundation
enum SourceFilesThatShouldLog {
case All
case None
case EnabledSourceFiles([String])
}
public enum LogLevel: Int {
case trace = 100
case debug = 200
case info = 300
case warn = 400
case error = 500
case fatal = 600
var string:String {
switch self {
case trace:
return "TRACE"
case debug:
return "DEBUG"
case info:
return "INFO "
case warn:
return "WARN "
case error:
return "ERROR"
case fatal:
return "FATAL"
}
}
}
public protocol LogDestination {
func log<T>(@autoclosure message: () -> T, level:LogLevel,
filename: String, line: Int)
}
private let slim = Slim()
public class Slim {
var logDestinations: [LogDestination] = []
var cleanedFilenamesCache:NSCache = NSCache()
init() {
if SlimConfig.enableConsoleLogging {
logDestinations.append(ConsoleDestination())
}
}
public class func addLogDestination(destination: LogDestination) {
slim.logDestinations.append(destination)
}
public class func trace<T>(@autoclosure message: () -> T,
filename: String = __FILE__, line: Int = __LINE__) {
slim.logInternal(message, level: LogLevel.trace, filename: filename, line: line)
}
public class func debug<T>(@autoclosure message: () -> T,
filename: String = __FILE__, line: Int = __LINE__) {
slim.logInternal(message, level: LogLevel.debug, filename: filename, line: line)
}
public class func info<T>(@autoclosure message: () -> T,
filename: String = __FILE__, line: Int = __LINE__) {
slim.logInternal(message, level: LogLevel.info, filename: filename, line: line)
}
public class func warn<T>(@autoclosure message: () -> T,
filename: String = __FILE__, line: Int = __LINE__) {
slim.logInternal(message, level: LogLevel.warn, filename: filename, line: line)
}
public class func error<T>(@autoclosure message: () -> T,
filename: String = __FILE__, line: Int = __LINE__) {
slim.logInternal(message, level: LogLevel.error, filename: filename, line: line)
}
public class func fatal<T>(@autoclosure message: () -> T,
filename: String = __FILE__, line: Int = __LINE__) {
slim.logInternal(message, level: LogLevel.fatal, filename: filename, line: line)
}
private func logInternal<T>(@autoclosure message: () -> T, level:LogLevel,
filename: String, line: Int) {
let cleanedfile = cleanedFilename(filename)
if isSourceFileEnabled(cleanedfile) {
for dest in logDestinations {
dest.log(message, level: level, filename: cleanedfile, line: line)
}
}
}
private func cleanedFilename(filename:String) -> String {
if let cleanedfile:String = cleanedFilenamesCache.objectForKey(filename) as? String {
return cleanedfile
} else {
var retval = ""
let items = split(filename, allowEmptySlices: false, isSeparator:{$0=="/"})
if items.count > 0 {
retval = items.last!
}
cleanedFilenamesCache.setObject(retval, forKey:filename)
return retval
}
}
private func isSourceFileEnabled(cleanedFile:String) -> Bool {
switch SlimConfig.sourceFilesThatShouldLog {
case .All:
return true
case .None:
return false
case .EnabledSourceFiles(let enabledFiles):
if contains(enabledFiles, cleanedFile) {
return true
} else {
return false
}
}
}
}
class ConsoleDestination: LogDestination {
let dateFormatter = NSDateFormatter()
let serialLogQueue = dispatch_queue_create("ConsoleDestinationQueue", DISPATCH_QUEUE_SERIAL)
init() {
dateFormatter.dateFormat = "HH:mm:ss:SSS"
}
func log<T>(@autoclosure message: () -> T, level:LogLevel,
filename: String, line: Int) {
if level.rawValue >= SlimConfig.consoleLogLevel.rawValue {
let msg = message()
dispatch_async(self.serialLogQueue) {
println("\(self.dateFormatter.stringFromDate(NSDate())):\(level.string):\(filename):\(line) - \(msg)")
}
}
}
}
| cda9099da36a83370ea984aa21914482 | 28.766234 | 118 | 0.583333 | false | false | false | false |
Bluthwort/Bluthwort | refs/heads/master | Sources/Classes/Core/UIViewController.swift | mit | 1 | //
// UIViewController.swift
//
// Copyright (c) 2018 Bluthwort
//
// 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.
//
extension Bluthwort where Base: UIViewController {
// MARK: Get current view controller
public static var current: UIViewController? {
let keyPath = #keyPath(UIApplication.shared.keyWindow)
let keyWindow = UIApplication.value(forKeyPath: keyPath) as? UIWindow
if let viewController = keyWindow?.rootViewController {
return bestViewController(from: viewController)
} else {
return nil
}
}
static func bestViewController(from viewController: UIViewController) -> UIViewController {
if let presentedViewController = viewController.presentedViewController {
return bestViewController(from: presentedViewController)
} else if let splitViewController = viewController as? UISplitViewController,
splitViewController.viewControllers.count > 0 {
return bestViewController(from: splitViewController.viewControllers.last!)
} else if let navigationController = viewController as? UINavigationController,
navigationController.viewControllers.count > 0 {
return bestViewController(from: navigationController.topViewController!)
} else if let tabBarController = viewController as? UITabBarController,
let viewControllers = tabBarController.viewControllers,
viewControllers.count > 0 {
return bestViewController(from: tabBarController.selectedViewController!)
} else {
return viewController
}
}
// MARK: Convert view controller to UINavigationController
public func asNavigationController() -> UINavigationController {
return UINavigationController(rootViewController: base)
}
}
| e189f107888d41dacdb8b50df06137e7 | 44.857143 | 95 | 0.724126 | false | false | false | false |
abertelrud/swift-package-manager | refs/heads/main | Tests/CommandsTests/CommandsTestCase.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TSCBasic
import XCTest
class CommandsTestCase: XCTestCase {
/// Original working directory before the test ran (if known).
private var originalWorkingDirectory: AbsolutePath? = .none
override func setUp() {
originalWorkingDirectory = localFileSystem.currentWorkingDirectory
}
override func tearDown() {
if let originalWorkingDirectory = originalWorkingDirectory {
try? localFileSystem.changeCurrentWorkingDirectory(to: originalWorkingDirectory)
}
}
// FIXME: We should also hoist the `execute()` helper function that the various test suites implement, but right now they all seem to have slightly different implementations, so that's a later project.
}
| 1019929b2a84677db6a9aaeb92a7110a | 38.125 | 205 | 0.634984 | false | true | false | false |
sahat/github | refs/heads/master | GitHub/GitHub/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// GitHub
//
// Created by Sahat Yalkabov on 9/18/14.
// Copyright (c) 2014 Sahat Yalkabov. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
let masterNavigationController = splitViewController.viewControllers[0] as UINavigationController
let controller = masterNavigationController.topViewController as MasterViewController
controller.managedObjectContext = self.managedObjectContext
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
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
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.yahoo.GitHub" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("GitHub", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added 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.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("GitHub.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| 7044097f0f03c8de5054b0b75681bfee | 56.515152 | 290 | 0.724842 | false | false | false | false |
HabitRPG/habitrpg-ios | refs/heads/develop | Habitica Database/Habitica Database/Models/Content/RealmPet.swift | gpl-3.0 | 1 | //
// RealmPet.swift
// Habitica Database
//
// Created by Phillip Thelen on 16.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import RealmSwift
class RealmPet: Object, PetProtocol {
@objc dynamic var key: String?
@objc dynamic var egg: String?
@objc dynamic var potion: String?
@objc dynamic var type: String?
@objc dynamic var text: String?
override static func primaryKey() -> String {
return "key"
}
convenience init(_ petProtocol: PetProtocol) {
self.init()
key = petProtocol.key
egg = petProtocol.egg
potion = petProtocol.potion
if petProtocol.type == "whacky" {
type = "wacky"
} else {
type = petProtocol.type
}
text = petProtocol.text
}
}
| 13ee2a1854c494b304bd7b95e3f581be | 22.722222 | 55 | 0.61007 | false | false | false | false |
svanimpe/around-the-table | refs/heads/master | Tests/AroundTheTableTests/Models/ConversationTests.swift | bsd-2-clause | 1 | import BSON
import XCTest
@testable import AroundTheTable
class ConversationTests: XCTestCase {
static var allTests: [(String, (ConversationTests) -> () throws -> Void)] {
return [
("testInitializationValues", testInitializationValues),
("testEncode", testEncode),
("testDecode", testDecode),
("testDecodeNotADocument", testDecodeNotADocument),
("testDecodeMissingID", testDecodeMissingID),
("testDecodeSenderNotDenormalized", testDecodeSenderNotDenormalized),
("testDecodeRecipientNotDenormalized", testDecodeRecipientNotDenormalized),
("testDecodeMissingMessages", testDecodeMissingMessages)
]
}
private let message = Conversation.Message(direction: .outgoing, text: "Hello")
private var host = User(id: 1, name: "Host")
private var player = User(id: 2, name: "Player")
func testInitializationValues() {
let conversation = Conversation(sender: player, recipient: host)
XCTAssertNil(conversation.id)
XCTAssert(conversation.messages.isEmpty)
}
func testEncode() {
let input = Conversation(id: 1, sender: host, recipient: player, messages: [message])
let expected: Document = [
"_id": 1,
"sender": host.id,
"recipient": player.id,
"messages": [message]
]
XCTAssert(input.typeIdentifier == expected.typeIdentifier)
XCTAssert(input.document == expected)
}
func testDecode() throws {
let input: Document = [
"_id": 1,
"sender": host,
"recipient": player,
"messages": [message]
]
guard let result = try Conversation(input) else {
return XCTFail()
}
XCTAssert(result.id == 1)
XCTAssert(result.sender == host)
XCTAssert(result.recipient == player)
XCTAssert(result.messages.count == 1)
assertDatesEqual(result.messages[0].timestamp, message.timestamp)
XCTAssert(result.messages[0].direction == .outgoing)
XCTAssert(result.messages[0].text == "Hello")
XCTAssertFalse(result.messages[0].isRead)
}
func testDecodeNotADocument() throws {
let input: Primitive = "Hello"
let result = try Conversation(input)
XCTAssertNil(result)
}
func testDecodeMissingID() throws {
let input: Document = [
"sender": host,
"recipient": player,
"messages": [message]
]
XCTAssertThrowsError(try Conversation(input))
}
func testDecodeSenderNotDenormalized() throws {
let input: Document = [
"_id": 1,
"sender": host.id,
"recipient": player,
"messages": [message]
]
XCTAssertThrowsError(try Conversation(input))
}
func testDecodeRecipientNotDenormalized() throws {
let input: Document = [
"_id": 1,
"sender": host,
"recipient": player.id,
"messages": [message]
]
XCTAssertThrowsError(try Conversation(input))
}
func testDecodeMissingMessages() throws {
let input: Document = [
"_id": 1,
"sender": host,
"recipient": player
]
XCTAssertThrowsError(try Conversation(input))
}
}
| 5ccc9092fe00de8ccfa6656f60ea580f | 31.733333 | 93 | 0.583649 | false | true | false | false |
eurofurence/ef-app_ios | refs/heads/release/4.0.0 | Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Default Dependency Implementations/Core Data Store/Model Adaptation/KnowledgeGroupEntity+Adaptation.swift | mit | 1 | import Foundation
extension KnowledgeGroupEntity: EntityAdapting {
typealias AdaptedType = KnowledgeGroupCharacteristics
static func makeIdentifyingPredicate(for model: KnowledgeGroupCharacteristics) -> NSPredicate {
return NSPredicate(format: "identifier == %@", model.identifier)
}
func asAdaptedType() -> KnowledgeGroupCharacteristics {
guard let identifier = identifier, let groupName = groupName, let groupDescription = groupDescription else {
abandonDueToInconsistentState()
}
return KnowledgeGroupCharacteristics(
identifier: identifier,
order: Int(order),
groupName: groupName,
groupDescription: groupDescription,
fontAwesomeCharacterAddress: fontAwesomeCharacterAddress ?? ""
)
}
func consumeAttributes(from value: KnowledgeGroupCharacteristics) {
identifier = value.identifier
order = Int64(value.order)
groupName = value.groupName
groupDescription = value.groupDescription
fontAwesomeCharacterAddress = value.fontAwesomeCharacterAddress
}
}
| c6583d4fde1100a8e8400ad4ec2e9f3a | 33.878788 | 116 | 0.691573 | false | false | false | false |
khawars/KSTokenView | refs/heads/master | Examples/Examples/ViewControllers/Horizontal.swift | mit | 1 | //
// Horizontal.swift
// Examples
//
// Created by Khawar Shahzad on 12/13/16.
// Copyright © 2016 Khawar Shahzad. All rights reserved.
//
import UIKit
class Horizontal: UIViewController {
let names: Array<String> = List.names()
@IBOutlet weak var tokenView: KSTokenView!
override func viewDidLoad() {
super.viewDidLoad()
tokenView.delegate = self
tokenView.promptText = "Top: "
tokenView.placeholder = "Type to search"
tokenView.descriptionText = "Languages"
tokenView.maxTokenLimit = -1
tokenView.minimumCharactersToSearch = 0 // Show all results without without typing anything
tokenView.style = .squared
tokenView.direction = .horizontal
}
}
extension Horizontal: KSTokenViewDelegate {
func tokenView(_ tokenView: KSTokenView, performSearchWithString string: String, completion: ((_ results: Array<AnyObject>) -> Void)?) {
if (string.isEmpty){
completion!(names as Array<AnyObject>)
return
}
var data: Array<String> = []
for value: String in names {
if value.lowercased().range(of: string.lowercased()) != nil {
data.append(value)
}
}
completion!(data as Array<AnyObject>)
}
func tokenView(_ tokenView: KSTokenView, displayTitleForObject object: AnyObject) -> String {
return object as! String
}
}
| 69232cfd1468c71a04a18fcdb9da2d9a | 28.857143 | 140 | 0.623377 | false | false | false | false |
codingforentrepreneurs/Django-to-iOS | refs/heads/master | Source/ios/srvup/VideoViewController.swift | apache-2.0 | 1 | //
// VideoViewController.swift
// srvup
//
// Created by Justin Mitchel on 6/17/15.
// Copyright (c) 2015 Coding for Entrepreneurs. All rights reserved.
//
import UIKit
class VideoViewController: UIViewController, UITextViewDelegate {
var lecture: Lecture?
var webView = UIWebView()
var commentView = UIView()
var message = UITextView()
let textArea = UITextView()
let textAreaPlaceholder = "Your comment here..."
let user = User()
override func viewWillAppear(animated: Bool) {
user.checkToken()
}
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel()
label.frame = CGRectMake(0, 30, self.view.frame.width, 50)
if self.lecture != nil {
let webViewWidth = self.view.frame.width - 20
let webViewVideoHeight = 275
let embedCode = lecture!.embedCode
let cssCode = "<style>body{padding:0px;margin:0px;}iframe{width:\(webViewWidth);height:\(webViewVideoHeight);}</style>"
let htmlCode = "<html>\(cssCode)<body><h1>\(self.lecture!.title)</h1>\(embedCode)</body></html>"
self.webView.frame = CGRectMake(10, 50, webViewWidth, 375)
let url = NSURL(string: "http://codingforentrepreneurs.com")
self.webView.loadHTMLString(htmlCode, baseURL: url)
self.webView.scrollView.bounces = false
self.webView.backgroundColor = .whiteColor()
}
// self.view.addSubview(label)
let btn = UINavButton(title: "Back", direction: .Right, parentView: self.view)
btn.addTarget(self, action: "popView:", forControlEvents: UIControlEvents.TouchUpInside)
let addFormBtn = UINavButton(title: "New", direction: .Right, parentView: self.view)
addFormBtn.frame = CGRectMake(btn.frame.origin.x, btn.frame.origin.y + btn.frame.height + 5, btn.frame.width, btn.frame.height)
addFormBtn.addTarget(self, action: "newComment:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(self.webView)
self.view.addSubview(btn)
self.view.addSubview(addFormBtn)
let commentViewBtn = UIButton()
commentViewBtn.frame = CGRectMake(self.webView.frame.origin.x, self.webView.frame.origin.y + self.webView.frame.height + 15, self.webView.frame.width, 50)
commentViewBtn.setTitle("View/Add Comments", forState: UIControlState.Normal)
commentViewBtn.addTarget(self, action: "showComments:", forControlEvents: UIControlEvents.TouchUpInside)
commentViewBtn.backgroundColor = .blackColor()
commentViewBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
self.view.addSubview(commentViewBtn)
// Do any additional setup after loading the view.
}
func showComments(sender:AnyObject) {
self.performSegueWithIdentifier("showComments", sender: self)
}
func newComment(sender:AnyObject){
self.commentView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
self.commentView.backgroundColor = .blackColor()
let topOffset = CGFloat(25)
let xOffset = CGFloat(10)
let spacingE = CGFloat(10)
// response message
self.message.editable = false
self.message.frame = CGRectMake(xOffset, topOffset, self.commentView.frame.width - (2 * xOffset), 30)
self.message.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.0)
self.message.textColor = .redColor()
// title
let label = UILabel()
label.text = "Add new Comment"
label.frame = CGRectMake(xOffset, self.message.frame.origin.y + self.message.frame.height + spacingE, self.message.frame.width, 30)
label.textColor = .whiteColor()
// text area field
self.textArea.editable = true
self.textArea.text = self.textAreaPlaceholder
self.textArea.delegate = self
self.textArea.frame = CGRectMake(xOffset, label.frame.origin.y + label.frame.height + spacingE, label.frame.width, 250)
// submit button
let submitBtn = UIButton()
submitBtn.frame = CGRectMake(xOffset, self.textArea.frame.origin.y + self.textArea.frame.height + spacingE, self.textArea.frame.width, 30)
submitBtn.setTitle("Submit", forState: UIControlState.Normal)
submitBtn.addTarget(self, action: "commentFormAction:", forControlEvents: UIControlEvents.TouchUpInside)
submitBtn.tag = 1
// cancel button
let cancelBtn = UIButton()
cancelBtn.frame = CGRectMake(xOffset, submitBtn.frame.origin.y + submitBtn.frame.height + spacingE, submitBtn.frame.width, 30)
cancelBtn.setTitle("Cancel", forState: UIControlState.Normal)
cancelBtn.addTarget(self, action: "commentFormAction:", forControlEvents: UIControlEvents.TouchUpInside)
cancelBtn.tag = 2
self.commentView.addSubview(label)
self.commentView.addSubview(self.message)
self.commentView.addSubview(self.textArea)
self.commentView.addSubview(submitBtn)
self.commentView.addSubview(cancelBtn)
self.view.addSubview(self.commentView)
Notification().fadeIn(self.commentView, speed: 0.5)
}
func textViewDidBeginEditing(textView: UITextView) {
self.message.text = ""
if textView.text == self.textAreaPlaceholder {
textView.text = ""
}
}
func commentFormAction(sender: AnyObject) {
let tag = sender.tag
switch tag {
case 1:
if self.textArea.text != "" && self.textArea.text != self.textAreaPlaceholder {
self.textArea.endEditing(true)
self.lecture!.addComment(self.textArea.text, completion: addCommentCompletionHandler)
} else {
self.message.text = "A comment is required."
}
default:
println("cancelled")
self.commentView.removeFromSuperview()
}
}
func addCommentCompletionHandler(success:Bool) -> Void {
if !success {
self.newComment(self)
Notification().notify("Failed to add", delay: 2.5, inSpeed: 0.7, outSpeed: 1.2)
// self.tiggerNotification()
} else {
// self.tiggerNotification("New comment added!")
Notification().notify("Message Added", delay: 1.5, inSpeed: 0.5, outSpeed: 1.0)
self.commentView.removeFromSuperview()
// let alert = UIAlertView(title: "Thank you for the comment.", message: "", delegate: nil, cancelButtonTitle: "Okay")
// alert.show()
}
}
func popView(sender:AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
// self.dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showComments" {
let vc = segue.destinationViewController as! CommentTableViewController
vc.lecture = self.lecture
}
}
}
| e8855ab07b103ad5c7584715ac663d69 | 37.704082 | 162 | 0.629976 | false | false | false | false |
kliu/Cartography | refs/heads/master | CartographyTests/LayoutSupportSpec.swift | mit | 2 | import Cartography
import Nimble
import Quick
import UIKit
class LayoutSupportSpec: QuickSpec {
override func spec() {
var window: TestWindow!
var view: TestView!
var viewController: UIViewController!
var navigationController: UINavigationController!
var tabBarController: UITabBarController!
beforeEach {
window = TestWindow(frame: CGRect(x: 0,y: 0, width: 400, height: 400))
view = TestView(frame: CGRect.zero)
viewController = UIViewController()
viewController.view.addSubview(view)
constrain(view) { view in
view.height == 200
view.width == 200
}
navigationController = UINavigationController(rootViewController: viewController)
tabBarController = UITabBarController()
tabBarController.viewControllers = [navigationController]
tabBarController.view.frame = window.bounds
tabBarController.view.layoutIfNeeded()
window.rootViewController = tabBarController
window.setNeedsLayout()
window.layoutIfNeeded()
print(viewController.topLayoutGuide)
}
describe("LayoutSupport.top") {
it("should support relative equalities") {
viewController.view.layoutIfNeeded()
constrain(view, viewController.car_topLayoutGuide) { view, topLayoutGuide in
view.top == topLayoutGuide.bottom
}
viewController.view.layoutIfNeeded()
expect(view.convert(view.bounds, to: window).minY).to(equal(viewController.topLayoutGuide.length))
}
it("should support relative inequalities") {
constrain(view, viewController.car_topLayoutGuide) { view, topLayoutGuide in
view.top <= topLayoutGuide.bottom
view.top >= topLayoutGuide.bottom
}
viewController.view.layoutIfNeeded()
expect(view.convert(view.bounds, to: window).minY).to(equal(viewController.topLayoutGuide.length))
}
it("should support addition") {
constrain(view, viewController.car_topLayoutGuide) { view, topGuide in
view.top == topGuide.bottom + 100
}
viewController.view.layoutIfNeeded()
expect(view.convert(view.bounds, to: window).minY).to(equal(100 + viewController.topLayoutGuide.length))
}
it("should support subtraction") {
constrain(view, viewController.car_topLayoutGuide) { view, topGuide in
view.top == topGuide.bottom - 100
}
viewController.view.layoutIfNeeded()
expect(view.convert(view.bounds, to: window).minY).to(equal(-100 - viewController.topLayoutGuide.length))
}
}
describe("LayoutSupport.bottom") {
it("should support relative equalities") {
constrain(view, viewController.car_bottomLayoutGuide) { view, bottomGuide in
view.bottom == bottomGuide.top
}
viewController.view.layoutIfNeeded()
expect(view.convert(view.bounds, to: window).maxY).to(equal(window.bounds.maxY - viewController.bottomLayoutGuide.length))
}
it("should support relative inequalities") {
constrain(view, viewController.car_bottomLayoutGuide) { view, bottomGuide in
view.bottom <= bottomGuide.top
view.bottom >= bottomGuide.top
}
viewController.view.layoutIfNeeded()
expect(view.convert(view.bounds, to: window).maxY).to(equal(window.bounds.maxY - viewController.bottomLayoutGuide.length))
}
it("should support addition") {
constrain(view, viewController.car_bottomLayoutGuide) { view, bottomGuide in
view.bottom == bottomGuide.top + 100
}
viewController.view.layoutIfNeeded()
expect(view.convert(view.bounds, to: window).maxY).to(equal(100 + window.bounds.maxY - viewController.bottomLayoutGuide.length))
}
it("should support subtraction") {
constrain(view, viewController.car_bottomLayoutGuide) { view, bottomGuide in
view.bottom == bottomGuide.top - 100
}
viewController.view.layoutIfNeeded()
expect(view.convert(view.bounds, to: window).maxY).to(equal((window.bounds.maxY - 100) - viewController.bottomLayoutGuide.length))
}
}
}
}
| 92d6c3fd147575e6527529aaee350703 | 39.207692 | 146 | 0.542759 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | refs/heads/master | AviasalesSDKTemplate/Source/Categories/DateExtensions.swift | mit | 1 | @objc extension NSDate {
func hour() -> Int {
let calendar = HDKDateUtil.sharedCalendar
let components = calendar.dateComponents(Set([Calendar.Component.hour]), from: self as Date)
return components.hour!
}
func minute() -> Int {
let calendar = HDKDateUtil.sharedCalendar
let components = calendar.dateComponents(Set([Calendar.Component.minute]), from: self as Date)
return components.minute!
}
func second() -> Int {
let calendar = HDKDateUtil.sharedCalendar
let components = calendar.dateComponents(Set([Calendar.Component.second]), from: self as Date)
return components.second!
}
}
| a0bdbc913cf1976f26eeb031960d8957 | 31.619048 | 102 | 0.658394 | false | false | false | false |
JeffESchmitz/RideNiceRide | refs/heads/master | Pods/Sugar/Source/iOS/Extensions/UIDevice+Model.swift | mit | 3 | import UIKit
public extension UIDevice {
public enum DeviceKind {
case iPhone4
case iPhone5
case iPhone6
case iPhone6Plus
case iPad
case unknown
}
public var kind: DeviceKind {
guard userInterfaceIdiom == .phone else {
return .iPad
}
let result: DeviceKind
switch UIScreen.main.nativeBounds.height {
case 960:
result = .iPhone4
case 1136:
result = .iPhone5
case 1334:
result = .iPhone6
case 2208:
result = .iPhone6Plus
default:
result = .unknown
}
return result
}
public static func isPhone() -> Bool {
return UIDevice().userInterfaceIdiom == .phone
}
public static func isPad() -> Bool {
return UIDevice().userInterfaceIdiom == .pad
}
public static func isSimulator() -> Bool {
return Simulator.isRunning
}
}
| b4b14b5d736250f09be6d3943099f391 | 16.895833 | 50 | 0.627474 | false | false | false | false |
caipre/forecast | refs/heads/master | Sources/Extensions/NSView+Forecast.swift | isc | 1 | //
// Forecast
//
//
import Cocoa
extension NSView {
var backgroundColor: NSColor? {
get {
guard let backgroundColor = self.layer?.backgroundColor else { return nil }
return NSColor(cgColor: backgroundColor)
}
set {
guard let color = newValue else {
self.layer?.backgroundColor = NSColor.clear.cgColor
return
}
self.wantsLayer = true
self.layer?.backgroundColor = color.cgColor
}
}
convenience init(backgroundColor: NSColor) {
self.init()
self.backgroundColor = backgroundColor
}
}
| b9c03e76963bfc52bf389eb24d4c4beb | 20.193548 | 87 | 0.5586 | false | false | false | false |
nifti/CinchKit | refs/heads/master | CinchKit/Client/CNHKeychain.swift | mit | 1 | //
// CNHKeychain.swift
// CinchKit
//
// Created by Ryan Fitzgerald on 2/25/15.
// Copyright (c) 2015 cinch. All rights reserved.
//
import Foundation
import KeychainAccess
public class CNHKeychain {
private let keychain = Keychain(service: "com.cinchkit.tokens")
public init() {
}
public func load() -> CNHAccessTokenData? {
var result : CNHAccessTokenData? = nil
do {
let accountID = try keychain.get("accountID")
let access = try keychain.get("access")
let refresh = try keychain.get("refresh")
let type = try keychain.get("type")
let href = try keychain.get("href")
let expires = try keychain.get("expires")
let cognitoId = try keychain.get("cognitoId")
let cognitoToken = try keychain.get("cognitoToken")
if let id = accountID, let acc = access, let ref = refresh, let t = type, let url = href, let exp: NSString = expires,
let cid = cognitoId, let cogToken = cognitoToken {
let timestamp = NSDate(timeIntervalSince1970: exp.doubleValue )
result = CNHAccessTokenData(
accountID : id,
href : NSURL(string: url)!,
access : acc,
refresh : ref,
type : t,
expires : timestamp,
cognitoId : cid,
cognitoToken : cogToken
)
}
} catch {
// ...
}
return result
}
public func save(accessTokenData : CNHAccessTokenData) -> ErrorType? {
let expiresString = NSString(format: "%f", accessTokenData.expires.timeIntervalSince1970) as String
do {
try keychain.set(accessTokenData.accountID, key: "accountID")
try keychain.set(accessTokenData.access, key: "access")
try keychain.set(accessTokenData.refresh, key: "refresh")
try keychain.set(accessTokenData.type, key: "type")
try keychain.set(accessTokenData.href.absoluteString, key: "href")
try keychain.set(expiresString, key: "expires")
try keychain.set(accessTokenData.cognitoId, key: "cognitoId")
try keychain.set(accessTokenData.cognitoToken, key: "cognitoToken")
} catch let error {
print("error: \(error)")
return error
}
return nil
}
public func clear() {
do {
try keychain.removeAll()
} catch let error {
print("error: \(error)")
}
}
} | 96ad9ef0d907029da5cad16132300604 | 31.5 | 130 | 0.550676 | false | false | false | false |
huangboju/Moots | refs/heads/master | 优雅处理/Result-master/Result/Result.swift | mit | 1 | // Copyright (c) 2015 Rob Rix. All rights reserved.
/// An enum representing either a failure with an explanatory error, or a success with a result value.
public enum Result<T, Error: Swift.Error>: ResultProtocol, CustomStringConvertible, CustomDebugStringConvertible {
case success(T)
case failure(Error)
// MARK: Constructors
/// Constructs a success wrapping a `value`.
public init(value: T) {
self = .success(value)
}
/// Constructs a failure wrapping an `error`.
public init(error: Error) {
self = .failure(error)
}
/// Constructs a result from an `Optional`, failing with `Error` if `nil`.
public init(_ value: T?, failWith: @autoclosure () -> Error) {
self = value.map(Result.success) ?? .failure(failWith())
}
/// Constructs a result from a function that uses `throw`, failing with `Error` if throws.
public init(_ f: @autoclosure () throws -> T) {
self.init(attempt: f)
}
/// Constructs a result from a function that uses `throw`, failing with `Error` if throws.
public init(attempt f: () throws -> T) {
do {
self = .success(try f())
} catch var error {
if Error.self == AnyError.self {
error = AnyError(error)
}
self = .failure(error as! Error)
}
}
// MARK: Deconstruction
/// Returns the value from `success` Results or `throw`s the error.
public func dematerialize() throws -> T {
switch self {
case let .success(value):
return value
case let .failure(error):
throw error
}
}
/// Case analysis for Result.
///
/// Returns the value produced by applying `ifFailure` to `failure` Results, or `ifSuccess` to `success` Results.
public func analysis<Result>(ifSuccess: (T) -> Result, ifFailure: (Error) -> Result) -> Result {
switch self {
case let .success(value):
return ifSuccess(value)
case let .failure(value):
return ifFailure(value)
}
}
// MARK: Errors
/// The domain for errors constructed by Result.
public static var errorDomain: String { return "com.antitypical.Result" }
/// The userInfo key for source functions in errors constructed by Result.
public static var functionKey: String { return "\(errorDomain).function" }
/// The userInfo key for source file paths in errors constructed by Result.
public static var fileKey: String { return "\(errorDomain).file" }
/// The userInfo key for source file line numbers in errors constructed by Result.
public static var lineKey: String { return "\(errorDomain).line" }
/// Constructs an error.
public static func error(_ message: String? = nil, function: String = #function, file: String = #file, line: Int = #line) -> NSError {
var userInfo: [String: Any] = [
functionKey: function,
fileKey: file,
lineKey: line,
]
if let message = message {
userInfo[NSLocalizedDescriptionKey] = message
}
return NSError(domain: errorDomain, code: 0, userInfo: userInfo)
}
// MARK: CustomStringConvertible
public var description: String {
return analysis(
ifSuccess: { ".success(\($0))" },
ifFailure: { ".failure(\($0))" })
}
// MARK: CustomDebugStringConvertible
public var debugDescription: String {
return description
}
}
// MARK: - Derive result from failable closure
public func materialize<T>(_ f: () throws -> T) -> Result<T, AnyError> {
return materialize(try f())
}
public func materialize<T>(_ f: @autoclosure () throws -> T) -> Result<T, AnyError> {
do {
return .success(try f())
} catch {
return .failure(AnyError(error))
}
}
// MARK: - Cocoa API conveniences
#if !os(Linux)
/// Constructs a `Result` with the result of calling `try` with an error pointer.
///
/// This is convenient for wrapping Cocoa API which returns an object or `nil` + an error, by reference. e.g.:
///
/// Result.try { NSData(contentsOfURL: URL, options: .dataReadingMapped, error: $0) }
public func `try`<T>(_ function: String = #function, file: String = #file, line: Int = #line, `try`: (NSErrorPointer) -> T?) -> Result<T, NSError> {
var error: NSError?
return `try`(&error).map(Result.success) ?? .failure(error ?? Result<T, NSError>.error(function: function, file: file, line: line))
}
/// Constructs a `Result` with the result of calling `try` with an error pointer.
///
/// This is convenient for wrapping Cocoa API which returns a `Bool` + an error, by reference. e.g.:
///
/// Result.try { NSFileManager.defaultManager().removeItemAtURL(URL, error: $0) }
public func `try`(_ function: String = #function, file: String = #file, line: Int = #line, `try`: (NSErrorPointer) -> Bool) -> Result<(), NSError> {
var error: NSError?
return `try`(&error) ?
.success(())
: .failure(error ?? Result<(), NSError>.error(function: function, file: file, line: line))
}
#endif
// MARK: - ErrorProtocolConvertible conformance
extension NSError: ErrorProtocolConvertible {
public static func error(from error: Swift.Error) -> Self {
func cast<T: NSError>(_ error: Swift.Error) -> T {
return error as! T
}
return cast(error)
}
}
// MARK: - Errors
/// An “error” that is impossible to construct.
///
/// This can be used to describe `Result`s where failures will never
/// be generated. For example, `Result<Int, NoError>` describes a result that
/// contains an `Int`eger and is guaranteed never to be a `failure`.
public enum NoError: Swift.Error, Equatable {
public static func ==(lhs: NoError, rhs: NoError) -> Bool {
return true
}
}
/// A type-erased error which wraps an arbitrary error instance. This should be
/// useful for generic contexts.
public struct AnyError: Swift.Error {
/// The underlying error.
public let error: Swift.Error
public init(_ error: Swift.Error) {
if let anyError = error as? AnyError {
self = anyError
} else {
self.error = error
}
}
}
extension AnyError: ErrorProtocolConvertible {
public static func error(from error: Error) -> AnyError {
return AnyError(error)
}
}
extension AnyError: CustomStringConvertible {
public var description: String {
return String(describing: error)
}
}
// There appears to be a bug in Foundation on Linux which prevents this from working:
// https://bugs.swift.org/browse/SR-3565
// Don't forget to comment the tests back in when removing this check when it's fixed!
#if !os(Linux)
extension AnyError: LocalizedError {
public var errorDescription: String? {
return error.localizedDescription
}
public var failureReason: String? {
return (error as? LocalizedError)?.failureReason
}
public var helpAnchor: String? {
return (error as? LocalizedError)?.helpAnchor
}
public var recoverySuggestion: String? {
return (error as? LocalizedError)?.recoverySuggestion
}
}
#endif
// MARK: - migration support
@available(*, unavailable, message: "Use the overload which returns `Result<T, AnyError>` instead")
public func materialize<T>(_ f: () throws -> T) -> Result<T, NSError> {
fatalError()
}
@available(*, unavailable, message: "Use the overload which returns `Result<T, AnyError>` instead")
public func materialize<T>(_ f: @autoclosure () throws -> T) -> Result<T, NSError> {
fatalError()
}
// MARK: -
import Foundation
| d31a4727421f99ca21b0e00790290b05 | 27.857143 | 148 | 0.689675 | false | false | false | false |
zacwest/ZSWTappableLabel | refs/heads/master | Example/ZSWTappableLabel/Data detectors/DataDetectorsSwiftViewController.swift | mit | 1 | //
// DataDetectorsSwiftViewController.swift
// ZSWTappableLabel
//
// Created by Zachary West on 12/19/15.
// Copyright © 2019 Zachary West. All rights reserved.
//
import UIKit
import ZSWTappableLabel
import ZSWTaggedString
import SafariServices
class DataDetectorsSwiftViewController: UIViewController, ZSWTappableLabelTapDelegate {
let label: ZSWTappableLabel = {
let label = ZSWTappableLabel()
label.adjustsFontForContentSizeCategory = true
return label
}()
static let TextCheckingResultAttributeName = NSAttributedString.Key(rawValue: "TextCheckingResultAttributeName")
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
label.tapDelegate = self
let string = "check google.com or call 415-555-5555? how about friday at 5pm?"
let detector = try! NSDataDetector(types: NSTextCheckingAllSystemTypes)
let attributedString = NSMutableAttributedString(string: string, attributes: [
.font: UIFont.preferredFont(forTextStyle: .body),
])
let range = NSRange(location: 0, length: (string as NSString).length)
detector.enumerateMatches(in: attributedString.string, options: [], range: range) { (result, flags, _) in
guard let result = result else { return }
var attributes = [NSAttributedString.Key: Any]()
attributes[.tappableRegion] = true
attributes[.tappableHighlightedBackgroundColor] = UIColor.lightGray
attributes[.tappableHighlightedForegroundColor] = UIColor.white
attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue
attributes[DataDetectorsSwiftViewController.TextCheckingResultAttributeName] = result
attributedString.addAttributes(attributes, range: result.range)
}
label.attributedText = attributedString
view.addSubview(label)
label.snp.makeConstraints { make in
make.edges.equalTo(view)
}
}
// MARK: - ZSWTappableLabelTapDelegate
func tappableLabel(_ tappableLabel: ZSWTappableLabel, tappedAt idx: Int, withAttributes attributes: [NSAttributedString.Key : Any]) {
var URL: URL?
if let result = attributes[DataDetectorsSwiftViewController.TextCheckingResultAttributeName] as? NSTextCheckingResult {
switch result.resultType {
case [.address]:
print("Address components: \(String(describing: result.addressComponents))")
case [.phoneNumber]:
var components = URLComponents()
components.scheme = "tel"
components.host = result.phoneNumber
URL = components.url
case [.date]:
print("Date: \(String(describing: result.date))")
case [.link]:
URL = result.url
default:
break
}
}
if let URL = URL {
if let scheme = URL.scheme?.lowercased(), ["http", "https"].contains(scheme) {
show(SFSafariViewController(url: URL), sender: self)
} else {
UIApplication.shared.open(URL, options: [:], completionHandler: nil)
}
}
}
}
| 43f070e33c47482a74f3dd3943cf9c5b | 37.375 | 137 | 0.624519 | false | false | false | false |
ReactKit/ReactKit | refs/heads/master | ReactKit/Stream+Conversion.swift | apache-2.0 | 2 | //
// Stream+Conversion.swift
// ReactKit
//
// Created by Yasuhiro Inami on 2015/01/08.
// Copyright (c) 2015年 Yasuhiro Inami. All rights reserved.
//
import Foundation
import SwiftTask
/// converts Stream<T> to Stream<U>
public func asStream<T, U>(type: U.Type)(upstream: Stream<T>) -> Stream<U>
{
let stream = upstream |> map { $0 as! U }
stream.name("\(upstream.name) |> asStream(\(type))")
return stream
}
/// converts Stream<T> to Stream<U?>
public func asStream<T, U>(type: U?.Type)(upstream: Stream<T>) -> Stream<U?>
{
let stream = upstream |> map { $0 as? U }
stream.name("\(upstream.name) |> asStream(\(type))")
return stream
}
public extension Stream
{
//--------------------------------------------------
/// MARK: - From SwiftTask
//--------------------------------------------------
///
/// Converts `Task<P, V, E>` to `Stream<V>`.
///
/// Task's fulfilled-value (`task.value`) will be interpreted as stream's progress-value (`stream.progress`),
/// and any task's progress-values (`task.progress`) will be discarded.
///
public class func fromTask<P, V, E>(task: Task<P, V, E>) -> Stream<V>
{
return Stream<V> { progress, fulfill, reject, configure in
task.then { value, errorInfo -> Void in
if let value = value {
progress(value)
fulfill()
}
else if let errorInfo = errorInfo {
if let error = errorInfo.error as? NSError {
reject(error)
}
else {
let error = _RKError(.RejectedByInternalTask, "`task` is rejected/cancelled while `Stream.fromTask(task)`.")
reject(error)
}
}
}
configure.pause = {
task.pause()
return
}
configure.resume = {
task.resume()
return
}
configure.cancel = {
task.cancel()
return
}
}.name("Stream.fromTask(\(task.name))")
}
///
/// Converts `Task<P, V, E>` to `Stream<(P?, V?)>`.
///
/// Both task's progress-values (`task.progress`) and fulfilled-value (`task.value`)
/// will be interpreted as stream's progress-value (`stream.progress`),
/// so unlike `Stream.fromTask(_:)`, all `task.progress` will NOT be discarded.
///
public class func fromProgressTask<P, V, E>(task: Task<P, V, E>) -> Stream<(P?, V?)>
{
return Stream<(P?, V?)> { progress, fulfill, reject, configure in
task.progress { _, progressValue in
progress(progressValue, nil)
}.then { [weak task] value, errorInfo -> Void in
if let value = value {
progress(task!.progress, value)
fulfill()
}
else if let errorInfo = errorInfo {
if let error = errorInfo.error as? NSError {
reject(error)
}
else {
let error = _RKError(.RejectedByInternalTask, "`task` is rejected/cancelled while `Stream.fromProgressTask(task)`.")
reject(error)
}
}
}
configure.pause = {
task.pause()
return
}
configure.resume = {
task.resume()
return
}
configure.cancel = {
task.cancel()
return
}
}.name("Stream.fromProgressTask(\(task.name))")
}
} | 895ce9b914ab0a398bbeb25f02628941 | 31.00813 | 140 | 0.453506 | false | true | false | false |
13983441921/ios-charts | refs/heads/master | Charts/Classes/Data/ChartDataEntry.swift | apache-2.0 | 5 | //
// ChartDataEntry.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class ChartDataEntry: NSObject, Equatable
{
/// the actual value (y axis)
public var value = Float(0.0)
/// the index on the x-axis
public var xIndex = Int(0)
/// optional spot for additional data this Entry represents
public var data: AnyObject?
public override init()
{
super.init();
}
public init(value: Float, xIndex: Int)
{
super.init();
self.value = value;
self.xIndex = xIndex;
}
public init(value: Float, xIndex: Int, data: AnyObject?)
{
super.init();
self.value = value;
self.xIndex = xIndex;
self.data = data;
}
// MARK: NSObject
public override func isEqual(object: AnyObject?) -> Bool
{
if (object === nil)
{
return false;
}
if (!object!.isKindOfClass(self.dynamicType))
{
return false;
}
if (object!.data !== data && !object!.data.isEqual(self.data))
{
return false;
}
if (object!.xIndex != xIndex)
{
return false;
}
if (fabsf(object!.value - value) > 0.00001)
{
return false;
}
return true;
}
// MARK: NSObject
public override var description: String
{
return "ChartDataEntry, xIndex: \(xIndex), value \(value)";
}
// MARK: NSCopying
public func copyWithZone(zone: NSZone) -> AnyObject
{
var copy = self.dynamicType.allocWithZone(zone) as ChartDataEntry;
copy.value = value;
copy.xIndex = xIndex;
copy.data = data;
return copy;
}
}
public func ==(lhs: ChartDataEntry, rhs: ChartDataEntry) -> Bool
{
if (lhs === rhs)
{
return true;
}
if (!lhs.isKindOfClass(rhs.dynamicType))
{
return false;
}
if (lhs.data !== rhs.data && !lhs.data!.isEqual(rhs.data))
{
return false;
}
if (lhs.xIndex != rhs.xIndex)
{
return false;
}
if (fabsf(lhs.value - rhs.value) > 0.00001)
{
return false;
}
return true;
} | cd0babb6e8757d97ea4d979b0bda8dec | 18.883721 | 74 | 0.517161 | false | false | false | false |
cpmpercussion/microjam | refs/heads/develop | chirpey/WorldJamsTableViewController.swift | mit | 1 | //
// WorldJamsTableViewController.swift
// microjam
//
// Created by Charles Martin on 3/2/17.
// Copyright © 2017 Charles Martin. All rights reserved.
//
import UIKit
import CloudKit
/// A UITableViewController for displaying MicroJams downloaded from the CloudKit feed - first screen in the app!
class WorldJamsTableViewController: UITableViewController {
/// Local reference to the performanceStore singleton.
let performanceStore = PerformanceStore.shared
/// Global ID for wordJamCells.
let worldJamCellIdentifier = "worldJamCell"
/// Local reference to the PerformerProfileStore.
let profilesStore = PerformerProfileStore.shared
/// UILabel as a header view for warning messages.
let headerView = NoAccountWarningStackView()
/// A list of currently playing ChirpPlayers.
var players = [ChirpPlayer]()
/// A record of the currently playing table cell.
var currentlyPlaying: PerformanceTableCell?
// MARK: - Lifecycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setColourTheme()
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 420 // iPhone 7 height
performanceStore.delegate = self
headerView.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: 100) // header view used to display iCloud errors
// Initialise the refreshControl
self.refreshControl?.addTarget(performanceStore, action: #selector(performanceStore.fetchWorldJamsFromCloud), for: UIControl.Event.valueChanged)
tableView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tableViewTapped)))
tableView.separatorStyle = .none // Remove the separator
NotificationCenter.default.addObserver(self, selector: #selector(updateProfilesInCells), name: .performerProfileUpdated, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(setColourTheme), name: .setColourTheme, object: nil) // notification for colour theme.
}
deinit {
NotificationCenter.default.removeObserver(self, name: .performerProfileUpdated, object: nil)
NotificationCenter.default.removeObserver(self, name: .setColourTheme, object: nil)
}
// Action if a play button is pressed in a cell
@objc func playButtonPressed(sender: UIButton) {
let indexPath = IndexPath(row: sender.tag, section: 0)
if let cell = tableView.cellForRow(at: indexPath) as? PerformanceTableCell,
let player = cell.player {
if !player.isPlaying {
currentlyPlaying = cell
player.play()
cell.playButton.setImage(#imageLiteral(resourceName: "microjam-pause"), for: .normal)
} else {
currentlyPlaying = nil
player.stop()
cell.playButton.setImage(#imageLiteral(resourceName: "microjam-play"), for: .normal)
}
}
}
// Action if a reply button is pressed in a cell
@objc func replyButtonPressed(sender: UIButton) {
let indexPath = IndexPath(row: sender.tag, section: 0)
if let cell = tableView.cellForRow(at: indexPath) as? PerformanceTableCell,
let player = cell.player {
if let current = currentlyPlaying {
current.player!.stop()
current.playButton.setImage(#imageLiteral(resourceName: "microjam-play"), for: .normal)
currentlyPlaying = nil
}
let controller = ChirpJamViewController.instantiateReplyController(forPlayer: player)
navigationController?.pushViewController(controller, animated: true)
controller.title = "Reply" // set the navigation bar title.
}
}
/// Action when the plus bar item button is pressed.
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
print("Add Button Pressed")
tabBarController?.selectedIndex = 1 // go to the second tab (jam!)
}
/// Visit each available table view cell and make sure it is displaying the correct profile information after an update.
@objc func updateProfilesInCells() {
//print("WJTVC: Received a profile update, making sure visible cells are up to date.")
for cell in tableView.visibleCells {
if let cell = cell as? PerformanceTableCell {
cell.displayProfileFromPlayer()
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return performanceStore.feed.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: worldJamCellIdentifier, for: indexPath) as! PerformanceTableCell
cell.avatarImageView.image = #imageLiteral(resourceName: "empty-profile-image") // set avatar image view to the empty one early to avoid wrong images.
let performance = performanceStore.feed[indexPath.row]
cell.player = ChirpPlayer()
cell.player?.delegate = self
cell.setColourTheme() // set colour theme if reloading.
// Get all replies and add them to the player and chirp container.
// TODO: Maybe the cell can do this for itself.
let performanceChain = performanceStore.getAllReplies(forPerformance: performance)
for perfItem in performanceChain {
let chirpView = ChirpView(with: cell.chirpContainer.bounds, andPerformance: perfItem)
cell.chirpContainer.backgroundColor = perfItem.backgroundColour.darkerColor
cell.player!.chirpViews.append(chirpView)
cell.chirpContainer.addSubview(chirpView)
}
// Add constraints for cell.chirpContainer's subviews.
for view in cell.chirpContainer.subviews {
view.translatesAutoresizingMaskIntoConstraints = false
view.constrainEdgesTo(cell.chirpContainer)
}
/// Setup the metadata area.
if let profile = profilesStore.getProfile(forPerformance: performance) {
cell.display(performerProfile: profile)
} else {
//cell.avatarImageView.image = nil
if performance.performer == UserProfile.shared.profile.stageName {
cell.avatarImageView.image = UserProfile.shared.profile.avatar
}
cell.performer.text = performance.performer
}
cell.title.text = performance.dateString
cell.instrument.text = performance.instrument
cell.context.text = nonCreditString(forDate: performance.date)
cell.playButton.tag = indexPath.row
cell.playButton.addTarget(self, action: #selector(playButtonPressed), for: .touchUpInside)
cell.playButton.setImage(#imageLiteral(resourceName: "microjam-play"), for: .normal)
cell.replyButton.tag = indexPath.row
cell.replyButton.addTarget(self, action: #selector(replyButtonPressed), for: .touchUpInside)
return cell
}
// MARK: UI Methods
@objc func tableViewTapped(sender: UIGestureRecognizer) {
let location = sender.location(in: tableView)
if let indexPath = tableView.indexPathForRow(at: location) {
// Find out which cell was tapped
if let cell = tableView.cellForRow(at: indexPath) as? PerformanceTableCell {
// get performance from that cell
let performance = performanceStore.feed[indexPath.row]
// Tapped the avatar imageview
if cell.avatarImageView.frame.contains(sender.location(in: cell.avatarImageView)) {
// Show user performances
let layout = UICollectionViewFlowLayout()
let controller = UserPerfController(collectionViewLayout: layout)
controller.performer = performance.performer
controller.performerID = performance.creatorID
navigationController?.pushViewController(controller, animated: true)
// Tapped the preview image
}
}
}
}
/// Adds multiple images on top of each other
func createImageFrom(images : [UIImage]) -> UIImage? {
if let size = images.first?.size {
UIGraphicsBeginImageContext(size)
let areaSize = CGRect(x: 0, y: 0, width:size.width, height: size.height)
for image in images.reversed() {
image.draw(in: areaSize, blendMode: CGBlendMode.normal, alpha: 1.0)
}
let outImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return outImage
}
return nil
}
/// Loads a string crediting the original performer
func creditString(originalPerformer: String) -> String {
let output = "replied to " + originalPerformer
return output
}
/// Loads a credit string for a solo performance, uses the performance date to choose a string consistently.
func nonCreditString(forDate date: Date) -> String {
let integerInterval = Int(date.timeIntervalSince1970)
let ind : Int = integerInterval % PerformanceLabels.solo.count
return PerformanceLabels.solo[ind]
}
// MARK: - Navigation
/// Segue to view loaded jams.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
}
/// Segue back to the World Jam Table
@IBAction func unwindToJamList(sender: UIStoryboardSegue) {
}
/// Adds a new ChirpPerformance to the top of the list and saves it in the data source.
func addNew(performance: ChirpPerformance) {
let newIndexPath = NSIndexPath(row: 0, section: 0)
performanceStore.addNew(performance: performance)
self.tableView.insertRows(at: [newIndexPath as IndexPath], with: .top)
}
}
extension WorldJamsTableViewController: PlayerDelegate {
func playbackStarted() {
// not used
}
func playbackStep(_ time: Double) {
// not used
}
func playbackEnded() {
if let cell = currentlyPlaying {
cell.player!.stop()
cell.playButton.setImage(#imageLiteral(resourceName: "microjam-play"), for: .normal)
currentlyPlaying = nil
}
}
}
// MARK: - Scroll view delegate methods
extension WorldJamsTableViewController {
override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if let cell = currentlyPlaying {
cell.playButton.setImage(#imageLiteral(resourceName: "microjam-play"), for: .normal)
cell.player!.stop()
currentlyPlaying = nil
}
}
}
// MARK: - ModelDelegate methods
extension WorldJamsTableViewController: ModelDelegate {
/// Conforms to ModelDelegate Protocol
func modelUpdated() {
refreshControl?.endRefreshing()
tableView.tableHeaderView = nil
// Maybe stop, not sure if right to do this.
tableView.reloadData()
}
/// Conforms to ModelDelegate Protocol
func errorUpdating(error: NSError) {
print("WJTVC: Model could not be updated.")
refreshControl?.endRefreshing()
tableView.tableHeaderView = headerView
let message: String
if error.code == 1 {
message = ErrorDialogues.icloudNotLoggedIn
} else {
message = error.localizedDescription
}
headerView.warningLabel.text = message
headerView.isHidden = false
}
}
// Set up dark and light mode.
extension WorldJamsTableViewController {
@objc func setColourTheme() {
UserDefaults.standard.bool(forKey: SettingsKeys.darkMode) ? setDarkMode() : setLightMode()
// set colour for visible table view cells.
for cell in self.tableView.visibleCells {
if let cell = cell as? PerformanceTableCell {
cell.setColourTheme()
}
}
}
func setDarkMode() {
view.backgroundColor = DarkMode.background
navigationController?.navigationBar.barStyle = .black
navigationController?.navigationBar.tintColor = DarkMode.highlight
navigationController?.view.backgroundColor = DarkMode.background
}
func setLightMode() {
view.backgroundColor = LightMode.background
navigationController?.navigationBar.barStyle = .default
navigationController?.navigationBar.tintColor = LightMode.highlight
navigationController?.view.backgroundColor = LightMode.background
}
}
| 13742dce024a0208c9103613e88ec94f | 39.495385 | 159 | 0.66036 | false | false | false | false |
svyatoslav-zubrin/CustomSolutions | refs/heads/master | CustomSolutions/UniversalRefreshControl/FRYMoonActivityIndicator.swift | mit | 1 | //
// FRYMoonLoadingIndicator.swift
// EmoWork
//
// Created by Slava Zubrin on 5/18/17.
// Copyright © 2017 Peder Nordvaller. All rights reserved.
//
import UIKit
class FRYMoonActivityIndicator: UIView {
// Public
var colors: [UIColor] = [.red,
.orange,
.yellow,
.green,
.blue]
{
didSet {
moonView.colors = colors
}
}
var animating: Bool = false {
didSet {
moonView.animating = animating
}
}
// Private
fileprivate var moonView: FRYMoonView!
fileprivate var imageView: UIImageView!
// Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
// animated moon view
moonView = FRYMoonView(frame: bounds)
moonView.colors = colors
if let fillColor = colors.last {
moonView.fillBackgroundColor = fillColor
}
moonView.autoresizingMask = [.flexibleBottomMargin,
.flexibleTopMargin,
.flexibleLeftMargin,
.flexibleRightMargin]
moonView.translatesAutoresizingMaskIntoConstraints = true
addSubview(moonView)
// image view
imageView = UIImageView()
imageView.image = UIImage(named: "and")
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(imageView)
NSLayoutConstraint(item: imageView,
attribute: .centerX,
relatedBy: .equal,
toItem: self,
attribute: .centerX,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: imageView,
attribute: .centerY,
relatedBy: .equal,
toItem: self,
attribute: .centerY,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: imageView,
attribute: .width,
relatedBy: .equal,
toItem: self,
attribute: .width,
multiplier: 0.6,
constant: 0).isActive = true
NSLayoutConstraint(item: imageView,
attribute: .height,
relatedBy: .equal,
toItem: self,
attribute: .height,
multiplier: 0.6,
constant: 0).isActive = true
}
}
| a834abeae7bbd6ec9f445cbd309db610 | 30.360825 | 67 | 0.465483 | false | false | false | false |
brentsimmons/Frontier | refs/heads/master | BeforeTheRename/FrontierVerbs/FrontierVerbs/VerbTables/SysVerbs.swift | gpl-2.0 | 1 | //
// SysVerbs.swift
// FrontierVerbs
//
// Created by Brent Simmons on 4/15/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import FrontierData
struct SysVerbs: VerbTable {
private enum Verb: String {
case osVersion = "osversion"
case systemTask = "systemtask"
case browseNetwork = "browsenetwork"
case appIsRunning = "appisrunning"
case frontmostApp = "frontmostapp"
case bringAppToFront = "bringapptofront"
case countApps = "countapps"
case getNthApp = "getnthapp"
case getAppPath = "getapppath"
case memAvail = "memavail"
case machine = "machine"
case os = "os"
case getEnvironmentVariable = "getenvironmentvariable"
case setEnvironmentVariable = "setenvironmentvariable"
case unixShellCommand = "unixshellcommand"
case winShellCommand = "winshellCommand"
}
static func evaluate(_ lowerVerbName: String, _ params: VerbParams, _ verbAppDelegate: VerbAppDelegate) throws -> Value {
guard let verb = Verb(rawValue: lowerVerbName) else {
throw LangError(.verbNotFound)
}
do {
switch verb {
case .osVersion:
return try osVersion(params)
case .systemTask:
return true
case .browseNetwork:
return try browseNetwork(params)
case .appIsRunning:
return try appIsRunning(params)
case .frontmostApp:
return try frontmostApp(params)
case .bringAppToFront:
return try bringAppToFront(params)
case .countApps:
return try countApps(params)
case .getNthApp:
return try getNthApp(params)
case .getAppPath:
return try getAppPath(params)
case .memAvail:
return Int.max
case .machine:
return try machine(params)
case .os:
return try os(params)
case .getEnvironmentVariable:
return try getEnvironmentVariable(params)
case .setEnvironmentVariable:
return try setEnvironmentVariable(params)
case .unixShellCommand:
return try unixShellCommand(params)
case .winShellCommand:
return false
}
}
catch { throw error }
}
}
private extension SysVerbs {
static func osVersion(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func browseNetwork(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func appIsRunning(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func frontmostApp(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func bringAppToFront(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func countApps(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getNthApp(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getAppPath(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func machine(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func os(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getEnvironmentVariable(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func setEnvironmentVariable(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func unixShellCommand(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
}
| 7082e0ee783b9d93395e2689d4c60824 | 23.054795 | 122 | 0.717255 | false | false | false | false |
abecker3/SeniorDesignGroup7 | refs/heads/master | ProvidenceWayfinding/ProvidenceWayfinding/FloorPlansViewController.swift | apache-2.0 | 1 | //
// FloorPlansViewController.swift
// ProvidenceWayfinding
//
// Created by Andrew Becker on 1/26/16.
// Copyright © 2016 GU. All rights reserved.
//
import UIKit
class FloorPlansViewController: UIViewController {
@IBOutlet weak var floorMap: UIImageView!
@IBOutlet weak var scrollMap: UIScrollView!
@IBOutlet weak var textTitle: UITextField!
@IBOutlet weak var buildingWomens: UIButton!
@IBOutlet weak var buildingChildrens: UIButton!
@IBOutlet weak var buildingHeart: UIButton!
@IBOutlet weak var buildingMain: UIButton!
@IBOutlet weak var floorL3: UIButton!
@IBOutlet weak var floorL2: UIButton!
@IBOutlet weak var floorL1: UIButton!
@IBOutlet weak var floor1: UIButton!
@IBOutlet weak var floor2: UIButton!
@IBOutlet weak var floor3: UIButton!
@IBOutlet weak var floor4: UIButton!
@IBOutlet weak var floor5: UIButton!
@IBOutlet weak var floor6: UIButton!
@IBOutlet weak var floor7: UIButton!
@IBOutlet weak var floor8: UIButton!
@IBOutlet weak var floor9: UIButton!
@IBOutlet weak var floor10: UIButton!
var building = String()
var floor = String()
var underscore = String()
var fileExtension = String()
var textBuilding = String()
var imageName = String()
override func viewDidLoad() {
super.viewDidLoad()
underscore = "_"
fileExtension = ".jpg"
initialize()
self.scrollMap.maximumZoomScale = 5.0
self.scrollMap.clipsToBounds = true
let tap = UITapGestureRecognizer(target: self, action: "doubleTapped")
tap.numberOfTapsRequired = 2
view.addGestureRecognizer(tap)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.floorMap
}
func setButtons(a: Bool,b: Bool,c: Bool,d: Bool,e: Bool,f: Bool,g: Bool,h: Bool,i: Bool,j: Bool, k: Bool, l: Bool, m: Bool){
floorL3.enabled = a
floorL2.enabled = b
floorL1.enabled = c
floor1.enabled = d
floor2.enabled = e
floor3.enabled = f
floor4.enabled = g
floor5.enabled = h
floor6.enabled = i
floor7.enabled = j
floor8.enabled = k
floor9.enabled = l
floor10.enabled = m
}
func initialize(){
building = "Main"
floor = "1"
textBuilding = "Main Tower"
setButtons(true, b: true, c: true, d: true, e: true, f: true, g: true, h: true, i: true, j: true, k: true, l: true, m: true)
textTitle.text = textBuilding + " Floor " + floor
imageName = building + underscore + floor + fileExtension
floorMap.image = UIImage(named: imageName)
floorMap.contentMode = UIViewContentMode.ScaleAspectFit
}
@IBAction func mainPressed(sender: UIButton) {
building = "Main"
floor = "1"
textBuilding = "Main Tower"
setButtons(true, b: true, c: true, d: true, e: true, f: true, g: true, h: true, i: true, j: true, k: true, l: true, m: true)
textTitle.text = textBuilding + " Floor " + floor
imageName = building + underscore + floor + fileExtension
floorMap.image = UIImage(named: imageName)
floorMap.contentMode = UIViewContentMode.ScaleAspectFit
}
@IBAction func heartPressed(sender: UIButton) {
building = "Heart"
floor = "1"
textBuilding = "Heart Institute"
setButtons(false, b: false, c: false, d: true, e: true, f: true, g: true, h: true, i: false, j: false, k: false, l: false, m: false)
textTitle.text = textBuilding + " Floor " + floor
imageName = building + underscore + floor + fileExtension
floorMap.image = UIImage(named: imageName)
floorMap.contentMode = UIViewContentMode.ScaleAspectFit
}
@IBAction func childrensPressed(sender: UIButton) {
building = "Childrens"
floor = "1"
textBuilding = "Children's Hospital"
setButtons(true, b: true, c: true, d: true, e: true, f: true, g: true, h: false, i: false, j: false, k: false, l: false, m: false)
textTitle.text = textBuilding + " Floor " + floor
imageName = building + underscore + floor + fileExtension
floorMap.image = UIImage(named: imageName)
floorMap.contentMode = UIViewContentMode.ScaleAspectFit
}
@IBAction func womensPressed(sender: UIButton) {
building = "Womens"
floor = "1"
textBuilding = "Womens Health Center"
setButtons(true, b: true, c: true, d: true, e: true, f: true, g: false, h: false, i: false, j: false, k: false, l: false, m: false)
textTitle.text = textBuilding + " Floor " + floor
imageName = building + underscore + floor + fileExtension
floorMap.image = UIImage(named: imageName)
floorMap.contentMode = UIViewContentMode.ScaleAspectFit
}
@IBAction func floorPressed(sender: UIButton) {
switch sender{
case floorL3: floor = "L3"
case floorL2: floor = "L2"
case floorL1: floor = "L1"
case floor2: floor = "2"
case floor3: floor = "3"
case floor4: floor = "4"
case floor5: floor = "5"
case floor6: floor = "6"
case floor7: floor = "7"
case floor8: floor = "8"
case floor9: floor = "9"
case floor10: floor = "10"
default: floor = "1"
}
textTitle.text = textBuilding + " Floor " + floor
imageName = building + underscore + floor + fileExtension
floorMap.image = UIImage(named: imageName)
floorMap.contentMode = UIViewContentMode.ScaleAspectFit
}
func doubleTapped() {
if (scrollMap.zoomScale > 1){
scrollMap.setZoomScale(0.25, animated: true)
}
else{
scrollMap.setZoomScale(2, animated: true)
}
}
}
| 3fda7b771e9bdd94f378f1e22774ce98 | 35.216867 | 140 | 0.615602 | false | false | false | false |
vanyaland/Californication | refs/heads/master | Californication/App.swift | mit | 1 | /**
* Copyright (c) 2016 Ivan Magda
*
* 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
final class App {
// MARK: Instance Properties
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tabBarController: UITabBarController
let placeListViewController: PlaceListViewController
let mapViewController: MapViewController
let placeDirector: PlaceDirector
// MARK: - Init
init(_ window: UIWindow) {
let firebaseDirector = FirebaseDirector(
builder: FirebaseBuilderImpl(),
databaseManager: FirebaseManagerImpl(authManager: FirebaseAuthManagerImpl())
)
let googleMapsDirector = GoogleMapsDirector(networkManager: GoogleMapsNetworkManagerImpl())
placeDirector = PlaceDirector(
firebaseDirector: firebaseDirector,
googleMapsDirector: googleMapsDirector,
cacheManager: PlaceCacheManagerImpl()
)
tabBarController = window.rootViewController as! UITabBarController
mapViewController = tabBarController.viewControllers![1] as! MapViewController
mapViewController.placeDirector = placeDirector
let navigationController = tabBarController.viewControllers![0] as! UINavigationController
placeListViewController = navigationController.topViewController as! PlaceListViewController
placeListViewController.placeDirector = placeDirector
placeListViewController.didSelect = push(place:)
mapViewController.didSelect = present(place:)
}
// MARK: Navigation
func push(place: Place) {
let detailVC = placeDetailsViewController(with: place)
detailVC.title = "Detail"
placeListViewController.navigationController!.pushViewController(detailVC, animated: true)
}
func present(place: Place) {
let detailVC = placeDetailsViewController(with: place)
tabBarController.present(detailVC, animated: true, completion: nil)
}
fileprivate func placeDetailsViewController(with place: Place) -> PlaceDetailsViewController {
let controller = storyboard
.instantiateViewController(withIdentifier: "PlaceDetails") as! PlaceDetailsViewController
controller.place = place
return controller
}
}
| 988aab5d12458dc07c28f85dcab98082 | 37.590361 | 96 | 0.760225 | false | false | false | false |
nodes-ios/NStackSDK | refs/heads/master | NStackSDK/NStackSDK/Operators/Operator.swift | mit | 1 | //
// Operator.swift
// NStackSDK
//
// Created by Peter Bødskov on 29/07/2019.
// Copyright © 2019 Nodes ApS. All rights reserved.
//
import Foundation
infix operator <=>
/*
OK so we wan't to return the value from the translation manager, unless a local proposal exists
and we wan't to do so for the selected language
So label.text <=> tr.myvalue.myvalue = give me the string for "tr.myvalue.myvalue" for the current language
*/
public func <=> (left: NStackLocalizable, right: String) {
left.localize(for: right)
}
public func <=> (left: NStackLocalizable, right: TranslationIdentifier) {
NStack.sharedInstance.translationsManager?.localize(component: left, for: right)
}
| ea2efab805a03dfde91eea883e9ae8b4 | 25.769231 | 108 | 0.722701 | false | false | false | false |
hilen/TSVoiceConverter | refs/heads/master | TSVoiceConverterDemo/TSVoiceConverterDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// TSVoiceConverterDemo
//
// Created by Hilen on 3/29/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import UIKit
import TSVoiceConverter
let kAudioFileTypeWav = "wav"
let kAudioFileTypeAmr = "amr"
private let kAmrRecordFolder = "ChatAudioAmrRecord"
private let kWavRecordFolder = "ChatAudioWavRecord"
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let amrPath = Bundle.main.path(forResource: "hello", ofType: "amr")
let wavPath = Bundle.main.path(forResource: "count", ofType: "wav")
let amrTargetPath = AudioFolderManager.amrPathWithName("test_amr").path
let wavTargetPath = AudioFolderManager.wavPathWithName("test_wav").path
if TSVoiceConverter.convertAmrToWav(amrPath!, wavSavePath: wavTargetPath) {
print("wav path: \(wavTargetPath)")
} else {
print("convertAmrToWav error")
}
if TSVoiceConverter.convertWavToAmr(wavPath!, amrSavePath: amrTargetPath) {
print("amr path: \(amrTargetPath)")
} else {
print("convertWavToAmr error")
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class AudioFolderManager {
/**
Get the AMR file's full path
- parameter fileName: file name
- returns: Full path
*/
class func amrPathWithName(_ fileName: String) -> URL {
let filePath = self.amrFilesFolder.appendingPathComponent("\(fileName).\(kAudioFileTypeAmr)")
return filePath
}
/**
Get the WAV file's full path
- parameter fileName: file name
- returns: Full path
*/
class func wavPathWithName(_ fileName: String) -> URL {
let filePath = self.wavFilesFolder.appendingPathComponent("\(fileName).\(kAudioFileTypeWav)")
return filePath
}
/// Create AMR file record folder
fileprivate class var amrFilesFolder: URL {
get { return self.createAudioFolder(kAmrRecordFolder)}
}
/// Create WAV file record folder
fileprivate class var wavFilesFolder: URL {
get { return self.createAudioFolder(kWavRecordFolder)}
}
/// Create record folder
class fileprivate func createAudioFolder(_ folderName :String) -> URL {
let documentsDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
let folder = documentsDirectory.appendingPathComponent(folderName)
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: folder.absoluteString) {
do {
try fileManager.createDirectory(atPath: folder.path, withIntermediateDirectories: true, attributes: nil)
return folder
} catch let error as NSError {
print("error:\(error)")
}
}
return folder
}
}
| ef3699bfb38b2410e4862689f8739165 | 30.09901 | 120 | 0.641515 | false | false | false | false |
daniel-beard/Starlight | refs/heads/master | Starlight/Starlight.swift | mit | 1 | //
// Starlight.swift
// Starlight
//
// Created by Daniel Beard on 9/13/15.
// Copyright © 2015 DanielBeard. All rights reserved.
//
import Foundation
//MARK: Typealiases
public typealias Point = (x: Int, y: Int)
typealias Pair = (first: Double, second: Double)
typealias StateLinkedList = Array<State>
extension Array where Element == State {
mutating func addFirst(_ element: Element) {
guard !self.isEmpty else {
append(element)
return
}
insert(element, at: 0)
}
public var description: String {
return self.reduce("", { $0 + ("\($1)\n") })
}
}
private class PriorityQueue<T: Comparable> {
private var heap = [T]()
func push(item: T) {
heap.append(item)
heap.sort()
}
func pop() -> T {
return heap.removeFirst()
}
func peek() -> T {
return (heap.first)!
}
func isEmpty() -> Bool {
return heap.isEmpty
}
var count: Int {
return heap.count
}
}
struct CellInfo {
var g = 0.0
var rhs = 0.0
var cost = 0.0
}
public class Starlight {
//MARK: Private Properties
private var path = [State]()
private var k_m = 0.0
private var s_start = State()
private var s_goal = State()
private var s_last = State()
private var openList = PriorityQueue<State>()
private var cellHash = [State: CellInfo]()
private var openHash = [State: Double]()
//MARK: Constants
private let maxSteps = 80000
private var C1 = 1.0
init(start: Point, goal: Point) {
s_start.x = start.x
s_start.y = start.y
s_goal.x = goal.x
s_goal.y = goal.y
let goalCellInfo = CellInfo(g: 0.0, rhs: 0.0, cost: C1)
cellHash[s_goal] = goalCellInfo
let startHeuristic = heuristic(s_start, b: s_goal)
let startCellInfo = CellInfo(g: startHeuristic, rhs: startHeuristic, cost: C1)
cellHash[s_start] = startCellInfo
s_start = calculateKey(s_start)
s_last = s_start
}
//MARK: Private Methods
/// CalculateKey - > As per [S. Koenig, 2002]
private func calculateKey(_ u: State) -> State {
let val = min(getRHS(u), getG(u))
let first = (val + heuristic(u, b: s_start) + k_m)
let second = val
return State(x: u.x, y: u.y, k: Pair(first, second))
}
/// Returns the rhs value for the state u
private func getRHS(_ u: State) -> Double {
guard u != s_goal else {
return 0.0
}
guard let cellHashU = cellHash[u] else {
return heuristic(u, b: s_goal)
}
return cellHashU.rhs
}
/// As per [S. Koenig,2002] except for two main modifications:
/// 1. We stop planning after a number of steps, 'maxsteps' we do this
/// because this algorithm can plan forever if the start is surrounded by obstacles
/// 2. We lazily remove states from the open list so we never have to iterate through it.
private func computeShortestPath() -> Int {
if openList.isEmpty() { return 1 }
var k = 0
var s = StateLinkedList()
while !openList.isEmpty() {
// Update start
s_start = calculateKey(s_start)
// Bail if our conditions aren't met
guard (openList.peek() < s_start || getRHS(s_start) != getG(s_start)) else {
break
}
k += 1
if k > maxSteps {
print("At maxsteps")
return -1
}
var u = State()
let test = getRHS(s_start) != getG(s_start)
// Lazy remove
while (true) {
if openList.isEmpty() { return 1 }
u = openList.pop()
if !isValid(u) { continue }
if !(u < s_start) && !test { return 2 }
break
}
openHash[u] = nil
let k_old = State(state: u)
u = calculateKey(u)
if k_old < u { // u is out of date
insert(u)
} else if getG(u) > getRHS(u) { // needs update (got better)
setG(u, g: getRHS(u))
s = getPred(u)
for state in s {
updateVertex(state)
}
} else { // g <= rhs, state has got worse
setG(u, g: Double.infinity)
s = getPred(u)
for state in s {
updateVertex(state)
}
updateVertex(u)
}
s_start = calculateKey(s_start)
}
return 0
}
/// Helper method for generating a list of states around a current state
/// Moves in a clockwise manner
private func generateSuccessorStates(fromState u: State, k: Pair) -> [State] {
return [
State(x: u.x + 1, y: u.y, k: k),
State(x: u.x + 1, y: u.y + 1, k: k),
State(x: u.x, y: u.y + 1, k: k),
State(x: u.x - 1, y: u.y + 1, k: k),
State(x: u.x - 1, y: u.y, k: k),
State(x: u.x - 1, y: u.y - 1, k: k),
State(x: u.x, y: u.y - 1, k: k),
State(x: u.x + 1, y: u.y - 1, k: k),
]
}
/// Returns a list of successor states for state u, since this is an
/// 8-way graph this list contains all of a cells neighbours. Unless
/// the cell is occupied, in which case it has no successors.
private func getSucc(_ u: State) -> StateLinkedList {
var s = StateLinkedList()
if occupied(u) { return s }
// Generating the successors, starting at the immediate right,
// moving in a clockwise manner
// transform to StateLinkedList and return
let successors = generateSuccessorStates(fromState: u, k: (-1.0, -1.0))
successors.forEach { s.addFirst($0) }
return s
}
/// Returns a list of all the predecessor states for state u. Since
/// this is for an 8-way connected graph, the list contains all the
/// neighbours for state u. Occupied neighbours are not added to the list
private func getPred(_ u: State) -> StateLinkedList {
var s = StateLinkedList()
let successors = generateSuccessorStates(fromState: u, k: (-1.0, -1.0))
successors.forEach { if !occupied($0) { s.addFirst($0) }}
return s;
}
/// As per [S. Koenig, 2002]
private func updateVertex(_ u: State) {
var states = StateLinkedList()
if u != s_goal {
states = getSucc(u)
var tmp = Double.infinity
var tmp2 = 0.0
for state in states {
tmp2 = getG(state) + cost(u, b: state)
if tmp2 < tmp { tmp = tmp2 }
}
if !close(getRHS(u), y: tmp) { setRHS(u, rhs: tmp) }
}
if !close(getG(u), y: getRHS(u)) { insert(u) }
}
/// Returns true if state u is on the open list or not by checking if it is in the hash table.
private func isValid(_ u: State) -> Bool {
guard let openHashU = openHash[u] else {
return false
}
if !close(keyHashCode(u), y: openHashU) { return false }
return true
}
/// Returns the value for the state u
private func getG(_ u: State) -> Double {
guard let cellHashU = cellHash[u] else {
return heuristic(u, b: s_goal)
}
return cellHashU.g
}
/// The heuristic we use is the 8-way distance
/// scaled by a constant C1 (should be set to <= min cost
private func heuristic(_ a: State, b: State) -> Double {
return eightCondist(a, b) * C1
}
/// Returns the 8-way distance between state a and state b
private func eightCondist(_ a: State, _ b: State) -> Double {
var min = Double(abs(a.x - b.x))
var max = Double(abs(a.y - b.y))
if min > max {
swap(&min, &max)
}
return (2.squareRoot() - 1.0) * min + max
}
/// Inserts state into openList and openHash
private func insert(_ u: State) {
let u = calculateKey(u)
let csum = keyHashCode(u)
openHash[u] = csum
openList.push(item: u)
}
/// Returns the key hash code for the state u, this is used to compare
/// a state that has been updated
private func keyHashCode(_ u: State) -> Double {
return Double(u.k.first + 1193 * u.k.second)
}
/// Returns true if the cell is occupied (non-traversable), false
/// otherwise. Non-traversable are marked with a cost < 0
private func occupied(_ u: State) -> Bool {
if let cell = cellHash[u] {
return (cell.cost < 0)
}
return false
}
/// Euclidean cost between state a and state b
private func trueDist(_ a: State, b: State) -> Double {
let x = Double(a.x - b.x)
let y = Double(a.y - b.y)
return sqrt(x * x + y * y)
}
/** Returns the cost of moving from state a to state b. This could be
either the cost of moving off state a or onto state b, we went with the
former. This is also the 8-way cost. */
private func cost(_ a: State, b: State) -> Double {
let xd = abs(a.x - b.x)
let yd = abs(a.y - b.y)
var scale = 1.0
if xd + yd > 1 { scale = 2.squareRoot() }
guard let cellHashA = cellHash[a] else {
return scale * C1
}
return scale * cellHashA.cost
}
/// Returns true if x and y are within 10E-5, false otherwise
private func close(_ x: Double, y: Double) -> Bool {
if x == Double.infinity && y == Double.infinity { return true }
return abs(x - y) < 0.00001
}
/// Sets the G value for state u
private func setG(_ u: State, g: Double) {
makeNewCell(u)
cellHash[u]!.g = g
}
/// Sets the rhs value for state u
private func setRHS(_ u: State, rhs: Double) {
makeNewCell(u)
cellHash[u]!.rhs = rhs
}
/// Checks if a cell is in the hash table, if not it adds it in.
private func makeNewCell(_ u: State) {
guard cellHash[u] == nil else { return }
let heuristicValue = heuristic(u, b: s_goal)
let cellInfo = CellInfo(g: heuristicValue, rhs: heuristicValue, cost: C1)
cellHash[u] = cellInfo
}
//MARK: Public Methods
public func replan() -> Bool {
path.removeAll()
let res = computeShortestPath()
if res < 0 {
print("No path to goal")
return false
}
var n = StateLinkedList()
var cur = s_start
if getG(s_start) == Double.infinity {
print("No path to goal")
return false
}
while (cur != s_goal) {
path.append(cur)
n = StateLinkedList()
n = getSucc(cur)
if n.isEmpty {
print("No path to goal")
return false
}
var cmin = Double.infinity
var tmin = 0.0
var smin = State()
for state in n {
var val = cost(cur, b: state)
let val2 = trueDist(state, b: s_goal) + trueDist(s_start, b: state)
val += getG(state)
if close(val, y: cmin) {
if tmin > val2 {
tmin = val2
cmin = val
smin = state
}
} else if val < cmin {
tmin = val2
cmin = val
smin = state
}
}
n.removeAll()
cur = State(state: smin)
}
path.append(s_goal)
return true
}
/// Update the position of the agent/robot.
/// This does not force a replan.
public func updateStart(x: Int, y: Int) {
s_start.x = x
s_start.y = y
k_m += heuristic(s_last, b: s_start)
s_start = calculateKey(s_start)
s_last = s_start
}
public func updateGoal(x: Int, y: Int) {
//TODO: Implement this
fatalError("Not implemented")
}
/// updateCell as per [S. Koenig, 2002]
public func updateCell(x: Int, y: Int, value: Double) {
var u = State()
u.x = x; u.y = y
if u == s_start || u == s_goal {
return
}
makeNewCell(u)
cellHash[u]!.cost = value
updateVertex(u)
}
public func getPath() -> [State] {
return self.path
}
}
public struct State: Hashable, Comparable, CustomStringConvertible {
var x = 0
var y = 0
var k = Pair(0.0, 0.0)
init() { }
init(x: Int, y: Int, k: Pair) {
self.x = x
self.y = y
self.k = k
}
init(state: State) {
x = state.x
y = state.y
k = state.k
}
public var hashValue: Int {
get { return x + 34245 * y }
}
public var description: String {
get { return "x: \(x) y: \(y)\n" }
}
}
public func ==(lhs: State, rhs: State) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
public func <(lhs: State, rhs: State) -> Bool {
let delta = 0.000001
if lhs.k.first + delta < rhs.k.first {
return true
} else if lhs.k.first - delta > rhs.k.first {
return false
}
return lhs.k.second < rhs.k.second
}
| 393e387c38f79f96f071df3a66536478 | 28.292994 | 98 | 0.505835 | false | false | false | false |
SolarSwiftem/solarswiftem.github.io | refs/heads/master | examples/swift/Example2/Example2/Example2/main.swift | apache-2.0 | 1 | import Foundation
//A variable
var x = 5
print(x)
// Int
var distance = 100
// Double
var rocketSpeed = 2.5
// String
var planet = "Earth"
// Bool
var readyForBlastOff = true
// printing
print("the distance to the next planet is", distance)
// Maths!
print("distance + 100 =", distance + 100)
print("distance - 25 =", distance - 25)
print("distance * 4 =", distance * 4)
print("distance / 2 =", distance / 2)
// Different types cause errors
//print("time left = ", distance / rocketSpeed)
// Same type
var distance2 = 100.0
print("time left = ", distance2 / rocketSpeed)
// Add strings together
var p = "Planet " + planet
print(p)
planet = "Mars"
p = "Planet " + planet
print(p)
| 21bd287f3b57fd40ea10c678eaba590e | 14.108696 | 53 | 0.657554 | false | false | false | false |
Dax220/SHRAM | refs/heads/master | SwiftyHttp/SHUploadRequest.swift | mit | 2 | //
// SHUploadRequest.swift
// SwiftyHttp
//
// Created by Максим on 18.08.17.
// Copyright © 2017 Maks. All rights reserved.
//
import Foundation
open class SHUploadRequest: SHRequest {
public var success: UploadCompletion?
public var progress: ProgressCallBack?
public var failure: FailureHTTPCallBack?
public override init(URL: String, method: SHMethod) {
super.init(URL: URL, method: method)
contentType = .multipart_form_data
}
@discardableResult
public func upload() -> URLSessionUploadTask {
configureRequest()
let uploadTask = SHDataTaskManager.createUploadTaskWithRequest(request: self,
completion: success,
progress: progress,
failure: failure)
uploadTask.resume()
return uploadTask
}
@discardableResult
public func upload(completion: UploadCompletion? = nil,
progress: ProgressCallBack? = nil,
failure: FailureHTTPCallBack? = nil) -> URLSessionUploadTask {
self.success = completion
self.progress = progress
self.failure = failure
return upload()
}
}
| e7c69ef294165f93222784b2e43e1a4c | 29.12766 | 91 | 0.534605 | false | false | false | false |
piscoTech/MBLibrary | refs/heads/master | Shared/CGPoint.swift | mit | 1 | //
// CGPoint.swift
// MBLibrary
//
// Created by Marco Boschi on 17/08/16.
// Copyright © 2016 Marco Boschi. All rights reserved.
//
import CoreGraphics
public func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
public func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
public prefix func - (p: CGPoint) -> CGPoint {
return CGPoint(x: -p.x, y: -p.y)
}
extension CGPoint {
public var module: CGFloat {
return sqrt(x*x + y*y)
}
public func normalized() -> CGPoint {
let m = module
guard m != 0 else {
return .zero
}
return CGPoint(x: x / m, y: y / m)
}
///The angle (in radians) described by the vector relative to the positive x axis in `(-π, π]` range.
public var angle: CGFloat {
if x == 0 {
return .pi / 2 * sgn(y)
}
let res = atan(y / x) + (x < 0 ? .pi : 0)
switch res {
case let tmp where tmp > .pi:
return tmp - 2 * .pi
case let tmp where tmp < -.pi:
return tmp + 2 * .pi
case let tmp:
return tmp
}
}
public func scaled(by f: CGFloat) -> CGPoint {
return CGPoint(x: x*f, y: y*f)
}
}
| f67ef226779fb1847fc08b9b82eda7ce | 18.55 | 102 | 0.591645 | false | false | false | false |
jpedrosa/sua_sdl | refs/heads/master | Sources/SuaSDL/element.swift | apache-2.0 | 1 |
import _Sua
public protocol Element: class {
var type: SType { get }
var maxWidth: Int { get set }
var maxHeight: Int { get set }
var width: Int { get set }
var height: Int { get set }
var borderTop: Bool { get set }
var borderRight: Bool { get set }
var borderBottom: Bool { get set }
var borderLeft: Bool { get set }
var borderType: BorderType { get set }
var expandWidth: Bool { get set }
var expandHeight: Bool { get set }
var expandParentWidth: Bool { get set }
var expandParentHeight: Bool { get set }
var backgroundStrings: [String] { get set }
var borderBackgroundColor: Color? { get set }
var borderColor: Color? { get set }
var _borderStyle: Int32 { get set }
var lastx: Int { get set }
var lasty: Int { get set }
var lastSize: TellSize { get set }
var eventStore: EventStore? { get set }
func tellSize() -> TellSize
func draw(x: Int, y: Int, size: TellSize)
func drawBorder(x: Int, y: Int, size: TellSize) -> Point
func drawBackground(x: Int, y: Int, width: Int, height: Int,
strings: [String])
func on(eventType: SEventType, fn: SEventHandler) -> Int
func signal(eventType: SEventType, inout ev: SEvent)
func hasListenerFor(eventType: SEventType) -> Bool
}
extension Element {
public func drawBorder(x: Int, y: Int, size: TellSize) -> Point {
let w = size.width
let h = size.height
if w <= 0 || h <= 0 {
return Point.far
}
var ny = y
var nx = x
var borderHeight = h
if size.borderTop > 0 {
var si = 0
var ei = w
if size.borderRight > 0 {
S.textGrid.move(nx + w - 1, y: ny)
S.textGrid.add("╮")
ei -= 1
}
S.textGrid.move(nx, y: ny)
if size.borderLeft > 0 {
S.textGrid.add("╭")
si += 1
}
if si < ei {
for _ in si..<ei {
S.textGrid.add("─")
}
}
ny += 1
borderHeight -= 1
}
if size.borderBottom > 0 {
borderHeight -= 1
var si = 0
var ei = w
if size.borderRight > 0 {
S.textGrid.move(nx + w - 1, y: ny + borderHeight)
S.textGrid.add("╯")
ei -= 1
}
S.textGrid.move(nx, y: ny + borderHeight)
if size.borderLeft > 0 {
S.textGrid.add("╰")
si += 1
}
if si < ei {
for _ in si..<ei {
S.textGrid.add("─")
}
}
}
if size.borderRight > 0 {
let ei = ny + borderHeight
let bx = nx + w - 1
if ny < ei {
for i in ny..<ei {
S.textGrid.move(bx, y: i)
S.textGrid.add("│")
}
}
}
if size.borderLeft > 0 {
let ei = ny + borderHeight
if ny < ei {
for i in ny..<ei {
S.textGrid.move(nx, y: i)
S.textGrid.add("│")
}
}
nx += 1
}
return Point(x: nx, y: ny)
}
public func drawBackground(x: Int, y: Int, width: Int, height: Int,
strings: [String]) {
assert(width >= 0 && height >= 0)
let blen = strings.count
if blen == 0 || strings[0].isEmpty {
return
}
let ey = y + height
let ex = x + width
if blen == 1 {
let a = Array(strings[0].characters)
let len = a.count
let s = strings[0]
if len == 1 {
for i in y..<ey {
S.textGrid.move(x, y: i)
for _ in x..<ex {
S.textGrid.add(s)
}
}
} else {
let limit = ex - len + 1
for i in y..<ey {
S.textGrid.move(x, y: i)
var j = x
while j < limit {
S.textGrid.add(s)
j += len
}
if j < ex {
S.textGrid.add(s.characters.substring(0, endIndex: ex - j))
}
}
}
} else {
var si = 0
let blen = strings.count
for i in y..<ey {
let s = strings[si]
let slen = s.characters.count
let limit = ex - slen + 1
S.textGrid.move(x, y: i)
var j = x
while j < limit {
S.textGrid.add(s)
j += slen
}
if j < ex {
S.textGrid.add(s.characters.substring(0, endIndex: ex - j))
}
si += 1
if si >= blen {
si = 0
}
}
}
}
// Handles only .Right and .Center types.
public func commonAlign(type: TextAlign, availableWidth: Int) -> Int {
var r = availableWidth
if type == .Center {
let share = availableWidth / 2
r = share
if (share * 2) < availableWidth {
r += 1 // Favor extra space on the first half to better match the
// spacing done with expandWidth.
}
}
return r
}
public func matchPoint(x: Int, y: Int) -> Bool {
return x >= lastx && x <= lastx + lastSize.width - 1 && y >= lasty &&
y <= lasty + lastSize.height - 1 &&
lastSize.contentWidth > 0 && lastSize.contentHeight > 0
}
public var borderStyle: String {
get { return "%#=" }
set {
borderColor = nil
borderBackgroundColor = nil
_borderStyle = 0
do {
let a = newValue.bytes
let (hc, _) = try Hexastyle.parseHexastyle(a, startIndex: 1,
maxBytes: a.count)
if let ahc = hc {
_borderStyle = ahc.toSStyle()
if let ac = ahc.color {
borderColor = Color(r: ac.r, g: ac.g, b: ac.b,
a: ac.a != nil ? ac.a! : 255)
}
if let ac = ahc.backgroundColor {
borderBackgroundColor = Color(r: ac.r, g: ac.g, b: ac.b,
a: ac.a != nil ? ac.a! : 255)
}
return
}
} catch {
// Ignore.
}
// Show border in red to indicate error.
borderColor = Color.red
}
}
public func on(eventType: SEventType, fn: SEventHandler) -> Int {
if eventStore == nil {
eventStore = EventStore()
}
return eventStore!.on(eventType, fn: fn)
}
public func signal(eventType: SEventType, inout ev: SEvent) {
if let es = eventStore {
es.signal(eventType, ev: &ev)
}
}
public func hasListenerFor(eventType: SEventType) -> Bool {
if let es = eventStore {
return es.hasListenerFor(eventType)
}
return false
}
}
public protocol FocusElement: class {
func _onKeyDown(ev: SEvent)
func _onKeyUp(ev: SEvent)
func _onTextInput(ev: SEvent)
func _onFocus(ev: SEvent)
func _onBlur(ev: SEvent)
func signal(eventType: SEventType, inout ev: SEvent)
func focus()
}
extension FocusElement {
public func focus() {
S.focus(self)
}
}
| 4e1fa1d724a5658f4b076006799811b7 | 22.620072 | 74 | 0.520334 | false | false | false | false |
frootloops/swift | refs/heads/master | stdlib/public/core/StringIndexConversions.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension String.Index {
/// Creates an index in the given string that corresponds exactly to the
/// specified position.
///
/// If the index passed as `sourcePosition` represents the start of an
/// extended grapheme cluster---the element type of a string---then the
/// initializer succeeds.
///
/// The following example converts the position of the Unicode scalar `"e"`
/// into its corresponding position in the string. The character at that
/// position is the composed `"é"` character.
///
/// let cafe = "Cafe\u{0301}"
/// print(cafe)
/// // Prints "Café"
///
/// let scalarsIndex = cafe.unicodeScalars.index(of: "e")!
/// let stringIndex = String.Index(scalarsIndex, within: cafe)!
///
/// print(cafe[...stringIndex])
/// // Prints "Café"
///
/// If the index passed as `sourcePosition` doesn't have an exact
/// corresponding position in `target`, the result of the initializer is
/// `nil`. For example, an attempt to convert the position of the combining
/// acute accent (`"\u{0301}"`) fails. Combining Unicode scalars do not have
/// their own position in a string.
///
/// let nextScalarsIndex = cafe.unicodeScalars.index(after: scalarsIndex)
/// let nextStringIndex = String.Index(nextScalarsIndex, within: cafe)
///
/// print(nextStringIndex)
/// // Prints "nil"
///
/// - Parameters:
/// - sourcePosition: A position in a view of the `target` parameter.
/// `sourcePosition` must be a valid index of at least one of the views
/// of `target`.
/// - target: The string referenced by the resulting index.
@_inlineable // FIXME(sil-serialize-all)
public init?(
_ sourcePosition: String.Index,
within target: String
) {
guard target.unicodeScalars._isOnGraphemeClusterBoundary(sourcePosition)
else { return nil }
self = target._characters._index(
atEncodedOffset: sourcePosition.encodedOffset)
}
/// Returns the position in the given UTF-8 view that corresponds exactly to
/// this index.
///
/// This example first finds the position of the character `"é"`, and then
/// uses this method find the same position in the string's `utf8` view.
///
/// let cafe = "Café"
/// if let i = cafe.index(of: "é") {
/// let j = i.samePosition(in: cafe.utf8)!
/// print(Array(cafe.utf8[j...]))
/// }
/// // Prints "[195, 169]"
///
/// - Parameter utf8: The view to use for the index conversion. This index
/// must be a valid index of at least one view of the string shared by
/// `utf8`.
/// - Returns: The position in `utf8` that corresponds exactly to this index.
/// If this index does not have an exact corresponding position in `utf8`,
/// this method returns `nil`. For example, an attempt to convert the
/// position of a UTF-16 trailing surrogate returns `nil`.
@_inlineable // FIXME(sil-serialize-all)
public func samePosition(
in utf8: String.UTF8View
) -> String.UTF8View.Index? {
return String.UTF8View.Index(self, within: utf8)
}
/// Returns the position in the given UTF-16 view that corresponds exactly to
/// this index.
///
/// The index must be a valid index of `String(utf16)`.
///
/// This example first finds the position of the character `"é"` and then
/// uses this method find the same position in the string's `utf16` view.
///
/// let cafe = "Café"
/// if let i = cafe.index(of: "é") {
/// let j = i.samePosition(in: cafe.utf16)!
/// print(cafe.utf16[j])
/// }
/// // Prints "233"
///
/// - Parameter utf16: The view to use for the index conversion. This index
/// must be a valid index of at least one view of the string shared by
/// `utf16`.
/// - Returns: The position in `utf16` that corresponds exactly to this
/// index. If this index does not have an exact corresponding position in
/// `utf16`, this method returns `nil`. For example, an attempt to convert
/// the position of a UTF-8 continuation byte returns `nil`.
@_inlineable // FIXME(sil-serialize-all)
public func samePosition(
in utf16: String.UTF16View
) -> String.UTF16View.Index? {
return String.UTF16View.Index(self, within: utf16)
}
}
| f9603b339d6a419dd645761403753eb7 | 39.216667 | 80 | 0.626399 | false | false | false | false |
rnystrom/GitHawk | refs/heads/master | Pods/cmark-gfm-swift/Source/Node+Elements.swift | mit | 1 | //
// Node+Elements.swift
// cmark-gfm-swift
//
// Created by Ryan Nystrom on 3/31/18.
//
import Foundation
import cmark_gfm
struct FoldingOptions {
var quoteLevel: Int
}
extension Block {
func folded(_ options: FoldingOptions) -> [Element] {
switch self {
case .blockQuote(let items):
var deeper = options
deeper.quoteLevel += 1
return items.flatMap { $0.folded(deeper) }
case .codeBlock(let text, let language):
return [.codeBlock(text: text, language: language)]
case .custom:
return []
case .heading(let text, let level):
return [.heading(text: text.textElements, level: level)]
case .html(let text):
return [.html(text: text)]
case .list(let items, let type):
return [.list(items: items.compactMap { $0.listElements(0) }, type: type)]
case .paragraph(let text):
let builder = InlineBuilder(options: options)
text.forEach { $0.fold(builder: builder) }
// clean up and append leftover text elements
var els = builder.elements
if let currentText = builder.currentText {
els.append(currentText)
}
return els
case .table(let items):
return [.table(rows: items.compactMap { $0.tableRow })]
case .tableHeader, .tableRow, .tableCell:
return [] // handled in flattening .table
case .thematicBreak:
return [.hr]
}
}
}
class InlineBuilder {
let options: FoldingOptions
var elements = [Element]()
var text = [TextElement]()
init(options: FoldingOptions) {
self.options = options
}
var currentText: Element? {
guard text.count > 0 else { return nil }
return options.quoteLevel > 0
? .quote(items: text, level: options.quoteLevel)
: .text(items: text)
}
func pushNonText(_ el: Element) {
if let currentText = self.currentText {
elements.append(currentText)
text.removeAll()
}
elements.append(el)
}
}
extension Inline {
/// Collapse all text elements, break by image elements
func fold(builder: InlineBuilder) {
switch self {
case .text, .softBreak, .lineBreak, .code, .emphasis, .strong,
.custom, .link, .strikethrough, .mention, .checkbox:
if let el = textElement {
builder.text.append(el)
}
case .image(_, let title, let url):
if let title = title, let url = url {
builder.pushNonText(.image(title: title, url: url))
}
case .html:
// handled by converting blocks containing html into full html elements
break
}
}
}
private extension Node {
var containsHTML: Bool {
if type == CMARK_NODE_HTML_BLOCK || type == CMARK_NODE_HTML_INLINE {
return true
}
for child in children {
if child.containsHTML { return true }
}
return false
}
}
public extension Node {
var flatElements: [Element] {
let options = FoldingOptions(quoteLevel: 0)
return children.reduce([Element]()) {
if $1.containsHTML {
return $0 + [.html(text: $1.html)]
} else {
if let block = Block($1) {
return $0 + block.folded(options)
} else {
return $0
}
}
}
}
}
| 9e39299e7a0137c361b40a8aac3eeabe | 28.590164 | 86 | 0.542105 | false | false | false | false |
shirai/SwiftLearning | refs/heads/master | playground/関数.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
/*
*
*宣言
func <関数>(<引数名>:<型>)-> <戻り値の型 {<処理>} >
*
*/
// String型とInt型の引数を受け取る関数
func assignmentFreshers(department: String, count: Int) {
print("\(department)に\(count)人の新人が配属された!")
}
assignmentFreshers(department:"流サ事1", count:8) // 関数の呼び出し(引数名: 省略不可)
// String型とInt型の引数を受け取り、String型を返す関数
func assignmentFreshers2(department: String, count: Int) -> String{
return "\(department)に\(count)人の新人が配属された!"
}
let message = assignmentFreshers2(department:"じゃらんゴルフ", count:1)
print(message) // 戻り値を受け取らなくてもエラーにはならない
//タプルを戻り値とすることで複数の値を返すことができる
enum Team {
case Golf, Beauty, スタサプ, スマデ,その他
}
// 指定された元号の名前と開始年を返す
func getFresher(team: Team) -> (teamName: String, number: Int)? {//オプショナルな戻り値を返すこともできる
switch team {
case .Golf:
return ("じゃらんゴルフ", 1)
case .Beauty:
return ("ホットペッパービューティ", 2)
case .スタサプ:
return ("スタディサプリ", 1)
case .スマデ:
return ("スマデ", 1)
case .その他:
return nil
}
}
print(getFresher(team:.Golf))
print(getFresher(team:.その他))
/*
*
*外部引数名
関数の各引数には、引数名(ローカル名)の他に、分かりやすいラベル(外部名)をつけて、呼び出し時に使うことができます。ラベルをつける事で関数自体がより説明的になり機能や意味が伝わりやすくなります。
*
*/
// RGB値を16進数文字列に変換
func calc(x a:Int, y b:Int, z c:Int) -> Int {
// 関数内では、各引数のローカル名を使用
return Int(a*b*c)
}
let sum = calc(x: 5, y: 16, z: 2)
print(sum)
//外部名を使いたくない場合は、次のように_(下線)を指定して無効にすることができます。(推奨はされないようです)
func encloseText2(_ text: String) -> String {//
return (text)
}
print(encloseText2("いちご"))//Javaと同じ
/*
*
*引数の規定値
関数の宣言時に引数にデフォルト(既定)値を与えることができます。
*
*/
func encloseText(text: String, prefix: String = "(", suffix: String = ")") -> String {
return prefix + text + suffix
}
print(encloseText(text:"みかん")) //既定値の与えられた引数を省略した場合、指定された既定値が引数として使用される
print(encloseText(text:"りんご", prefix:"【", suffix:"】"))
//引数の順番を次のようにすることも可能ですが、呼び出し方の一貫性を保つために、既定値付きの引数は引数リストの後方にもってくるように推奨されています。
/*
*
*可変数個引数
*
*/
//文字列中に指定した文字のどれかが含まれればtrueを返す
func containsCharacter(text: String, characters: Character...) -> Bool {
for ch in characters {
for t in text.characters {
if ch == t {
return true
}
}
}
return false
}
containsCharacter(text:"abcdefg", characters:"i")
containsCharacter(text:"abcdefg", characters:"g", "h", "i")
//可変数個引数は引数リストの最後に配置する必要があります。もし既定値と可変数個引数をもつ関数が必要な場合は、既定値をもつ引数の後に可変数個引数を配置するようにします。
// 可変数個引数は引数の最後に
func someFunc(arg1: Int, arg2: String = "hogehoge", arg3: Int...) {
}
/*
*
*定数引数と可変引数
関数の引数はデフォルトで定数として渡されます。(letが省略されています。引数名の前にletをつけても構いません)関
*
*/
//func printHelloMessage(text: String) {
// text = "Hello、" + text //数の中で引数の値を変更しようとするとエラーになる。
// print(text);
//}
//func printHelloMessage(var text: String) {
// text = "Hello、" + text
// print(text);
//}
//
//printHelloMessage("Swift") // Hello, Swift
//inoutをつけると、引数として渡した可変変数を関数の中で変更して、変更後の値を関数の外側でも参照できるようになる。
func incrementBy(inc: Int, val1: inout Int, val2: inout Int) { //Swift 3以降では型名の前
val1 += inc
val2 += inc
}
var val1 = 100
var val2 = 200
incrementBy(inc: 10, val1: &val1, val2: &val2)
//変数を関数パラメータに渡す際には、変数の直前にアンドマーク&を付けないといけない。
print("val1=\(val1), val2=\(val2)") // val1=110, val2=210
/*
*
*関数型
*
*/
//(Int, Int) -> Intの関数
func multiply(val: Int, by: Int) -> Int {
return val * by
}
//(String, Int) -> () の関数
func showEncounterMessage(monster: String, count: Int) {
print("\(count)匹の\(monster)が現れた!")
}
var f: (Int, Int) -> Int //関数型の変数を宣言
f = multiply //関数名を代入して呼び出す
var v = f(10, 3) //型推論が働く為、型を宣言しなくても代入することができる
//f = showEncounterMessage //異なる型の代入は実行時エラー
//関数自体を他の関数への引数として使う
//関数①足し算
func add(a: Int, b: Int) -> Int {
return a + b
}
//関数②引き算
func subtract(a: Int, b: Int) -> Int {
return a - b
}
//関数③関数を渡して計算
func calculate(a: Int, b: Int, function:(Int, Int) -> Int) -> Int{ //引数に関数を受け取る
return function(a, b)
}
print(calculate(a:10, b:20, function:add)) //関数③の呼び出し
let c = subtract //定数に関数を代入
calculate(a:10, b:20, function:c)
/*
*
*無名関数
*
*/
func calculate2(a: Int, b: Int, function:(Int, Int) -> Int) -> Int{
return function(a, b)
}
// 引数として乗算の結果を返す無名関数を記述
calculate2(a: 10, b: 20, function: {
(val1: Int, val2: Int) in //{}でくくってinをつける、と覚えれば良さそうですね。
return val1 * val2
})
/*さらに、無名関数の引数は上の例のように名前をつけなくても、第一引数から順に$0, $1...として参照できる。
また値を返すだけの関数の場合、return文自体も省略できる*/
calculate2(a: 10, b: 20, function: {$0 * $1})
/*Swiftでは、演算子も関数として実装されているため、省略できる*/
calculate2(a:10, b:20, function:*)
calculate2(a:10, b:20, function:+)
calculate2(a:0, b:20, function:-)
/*引数で渡す関数が引数リストの最後の引数の場合、次のように、関数名()の後の、{ }の中に処理内容を記述することができる*/
calculate2(a:10, b:20) {
$0 * $1
}
//呼び出す関数の引数が関数のみの場合は、関数名の後の()も不要。
func sayHello(greeting:(String) -> String) -> () { //戻り値なし
print(greeting("Hello"))
}
sayHello { $0 } //()なし
sayHello { $0 + ", World" } //()なし
sayHello { "Hi, " + $0 } //()なし
/*
*
*関数のネスト
*
*/
//関数の中で関数を作ることができる
func addAndSubtract(val1: Int, val2: Int, val3:Int) -> Int {
func add(a: Int, b: Int) -> Int {
return a + b
}
func subtract(a: Int, b: Int) -> Int {
return a - b
}
var result = add(a: val1, b: val2) //add関数の呼び出し
result = subtract(a: result, b: val3) //subtract関数の呼び出し
return result
}
addAndSubtract(val1: 10, val2: 50, val3: 20)
/*
*
*クロージャ
*
*/
func calculate(val1: Int, val2: Int, val3:Int) -> Int {
var x: Int?
func calc1(a: Int, b: Int) -> Int {
if x == nil {
x = 100
}
return a + b
}
func calc2(a: Int, b: Int) -> Int {
return a - b + (x == nil ? 0 : x!) //<条件> ? <trueの時> : <falseの時>
//return a - b + x ?? 0
}
var result = calc1(a: val1, b: val2) //calc1関数の呼び出し
result = calc2(a: result, b: val3) //calc2関数の呼び出し
return result
}
calculate(val1: 10, val2: 50, val3: 20)
//呼び出されるたびに+1した値を返す
func makeIncrementer(initValue: Int) -> () -> Int {
var v = initValue
func incrementer() -> Int {
v += 1
return v
}
return incrementer
}
let inc = makeIncrementer(initValue: 10)
inc()
inc()
inc()
//呼び出されるたびに第2引数で指定した値を加算した値を返す
func makeIncrementer2(initValue: Int, addValue: Int) -> () -> Int {
var v = initValue
func incrementer() -> Int {
v += addValue
return v
}
return incrementer
}
let inc2 = makeIncrementer2(initValue: 10, addValue: 5)
inc2()
inc2()
inc2()
| 27588a88c0cba73e8f68f9d250328941 | 20.764505 | 98 | 0.631802 | false | false | false | false |
googlesamples/mlkit | refs/heads/master | ios/quickstarts/digitalinkrecognition/DigitalInkRecognitionExample/StrokeManager.swift | apache-2.0 | 1 | import Foundation
import UIKit
import MLKit
/// Protocol used by the `StrokeManager` to send requests back to the `ViewController` to update the
/// display.
protocol StrokeManagerDelegate: class {
/** Clears any temporary ink managed by the caller. */
func clearInk()
/** Redraws the ink and recognition results. */
func redraw()
/** Display the given message to the user. */
func displayMessage(message: String)
}
/// The `StrokeManager` object is responsible for storing the ink and recognition results, and
/// managing the interaction with the recognizer. It receives the touch points as the user is drawing
/// from the `ViewController` (which takes care of rendering the ink), and stores them into an array
/// of `Stroke`s. When the user taps "recognize", the strokes are collected together into an `Ink`
/// object, and passed to the recognizer. The `StrokeManagerDelegate` protocol is used to inform the
/// `ViewController` when the display needs to be updated.
///
/// The `StrokeManager` provides additional methods to handle other buttons in the UI, including
/// selecting a recognition language, downloading or deleting the recognition model, or clearing the
/// ink.
class StrokeManager {
/**
* Array of `RecognizedInk`s that have been sent to the recognizer along with any recognition
* results.
*/
var recognizedInks: [RecognizedInk]
/**
* Conversion factor between `TimeInterval` and milliseconds, which is the unit used by the
* recognizer.
*/
private var kMillisecondsPerTimeInterval = 1000.0
/** Arrays used to keep the piece of ink that is currently being drawn. */
private var strokes: [Stroke] = []
private var points: [StrokePoint] = []
/** The recognizer that will translate the ink into text. */
private var recognizer: DigitalInkRecognizer! = nil
/** The view that handles UI stuff. */
private weak var delegate: StrokeManagerDelegate?
/** Properties to track and manage the selected language and recognition model. */
private var model: DigitalInkRecognitionModel?
private var modelManager: ModelManager
/**
* Initialization of internal variables as well as creating the model manager and setting up
* observers of the recognition model downloading status.
*/
init(delegate: StrokeManagerDelegate) {
self.delegate = delegate
modelManager = ModelManager.modelManager()
recognizedInks = []
// Add observers for download notifications, and reflect the status back to the user.
NotificationCenter.default.addObserver(
forName: NSNotification.Name.mlkitModelDownloadDidSucceed, object: nil,
queue: OperationQueue.main,
using: {
[unowned self]
(notification) in
if notification.userInfo![ModelDownloadUserInfoKey.remoteModel.rawValue]
as? DigitalInkRecognitionModel == self.model
{
self.delegate?.displayMessage(message: "Model download succeeded")
}
})
NotificationCenter.default.addObserver(
forName: NSNotification.Name.mlkitModelDownloadDidFail, object: nil,
queue: OperationQueue.main,
using: {
[unowned self]
(notification) in
if notification.userInfo![ModelDownloadUserInfoKey.remoteModel.rawValue]
as? DigitalInkRecognitionModel == self.model
{
self.delegate?.displayMessage(message: "Model download failed")
}
})
}
/**
* Check whether the model for the given language tag is downloaded.
*/
func isLanguageDownloaded(languageTag: String) -> Bool {
let identifier = DigitalInkRecognitionModelIdentifier(forLanguageTag: languageTag)
let model = DigitalInkRecognitionModel.init(modelIdentifier: identifier!)
return modelManager.isModelDownloaded(model)
}
/**
* Given a language tag, looks up the cooresponding model identifier and initializes the model. Note
* that this doesn't actually download the model, which is triggered manually by the user for the
* purposes of this demo app.
*/
func selectLanguage(languageTag: String) {
let identifier = DigitalInkRecognitionModelIdentifier(forLanguageTag: languageTag)
model = DigitalInkRecognitionModel.init(modelIdentifier: identifier!)
recognizer = nil
self.delegate?.displayMessage(message: "Selected language with tag \(languageTag)")
}
/**
* Actually downloads the model. This happens asynchronously with the user being shown status messages
* when the download completes or fails.
*/
func downloadModel() {
if modelManager.isModelDownloaded(model!) {
self.delegate?.displayMessage(message: "Model is already downloaded")
return
}
self.delegate?.displayMessage(message: "Starting download")
// The Progress object returned by `downloadModel` currently only takes on the values 0% or 100%
// so is not very useful. Instead we'll rely on the outcome listeners in the initializer to
// inform the user if a download succeeds or fails.
modelManager.download(
model!,
conditions: ModelDownloadConditions.init(
allowsCellularAccess: true, allowsBackgroundDownloading: true)
)
}
/** Deletes the currently selected model. */
func deleteModel() {
if !modelManager.isModelDownloaded(model!) {
self.delegate?.displayMessage(message: "Model not downloaded, nothing to delete")
return
}
modelManager.deleteDownloadedModel(
model!,
completion: {
[unowned self] _ in
self.delegate?.displayMessage(message: "Model deleted")
})
}
/**
* Actually carries out the recognition. The recognition may happen asynchronously so there's a
* callback that handles the results when they are ready.
*/
func recognizeInk() {
if strokes.isEmpty {
delegate?.displayMessage(message: "No ink to recognize")
return
}
if !modelManager.isModelDownloaded(model!) {
delegate?.displayMessage(message: "Recognizer model not downloaded")
return
}
if recognizer == nil {
self.delegate?.displayMessage(message: "Initializing recognizer")
let options: DigitalInkRecognizerOptions = DigitalInkRecognizerOptions.init(model: model!)
recognizer = DigitalInkRecognizer.digitalInkRecognizer(options: options)
delegate?.displayMessage(message: "Initialized recognizer")
}
// Turn the list of strokes into an `Ink`, and add this ink to the `recognizedInks` array.
let ink = Ink.init(strokes: strokes)
let recognizedInk = RecognizedInk.init(ink: ink)
recognizedInks.append(recognizedInk)
// Clear the currently being drawn ink, and display the ink from `recognizedInks` (which results
// in it changing color).
delegate?.redraw()
delegate?.clearInk()
strokes = []
// Start the recognizer. Callback function will store the recognized text and tell the
// `ViewController` to redraw the screen to show it.
recognizer.recognize(
ink: ink,
completion: {
[unowned self, recognizedInk]
(result: DigitalInkRecognitionResult?, error: Error?) in
if let result = result, let candidate = result.candidates.first {
recognizedInk.text = candidate.text
var message = "Recognized: \(candidate.text)"
if candidate.score != nil {
message += " score \(candidate.score!.floatValue)"
}
self.delegate?.displayMessage(message: message)
} else {
recognizedInk.text = "error"
self.delegate?.displayMessage(message: "Recognition error " + String(describing: error))
}
self.delegate?.redraw()
})
}
/** Clear out all the ink and other state. */
func clear() {
recognizedInks = []
strokes = []
points = []
}
/** Begins a new stroke when the user touches the screen. */
func startStrokeAtPoint(point: CGPoint, t: TimeInterval) {
points = [
StrokePoint.init(
x: Float(point.x), y: Float(point.y), t: Int(t * kMillisecondsPerTimeInterval))
]
}
/** Adds an additional point to the stroke when the user moves their finger. */
func continueStrokeAtPoint(point: CGPoint, t: TimeInterval) {
points.append(
StrokePoint.init(
x: Float(point.x), y: Float(point.y),
t: Int(t * kMillisecondsPerTimeInterval)))
}
/** Completes a stroke when the user lifts their finger. */
func endStrokeAtPoint(point: CGPoint, t: TimeInterval) {
points.append(
StrokePoint.init(
x: Float(point.x), y: Float(point.y),
t: Int(t * kMillisecondsPerTimeInterval)))
// Create an array of strokes if it doesn't exist already, and add this stroke to it.
strokes.append(Stroke.init(points: points))
points = []
}
}
| 206a8f3b39740ea91447f938f15753b1 | 36.939394 | 104 | 0.69717 | false | false | false | false |
NickAger/elm-slider | refs/heads/master | ServerSlider/HTTPServer/Packages/Axis-0.14.0/Sources/Axis/Stream/Stream.swift | mit | 2 | public enum StreamError : Error {
case closedStream
case timeout
}
public protocol InputStream {
var closed: Bool { get }
func open(deadline: Double) throws
func close()
func read(into readBuffer: UnsafeMutableBufferPointer<Byte>, deadline: Double) throws -> UnsafeBufferPointer<Byte>
func read(upTo byteCount: Int, deadline: Double) throws -> Buffer
func read(exactly byteCount: Int, deadline: Double) throws -> Buffer
}
extension InputStream {
public func read(upTo byteCount: Int, deadline: Double) throws -> Buffer {
guard byteCount > 0 else {
return Buffer()
}
var bytes = [Byte](repeating: 0, count: byteCount)
let bytesRead = try bytes.withUnsafeMutableBufferPointer {
try read(into: $0, deadline: deadline).count
}
return Buffer(bytes[0..<bytesRead])
}
public func read(exactly byteCount: Int, deadline: Double) throws -> Buffer {
guard byteCount > 0 else {
return Buffer()
}
var bytes = [Byte](repeating: 0, count: byteCount)
try bytes.withUnsafeMutableBufferPointer { pointer in
var address = pointer.baseAddress!
var remaining = byteCount
while remaining > 0 {
let chunk = try read(into: UnsafeMutableBufferPointer(start: address, count: remaining), deadline: deadline)
guard chunk.count > 0 else {
throw StreamError.closedStream
}
address = address.advanced(by: chunk.count)
remaining -= chunk.count
}
}
return Buffer(bytes)
}
/// Drains the `Stream` and returns the contents in a `Buffer`. At the end of this operation the stream will be closed.
public func drain(deadline: Double) throws -> Buffer {
var buffer = Buffer()
while !self.closed, let chunk = try? self.read(upTo: 2048, deadline: deadline), chunk.count > 0 {
buffer.append(chunk)
}
return buffer
}
}
public protocol OutputStream {
var closed: Bool { get }
func open(deadline: Double) throws
func close()
func write(_ buffer: UnsafeBufferPointer<Byte>, deadline: Double) throws
func write(_ buffer: Buffer, deadline: Double) throws
func write(_ buffer: BufferRepresentable, deadline: Double) throws
func flush(deadline: Double) throws
}
extension OutputStream {
public func write(_ buffer: Buffer, deadline: Double) throws {
guard !buffer.isEmpty else {
return
}
try buffer.bytes.withUnsafeBufferPointer {
try write($0, deadline: deadline)
}
}
public func write(_ converting: BufferRepresentable, deadline: Double) throws {
try write(converting.buffer, deadline: deadline)
}
public func write(_ bytes: [Byte], deadline: Double) throws {
guard !bytes.isEmpty else {
return
}
try bytes.withUnsafeBufferPointer { try self.write($0, deadline: deadline) }
}
}
public typealias Stream = InputStream & OutputStream
| 572d2e3e033f040be306138108bdc0a6 | 30.633663 | 124 | 0.615023 | false | false | false | false |
TelerikAcademy/Mobile-Applications-with-iOS | refs/heads/master | demos/AsyncOperations/AsyncOperations/DemoViewController.swift | mit | 1 | //
// DemoViewController.swift
// AsyncOperations
//
// Created by Doncho Minkov on 3/20/17.
// Copyright © 2017 Doncho Minkov. All rights reserved.
import UIKit
class DemoViewController: UIViewController {
var url: URL {
get {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return URL(string: appDelegate.baseUrl + "/books")!
}
}
override func viewDidLoad() {
super.viewDidLoad()
//
// var booksData = BooksData()
//
// // Delegate pattern
//
// booksData.delegate = self
// booksData.getAll()
//
//
// // LAMBDA
//
// booksData.getAll(completionCallback: {(books, error) in
//
// })
// Get the URL
let url = self.url
// create the NSMutableURLRequest
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
// send the request wiht URLSession
let urlRequest = request as URLRequest
let session = URLSession.shared.dataTask(with:urlRequest) { (data, response, error) in
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(json)
} catch {
}
}
session.resume()
// use the response
}
func onDataReceived(books: [Book]) {
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 6afc500ed96fb32bc7d83599ee8970b4 | 24.952941 | 107 | 0.519039 | false | false | false | false |
PigDogBay/swift-utils | refs/heads/master | SwiftUtils/CodewordSolver.swift | apache-2.0 | 1 | //
// CodewordSolver.swift
// SwiftUtils
//
// Created by Mark Bailey on 06/09/2018.
// Copyright © 2018 MPD Bailey Technology. All rights reserved.
//
import Foundation
open class CodewordSolver {
fileprivate let CROSSWORD_CHAR = UnicodeScalar(".")
fileprivate let SAME_CHAR_1 = UnicodeScalar("1")
fileprivate let SAME_CHAR_2 = UnicodeScalar("2")
fileprivate let SAME_CHAR_3 = UnicodeScalar("3")
fileprivate let SAME_CHAR_4 = UnicodeScalar("4")
fileprivate let SAME_CHAR_5 = UnicodeScalar("5")
fileprivate let SAME_CHAR_6 = UnicodeScalar("6")
fileprivate let SAME_CHAR_7 = UnicodeScalar("7")
class Letter {
var character : UnicodeScalar
let position : Int
init(character : UnicodeScalar, position : Int){
self.character = character
self.position = position
}
}
var unknowns : [Letter] = []
var knowns : [Letter] = []
var same1 : [Letter] = []
var same2 : [Letter] = []
var same3 : [Letter] = []
var same4 : [Letter] = []
var same5 : [Letter] = []
var same6 : [Letter] = []
var same7 : [Letter] = []
var letterSet = LetterSet(word: "")
fileprivate var wordLength = 0
public init(){}
open func parse(query : String){
unknowns.removeAll()
knowns.removeAll()
same1.removeAll()
same2.removeAll()
same3.removeAll()
same4.removeAll()
same5.removeAll()
same6.removeAll()
same7.removeAll()
wordLength = query.length
var pos = 0
for s in query.unicodeScalars {
let letter = Letter(character: s,position: pos)
pos = pos + 1
switch s {
case CROSSWORD_CHAR:
unknowns.append(letter)
case SAME_CHAR_1:
same1.append(letter)
case SAME_CHAR_2:
same2.append(letter)
case SAME_CHAR_3:
same3.append(letter)
case SAME_CHAR_4:
same4.append(letter)
case SAME_CHAR_5:
same5.append(letter)
case SAME_CHAR_6:
same6.append(letter)
case SAME_CHAR_7:
same7.append(letter)
default:
knowns.append(letter)
}
}
}
open func isMatch(word : String) -> Bool {
if (word.length != wordLength) {return false}
//check if known letters match
let scalars = word.unicodeScalars
for letter in knowns {
let index = scalars.index(scalars.startIndex, offsetBy: letter.position)
if letter.character != scalars[index] {return false}
}
//check if numbered letters are the same and different to the rest
if !checkSameLetters(word: scalars, sameLetters: &same1) {return false}
if !checkSameLetters(word: scalars, sameLetters: &same2) {return false}
if !checkSameLetters(word: scalars, sameLetters: &same3) {return false}
if !checkSameLetters(word: scalars, sameLetters: &same4) {return false}
if !checkSameLetters(word: scalars, sameLetters: &same5) {return false}
if !checkSameLetters(word: scalars, sameLetters: &same6) {return false}
if !checkSameLetters(word: scalars, sameLetters: &same7) {return false}
//check knowns do not equal unknown
for unknown in unknowns {
let index = scalars.index(scalars.startIndex, offsetBy: unknown.position)
let c = scalars[index]
if knowns.contains(where: {known in known.character == c}) {return false}
//store char for later use
unknown.character = c
}
//check no other groups of letters in the unknowns
letterSet.clear()
letterSet.add(word)
if unknowns.contains(where: { letter in letterSet.getCount(scalar: letter.character) > 1}) {return false}
return true
}
/*
Check that the pattern of the same letters are actuall the same
*/
fileprivate func checkSameLetters(word : String.UnicodeScalarView, sameLetters : inout [Letter]) -> Bool {
if sameLetters.count<2 {return true}
//get the letter that is the same from the word
let letterIndex = word.index(word.startIndex, offsetBy: sameLetters[0].position)
let actualLetter = word[letterIndex]
//check if numbered letters are the same
for sl in sameLetters.dropFirst() {
let index = word.index(word.startIndex, offsetBy: sl.position)
if actualLetter != word[index] {return false}
}
//check that the other letters in the word are different
var pos = 0
for s in word {
if !sameLetters.contains(where: {letter in letter.position == pos }) {
if (s == actualLetter) {return false}
}
pos = pos + 1
}
return true
}
}
| 1e754f03fbfcb4847868fa2a9c920d73 | 34.195804 | 113 | 0.583747 | false | false | false | false |
Fenrikur/ef-app_ios | refs/heads/master | Eurofurence/Notifications/Scheduling/UserNotificationsScheduler.swift | mit | 1 | import EurofurenceModel
import UserNotifications
struct UserNotificationsScheduler: NotificationScheduler {
func scheduleNotification(forEvent identifier: EventIdentifier,
at dateComponents: DateComponents,
title: String,
body: String,
userInfo: [ApplicationNotificationKey: String]) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.userInfo = userInfo.xpcSafeDictionary
let soundName = UNNotificationSoundName(rawValue: "personal_notification.caf")
content.sound = UNNotificationSound(named: soundName)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: identifier.rawValue, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("Failed to add notification with error: \(error)")
}
}
}
func cancelNotification(forEvent identifier: EventIdentifier) {
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
}
}
private extension Dictionary where Key == ApplicationNotificationKey, Value == String {
var xpcSafeDictionary: [String: String] {
let stringPairs: [(String, String)] = map({ (key, value) -> (String, String) in
return (key.rawValue, value)
})
var dictionary = [String: String]()
for (key, value) in stringPairs {
dictionary[key] = value
}
return dictionary
}
}
| d9b96b1e3fdb742ba25b8333a7b798c3 | 35.06 | 116 | 0.636162 | false | false | false | false |
ZWCoder/KMLive | refs/heads/master | KMLive/KMLive/Classes/Home/KMRecommendViewController.swift | mit | 1 | //
// KMRecommendViewController.swift
// KMLive
//
// Created by 联合创想 on 16/12/16.
// Copyright © 2016年 KMXC. All rights reserved.
// 关注
import UIKit
fileprivate let kNormalItemW = (UIScreen.main.bounds.width - 3 * 10) / 2
fileprivate let kNormalItemH = kNormalItemW * 3 / 4
fileprivate let kPrettyItemH = kNormalItemW * 4 / 3
fileprivate let kCycleViewH = UIScreen.main.bounds.width * 3 / 8
fileprivate let KMRecommendNormalCellIdentifier = "KMRecommendNormalCellIdentifier"
fileprivate let KMRecommendPrettyCellIdentifier = "KMRecommendPrettyCellIdentifier"
fileprivate let KMRecommendHeaderIdentifier = "KMRecommendHeaderIdentifier"
class KMRecommendViewController: UIViewController {
//MARK:-- 定义属性
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupUI()
view.backgroundColor = UIColor.yellow
loadData()
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
//MARK:--懒加载
fileprivate lazy var collectionView:UICollectionView = {
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
let collection = UICollectionView(frame:frame, collectionViewLayout: KMRecommendViewLayout())
collection.delegate = self
collection.dataSource = self
collection.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collection.register(KMRecommandNormalCell.self, forCellWithReuseIdentifier: KMRecommendNormalCellIdentifier)
collection.register(KMRecommandPrettyCell.self, forCellWithReuseIdentifier: KMRecommendPrettyCellIdentifier)
collection.register(KMRecommendHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KMRecommendHeaderIdentifier)
collection.backgroundColor = UIColor.white
return collection
}()
fileprivate lazy var recomendVM:KMRecomandViewModel = KMRecomandViewModel()
fileprivate lazy var cycleView:KMRecommandCycleView = {
let cycleView = KMRecommandCycleView()
cycleView.frame = CGRect(x: 0, y: -kCycleViewH, width: UIScreen.main.bounds.width, height: kCycleViewH)
return cycleView
}()
}
//MARK:--
extension KMRecommendViewController{
fileprivate func setupUI(){
view.addSubview(collectionView)
collectionView.addSubview(cycleView)
collectionView.contentInset = UIEdgeInsets(top: kCycleViewH, left: 0, bottom: 0, right: 0)
}
}
extension KMRecommendViewController{
func loadData() {
recomendVM.requestData {
self.collectionView.reloadData()
}
recomendVM.requestCycleViewData {
self.cycleView.cycleModels = self.recomendVM.kmCycleModels
}
}
}
//MARK:--UICollectionViewDelegate,UICollectionViewDataSource
extension KMRecommendViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return recomendVM.kmAnchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return recomendVM.kmAnchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let anchor = recomendVM.kmAnchorGroups[indexPath.section].anchors[indexPath.item]
if indexPath.section == 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KMRecommendPrettyCellIdentifier, for: indexPath) as! KMRecommandPrettyCell
cell.anchor = anchor
cell.backgroundColor = UIColor.white
return cell
}else
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KMRecommendNormalCellIdentifier, for: indexPath) as! KMRecommandNormalCell
cell.anchor = anchor
cell.backgroundColor = UIColor.white
return cell
}
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: KMRecommendHeaderIdentifier, for: indexPath)
headerView.backgroundColor = UIColor.yellow
return headerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kNormalItemW, height: kPrettyItemH)
}
return CGSize(width: kNormalItemW, height: kNormalItemH)
}
}
//MARK:--
class KMRecommendViewLayout: UICollectionViewFlowLayout {
override func prepare() {
super.prepare()
let itemW = (UIScreen.main.bounds.width - 30) * 0.5
let itemH = itemW * 3 / 4
itemSize = CGSize(width: itemW, height: itemH)
minimumLineSpacing = 0
minimumInteritemSpacing = 10
headerReferenceSize = CGSize(width: UIScreen.main.bounds.width, height: 50)
sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
}
}
//MARK:-- KMRecommendHeaderView
class KMRecommendHeaderView: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK:--
fileprivate lazy var sectionLine:UIView = {
let line = UIView()
line.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 10)
line.backgroundColor = UIColor.lightGray
return line
}()
fileprivate lazy var iconImage:UIImageView = {
let iconImage = UIImageView()
iconImage.image = UIImage(named: "home_header_phone")
iconImage.frame = CGRect(x: 10, y: 15, width: 18, height: 20)
return iconImage
}()
fileprivate lazy var sectionLabel:UILabel = {
let label = UILabel()
label.frame = CGRect(x: self.iconImage.km_Right + 10, y: self.iconImage.km_Top, width: 50, height: 20)
label.text = "颜值"
return label
}()
fileprivate lazy var moreButton:UIButton = {
let button = UIButton()
button.setTitle("更多 >", for: .normal)
button.setTitleColor(UIColor.lightGray, for: .normal)
button.sizeToFit()
button.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
return button
}()
}
extension KMRecommendHeaderView {
fileprivate func setupUI(){
addSubview(sectionLine)
addSubview(iconImage)
addSubview(sectionLabel)
addSubview(moreButton)
_ = moreButton.xmg_AlignInner(type: .TopRight, referView: self, size: nil,offset:CGPoint(x: -10, y: 10))
}
}
| a0dda35a65f9709b318a3a1f1299177c | 31.126531 | 171 | 0.667133 | false | false | false | false |
Dreezydraig/actor-platform | refs/heads/master | actor-apps/app-ios/ActorApp/Controllers/Dialogs/DialogsViewController.swift | mit | 14 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class DialogsViewController: EngineListController, UISearchBarDelegate, UISearchDisplayDelegate {
var tableView: UITableView!
var searchView: UISearchBar?
var searchDisplay: UISearchDisplayController?
var searchSource: DialogsSearchSource?
var binder = Binder()
init() {
super.init(contentSection: 0)
var title = "";
if (MainAppTheme.tab.showText) {
title = NSLocalizedString("TabMessages", comment: "Messages Title")
}
tabBarItem = UITabBarItem(title: title,
image: MainAppTheme.tab.createUnselectedIcon("TabIconChats"),
selectedImage: MainAppTheme.tab.createSelectedIcon("TabIconChatsHighlighted"))
binder.bind(Actor.getAppState().getGlobalCounter(), closure: { (value: JavaLangInteger?) -> () in
if value != nil {
if value!.integerValue > 0 {
self.tabBarItem.badgeValue = "\(value!.integerValue)"
} else {
self.tabBarItem.badgeValue = nil
}
} else {
self.tabBarItem.badgeValue = nil
}
})
if (!MainAppTheme.tab.showText) {
tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
self.extendedLayoutIncludesOpaqueBars = true
tableView = UITableView()
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.rowHeight = 76
tableView.backgroundColor = MainAppTheme.list.backyardColor
view.addSubview(tableView)
// view = tableView
}
override func buildDisplayList() -> ARBindedDisplayList {
return Actor.getDialogsDisplayList()
}
func isTableEditing() -> Bool {
return self.tableView.editing;
}
override func viewDidLoad() {
// Footer
var footer = TableViewHeader(frame: CGRectMake(0, 0, 320, 80));
var footerHint = UILabel(frame: CGRectMake(0, 0, 320, 60));
footerHint.textAlignment = NSTextAlignment.Center;
footerHint.font = UIFont.systemFontOfSize(16);
footerHint.textColor = MainAppTheme.list.hintColor
footerHint.text = NSLocalizedString("DialogsHint", comment: "Swipe hint")
footer.addSubview(footerHint);
var shadow = UIImageView(image: UIImage(named: "CardBottom2"));
shadow.frame = CGRectMake(0, 0, 320, 4);
shadow.contentMode = UIViewContentMode.ScaleToFill;
footer.addSubview(shadow);
self.tableView.tableFooterView = footer;
bindTable(tableView, fade: true);
searchView = UISearchBar()
searchView!.delegate = self
searchView!.frame = CGRectMake(0, 0, 320, 44)
searchView!.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
MainAppTheme.search.styleSearchBar(searchView!)
searchDisplay = UISearchDisplayController(searchBar: searchView, contentsController: self)
searchDisplay?.searchResultsDelegate = self
searchDisplay?.searchResultsTableView.rowHeight = 76
searchDisplay?.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.None
searchDisplay?.searchResultsTableView.backgroundColor = MainAppTheme.list.backyardColor
searchDisplay?.searchResultsTableView.frame = tableView.frame
var header = TableViewHeader(frame: CGRectMake(0, 0, 320, 44))
header.addSubview(searchDisplay!.searchBar)
// var headerShadow = UIImageView(frame: CGRectMake(0, -4, 320, 4));
// headerShadow.image = UIImage(named: "CardTop2");
// headerShadow.contentMode = UIViewContentMode.ScaleToFill;
// header.addSubview(headerShadow);
tableView.tableHeaderView = header
searchSource = DialogsSearchSource(searchDisplay: searchDisplay!)
super.viewDidLoad();
navigationItem.title = NSLocalizedString("TabMessages", comment: "Messages Title")
navigationItem.leftBarButtonItem = editButtonItem()
navigationItem.leftBarButtonItem!.title = NSLocalizedString("NavigationEdit", comment: "Edit Title");
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "navigateToCompose")
placeholder.setImage(
UIImage(named: "chat_list_placeholder"),
title: NSLocalizedString("Placeholder_Dialogs_Title", comment: "Placeholder Title"),
subtitle: NSLocalizedString("Placeholder_Dialogs_Message", comment: "Placeholder Message"))
binder.bind(Actor.getAppState().getIsDialogsEmpty(), closure: { (value: Any?) -> () in
if let empty = value as? JavaLangBoolean {
if Bool(empty.booleanValue()) == true {
self.navigationItem.leftBarButtonItem = nil
self.showPlaceholder()
} else {
self.hidePlaceholder()
self.navigationItem.leftBarButtonItem = self.editButtonItem()
}
}
})
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
Actor.onDialogsOpen();
}
override func viewDidDisappear(animated: Bool) {
Actor.onDialogsClosed();
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// SearchBar hack
var searchBar = searchDisplay!.searchBar
var superView = searchBar.superview
if !(superView is UITableView) {
searchBar.removeFromSuperview()
superView?.addSubview(searchBar)
}
// Header hack
tableView.tableHeaderView?.setNeedsLayout()
tableView.tableFooterView?.setNeedsLayout()
// tableView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height)
if (searchDisplay != nil && searchDisplay!.active) {
MainAppTheme.search.applyStatusBar()
} else {
MainAppTheme.navigation.applyStatusBar()
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
tableView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
searchDisplay?.setActive(false, animated: animated)
}
// MARK: -
// MARK: Setters
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.setEditing(editing, animated: animated)
if (editing) {
self.navigationItem.leftBarButtonItem!.title = NSLocalizedString("NavigationDone", comment: "Done Title");
self.navigationItem.leftBarButtonItem!.style = UIBarButtonItemStyle.Done;
navigationItem.rightBarButtonItem = nil
}
else {
self.navigationItem.leftBarButtonItem!.title = NSLocalizedString("NavigationEdit", comment: "Edit Title");
self.navigationItem.leftBarButtonItem!.style = UIBarButtonItemStyle.Bordered;
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "navigateToCompose")
}
if editing == true {
navigationItem.rightBarButtonItem = nil
} else {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "navigateToCompose")
}
}
// MARK: -
// MARK: UITableView
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
var dialog = objectAtIndexPath(indexPath) as! ACDialog
execute(Actor.deleteChatCommandWithPeer(dialog.getPeer()));
}
}
override func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell {
let reuseKey = "cell_dialog";
var cell = tableView.dequeueReusableCellWithIdentifier(reuseKey) as! DialogCell?;
if (cell == nil){
cell = DialogCell(reuseIdentifier: reuseKey);
cell?.awakeFromNib();
}
return cell!;
}
override func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) {
var dialog = item as! ACDialog;
let isLast = indexPath.row == tableView.numberOfRowsInSection(indexPath.section)-1;
(cell as! DialogCell).bindDialog(dialog, isLast: isLast);
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (tableView == self.tableView) {
var dialog = objectAtIndexPath(indexPath) as! ACDialog
navigateToMessagesWithPeer(dialog.getPeer())
} else {
var searchEntity = searchSource!.objectAtIndexPath(indexPath) as! ACSearchEntity
navigateToMessagesWithPeer(searchEntity.getPeer())
}
}
// MARK: -
// MARK: Navigation
func navigateToCompose() {
navigateDetail(ComposeController())
}
private func navigateToMessagesWithPeer(peer: ACPeer) {
navigateDetail(ConversationViewController(peer: peer))
MainAppTheme.navigation.applyStatusBar()
}
}
| c2299983abb7eb7551892ce52a8842a5 | 36.914498 | 158 | 0.634572 | false | false | false | false |
googleprojectzero/fuzzilli | refs/heads/main | Sources/Fuzzilli/Corpus/MarkovCorpus.swift | apache-2.0 | 1 | import Foundation
/// Corpus & Scheduler based on
/// Coverage-based Greybox Fuzzing as Markov Chain paper
/// https://mboehme.github.io/paper/TSE18.pdf
/// Simply put, the corpus keeps track of which paths have been found, and prioritizes seeds
/// whose path has been hit less than average. Ideally, this allows the fuzzer to prioritize
/// less explored coverage.
/// In the paper, a number of iterations is assigned to each sample, and each sample is then
/// scheduled that number of times. This implementation finds 1 / desiredSelectionProportion
/// of the least hit edges, and schedules those. After those have been mutated and evalutated,
/// the list is regenerated.
/// TODO:
/// - In order to properly implement the paper, the number of executions of each sample needs
/// to be scaled by its execution time (e.g. multiple by timeout / execution time), to
/// prioritize faster samples
public class MarkovCorpus: ComponentBase, Corpus {
// All programs that were added to the corpus so far
private var allIncludedPrograms: [Program] = []
// Queue of programs to be executed next, all of which hit a rare edge
private var programExecutionQueue: [Program] = []
// For each edge encountered thus far, track which program initially discovered it
private var edgeMap: [UInt32:Program] = [:]
// This scheduler tracks the total number of samples it has returned
// This allows it to build an initial baseline by randomly selecting a program to mutate
// before switching to the more computationally expensive selection of programs that
// hit infreqent edges
private var totalExecs: UInt32 = 0
// This scheduler returns one base program multiple times, in order to compensate the overhead caused by tracking
// edge counts
private var currentProg: Program
private var remainingEnergy: UInt32 = 0
// Markov corpus requires an evaluator that tracks edge coverage
// Thus, the corpus object keeps a reference to the evaluator, in order to only downcast once
private var covEvaluator: ProgramCoverageEvaluator
// Rate at which selected samples will be included, to promote diversity between instances
// Equivalent to 1 - dropoutRate
private var dropoutRate: Double
// The scheduler will initially selectd the 1 / desiredSelectionProportion samples with the least frequent
// edge hits in each round, before dropout is applied
private let desiredSelectionProportion = 8
public init(covEvaluator: ProgramCoverageEvaluator, dropoutRate: Double) {
self.dropoutRate = dropoutRate
covEvaluator.enableEdgeTracking()
self.covEvaluator = covEvaluator
self.currentProg = Program()
super.init(name: "MarkovCorpus")
}
override func initialize() {
assert(covEvaluator === fuzzer.evaluator as! ProgramCoverageEvaluator)
}
public func add(_ program: Program, _ aspects: ProgramAspects) {
guard program.size > 0 else { return }
guard let origCov = aspects as? CovEdgeSet else {
logger.fatal("Markov Corpus needs to be provided a CovEdgeSet when adding a program")
}
prepareProgramForInclusion(program, index: self.size)
allIncludedPrograms.append(program)
for e in origCov.getEdges() {
edgeMap[e] = program
}
}
/// Split evenly between programs in the current queue and all programs available to the corpus
public func randomElementForSplicing() -> Program {
var prog = programExecutionQueue.randomElement()
if prog == nil || probability(0.5) {
prog = allIncludedPrograms.randomElement()
}
assert(prog != nil && prog!.size > 0)
return prog!
}
/// For the first 250 executions, randomly choose a program. This is done to build a base list of edge counts
/// Once that base is acquired, provide samples that trigger an infrequently hit edge
public func randomElementForMutating() -> Program {
totalExecs += 1
// Only do computationally expensive work choosing the next program when there is a solid
// baseline of execution data. The data tracked in the statistics module is not used, as modules are intended
// to not be required for the fuzzer to function.
if totalExecs > 250 {
// Check if more programs are needed
if programExecutionQueue.isEmpty {
regenProgramList()
}
if remainingEnergy > 0 {
remainingEnergy -= 1
} else {
remainingEnergy = energyBase()
currentProg = programExecutionQueue.popLast()!
}
return currentProg
} else {
return allIncludedPrograms.randomElement()!
}
}
private func regenProgramList() {
if programExecutionQueue.count != 0 {
logger.fatal("Attempted to generate execution list while it still has programs")
}
let edgeCounts = covEvaluator.getEdgeHitCounts()
let edgeCountsSorted = edgeCounts.sorted()
// Find the edge with the smallest count
var startIndex = -1
for (i, val) in edgeCountsSorted.enumerated() {
if val != 0 {
startIndex = i
break
}
}
if startIndex == -1 {
logger.fatal("No edges found in edge count")
}
// Find the nth interesting edge's count
let desiredEdgeCount = max(size / desiredSelectionProportion, 30)
let endIndex = min(startIndex + desiredEdgeCount, edgeCountsSorted.count - 1)
let maxEdgeCountToFind = edgeCountsSorted[endIndex]
// Find the n edges with counts <= maxEdgeCountToFind.
for (i, val) in edgeCounts.enumerated() {
// Applies dropout on otherwise valid samples, to ensure variety between instances
// This will likely select some samples multiple times, which is acceptable as
// it is proportional to how many infrquently hit edges the sample has
if val != 0 && val <= maxEdgeCountToFind && (probability(1 - dropoutRate) || programExecutionQueue.isEmpty) {
if let prog = edgeMap[UInt32(i)] {
programExecutionQueue.append(prog)
}
}
}
// Determine how many edges have been leaked and produce a warning if over 1% of total edges
// Done as second pass for code clarity
// Testing on v8 shows that < 0.01% of total edges are leaked
// Potential causes:
// - Libcoverage iterates over the edge map twice, once for new coverage, and once for edge counts.
// This occurs while the target JS engine is running, so the coverage may be slightly different between the passes
// However, this is unlikely to be useful coverage for the purposes of Fuzzilli
// - Crashing samples may find new coverage and thus increment counters, but are not added to the corpus
var missingEdgeCount = 0
for (i, val) in edgeCounts.enumerated() {
if val != 0 && edgeMap[UInt32(i)] == nil {
missingEdgeCount += 1
}
}
if missingEdgeCount > (edgeCounts.count / 100) {
let missingPercentage = Double(missingEdgeCount) / Double(edgeCounts.count) * 100.0
logger.warning("\(missingPercentage)% of total edges have been leaked")
}
if programExecutionQueue.count == 0 {
logger.fatal("Program regeneration failed")
}
logger.info("Markov Corpus selected \(programExecutionQueue.count) new programs")
}
public var size: Int {
return allIncludedPrograms.count
}
public var isEmpty: Bool {
return size == 0
}
public subscript(index: Int) -> Program {
return allIncludedPrograms[index]
}
public func allPrograms() -> [Program] {
return allIncludedPrograms
}
// We don't currently support fast state synchronization.
// Instead, we need to import every sample separately (potentially
// multiple times for determinism) to determine the edges it triggers.
public var supportsFastStateSynchronization: Bool {
return false
}
// Note that this exports all programs, but does not include edge counts
public func exportState() throws -> Data {
fatalError("Not Supported")
}
public func importState(_ buffer: Data) throws {
fatalError("Not Supported")
}
// Ramp up the number of times a sample is used as the initial seed over time
private func energyBase() -> UInt32 {
return UInt32(Foundation.log10(Float(totalExecs))) + 1
}
}
| 84c48826af2b5975479694926e75af73 | 41.355769 | 127 | 0.659024 | false | false | false | false |
hooman/swift | refs/heads/main | test/IRGen/generic_casts.swift | apache-2.0 | 4 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -enable-objc-interop -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
import Foundation
import gizmo
// -- Protocol records for cast-to ObjC protocols
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_ = internal constant
// CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section {{"__DATA,__objc_protolist,coalesced,no_dead_strip"|"objc_protolist"|".objc_protolist\$B"}}
// CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section {{"__DATA,__objc_protorefs,coalesced,no_dead_strip"|"objc_protorefs"|".objc_protorefs\$B"}}
// CHECK: @_PROTOCOL_NSRuncing = internal constant
// CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section {{"__DATA,__objc_protolist,coalesced,no_dead_strip"|"objc_protolist"|".objc_protolist\$B"}}
// CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section {{"__DATA,__objc_protorefs,coalesced,no_dead_strip"|"objc_protorefs"|".objc_protorefs\$B"}}
// CHECK: @_PROTOCOLS__TtC13generic_casts10ObjCClass2 = internal constant { i64, [1 x i8*] } {
// CHECK: i64 1,
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto2_
// CHECK: }
// CHECK: @_DATA__TtC13generic_casts10ObjCClass2 = internal constant {{.*}} @_PROTOCOLS__TtC13generic_casts10ObjCClass2
// CHECK: @_PROTOCOL_PROTOCOLS__TtP13generic_casts10ObjCProto2_ = internal constant { i64, [1 x i8*] } {
// CHECK: i64 1,
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_
// CHECK: }
// CHECK: define hidden swiftcc i64 @"$s13generic_casts8allToIntySixlF"(%swift.opaque* noalias nocapture %0, %swift.type* %T)
func allToInt<T>(_ x: T) -> Int {
return x as! Int
// CHECK: [[INT_TEMP:%.*]] = alloca %TSi,
// CHECK: [[TYPE_ADDR:%.*]] = bitcast %swift.type* %T to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[TYPE_ADDR]], i64 -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable*
// CHECK: [[SIZE_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8
// CHECK: [[SIZE:%.*]] = load i64, i64* [[SIZE_ADDR]]
// CHECK: [[T_ALLOCA:%.*]] = alloca i8, {{.*}} [[SIZE]], align 16
// CHECK: [[T_TMP:%.*]] = bitcast i8* [[T_ALLOCA]] to %swift.opaque*
// CHECK: [[TEMP:%.*]] = call %swift.opaque* {{.*}}(%swift.opaque* noalias [[T_TMP]], %swift.opaque* noalias %0, %swift.type* %T)
// CHECK: [[T0:%.*]] = bitcast %TSi* [[INT_TEMP]] to %swift.opaque*
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* [[T0]], %swift.opaque* [[T_TMP]], %swift.type* %T, %swift.type* @"$sSiN", i64 7)
// CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0
// CHECK: [[INT_RESULT:%.*]] = load i64, i64* [[T0]],
// CHECK: ret i64 [[INT_RESULT]]
}
// CHECK: define hidden swiftcc void @"$s13generic_casts8intToAllyxSilF"(%swift.opaque* noalias nocapture sret({{.*}}) %0, i64 %1, %swift.type* %T) {{.*}} {
func intToAll<T>(_ x: Int) -> T {
// CHECK: [[INT_TEMP:%.*]] = alloca %TSi,
// CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0
// CHECK: store i64 %1, i64* [[T0]],
// CHECK: [[T0:%.*]] = bitcast %TSi* [[INT_TEMP]] to %swift.opaque*
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[T0]], %swift.type* @"$sSiN", %swift.type* %T, i64 7)
return x as! T
}
// CHECK: define hidden swiftcc i64 @"$s13generic_casts8anyToIntySiypF"(%Any* noalias nocapture dereferenceable({{.*}}) %0) {{.*}} {
func anyToInt(_ x: Any) -> Int {
return x as! Int
}
@objc protocol ObjCProto1 {
static func forClass()
static func forInstance()
var prop: NSObject { get }
}
@objc protocol ObjCProto2 : ObjCProto1 {}
@objc class ObjCClass {}
// CHECK: define hidden swiftcc %objc_object* @"$s13generic_casts9protoCastyAA10ObjCProto1_So9NSRuncingpAA0E6CClassCF"(%T13generic_casts9ObjCClassC* %0) {{.*}} {
func protoCast(_ x: ObjCClass) -> ObjCProto1 & NSRuncing {
// CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_"
// CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing"
// CHECK: call %objc_object* @swift_dynamicCastObjCProtocolUnconditional(%objc_object* {{%.*}}, i64 2, i8** {{%.*}})
return x as! ObjCProto1 & NSRuncing
}
@objc class ObjCClass2 : NSObject, ObjCProto2 {
class func forClass() {}
class func forInstance() {}
var prop: NSObject { return self }
}
// <rdar://problem/15313840>
// Class existential to opaque archetype cast
// CHECK: define hidden swiftcc void @"$s13generic_casts33classExistentialToOpaqueArchetypeyxAA10ObjCProto1_plF"(%swift.opaque* noalias nocapture sret({{.*}}) %0, %objc_object* %1, %swift.type* %T)
func classExistentialToOpaqueArchetype<T>(_ x: ObjCProto1) -> T {
var x = x
// CHECK: [[X:%.*]] = alloca %T13generic_casts10ObjCProto1P
// CHECK: [[LOCAL:%.*]] = alloca %T13generic_casts10ObjCProto1P
// CHECK: [[LOCAL_OPAQUE:%.*]] = bitcast %T13generic_casts10ObjCProto1P* [[LOCAL]] to %swift.opaque*
// CHECK: [[PROTO_TYPE:%.*]] = call {{.*}}@"$s13generic_casts10ObjCProto1_pMD"
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[LOCAL_OPAQUE]], %swift.type* [[PROTO_TYPE]], %swift.type* %T, i64 7)
return x as! T
}
protocol P {}
protocol Q {}
// CHECK: define hidden swiftcc void @"$s13generic_casts19compositionToMemberyAA1P_pAaC_AA1QpF{{.*}}"(%T13generic_casts1PP* noalias nocapture sret({{.*}}) %0, %T13generic_casts1P_AA1Qp* noalias nocapture dereferenceable({{.*}}) %1) {{.*}} {
func compositionToMember(_ a: P & Q) -> P {
return a
}
| 064c6dab0c0e494971ba989141622d32 | 53.285714 | 270 | 0.65625 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | Riot/Modules/CrossSigning/Setup/CrossSigningSetupCoordinator.swift | apache-2.0 | 1 | // File created from FlowTemplate
// $ createRootCoordinator.sh CrossSigning CrossSigningSetup
/*
Copyright 2021 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
@objcMembers
final class CrossSigningSetupCoordinator: CrossSigningSetupCoordinatorType {
// MARK: - Properties
// MARK: Private
private let parameters: CrossSigningSetupCoordinatorParameters
private let crossSigningService: CrossSigningService
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: CrossSigningSetupCoordinatorDelegate?
// MARK: - Setup
init(parameters: CrossSigningSetupCoordinatorParameters) {
self.parameters = parameters
self.crossSigningService = CrossSigningService()
}
// MARK: - Public methods
func start() {
self.showReauthentication()
}
func toPresentable() -> UIViewController {
return self.parameters.presenter.toPresentable()
}
// MARK: - Private methods
private func showReauthentication() {
let setupCrossSigningRequest = self.crossSigningService.setupCrossSigningRequest()
let reauthenticationParameters = ReauthenticationCoordinatorParameters(session: parameters.session,
presenter: parameters.presenter,
title: parameters.title,
message: parameters.message,
authenticatedEndpointRequest: setupCrossSigningRequest)
let coordinator = ReauthenticationCoordinator(parameters: reauthenticationParameters)
coordinator.delegate = self
self.add(childCoordinator: coordinator)
coordinator.start()
}
private func setupCrossSigning(with authenticationParameters: [String: Any]) {
guard let crossSigning = self.parameters.session.crypto.crossSigning else {
return
}
crossSigning.setup(withAuthParams: authenticationParameters) { [weak self] in
guard let self = self else {
return
}
self.delegate?.crossSigningSetupCoordinatorDidComplete(self)
} failure: { [weak self] error in
guard let self = self else {
return
}
self.delegate?.crossSigningSetupCoordinator(self, didFailWithError: error)
}
}
}
// MARK: - ReauthenticationCoordinatorDelegate
extension CrossSigningSetupCoordinator: ReauthenticationCoordinatorDelegate {
func reauthenticationCoordinatorDidComplete(_ coordinator: ReauthenticationCoordinatorType, withAuthenticationParameters authenticationParameters: [String: Any]?) {
self.setupCrossSigning(with: authenticationParameters ?? [:])
}
func reauthenticationCoordinatorDidCancel(_ coordinator: ReauthenticationCoordinatorType) {
self.delegate?.crossSigningSetupCoordinatorDidCancel(self)
}
func reauthenticationCoordinator(_ coordinator: ReauthenticationCoordinatorType, didFailWithError error: Error) {
self.delegate?.crossSigningSetupCoordinator(self, didFailWithError: error)
}
}
| 813f046f5060a71ad385cecd90d6acb0 | 36.102804 | 168 | 0.653652 | false | false | false | false |
joerocca/GitHawk | refs/heads/master | Classes/Issues/Request/IssueRequestSectionController.swift | mit | 1 | //
// IssueRequestSectionController.swift
// Freetime
//
// Created by Ryan Nystrom on 7/12/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import IGListKit
final class IssueRequestSectionController: ListGenericSectionController<IssueRequestModel> {
override func sizeForItem(at index: Int) -> CGSize {
guard let width = collectionContext?.containerSize.width,
let object = self.object
else { fatalError("Collection context must be set") }
return CGSize(
width: width,
height: object.attributedText.textViewSize(width).height
)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCell(of: IssueRequestCell.self, for: self, at: index) as? IssueRequestCell,
let object = self.object
else { fatalError("Missing collection context, cell incorrect type, or object missing") }
cell.configure(object)
cell.delegate = viewController
return cell
}
}
| 53cee434c1584e8ad04a0c5d5bb3b4fc | 31.757576 | 134 | 0.680851 | false | false | false | false |
intrahouse/aerogear-ios-http | refs/heads/master | AeroGearHttp/Utils.swift | apache-2.0 | 1 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/**
Handy extensions and utilities.
*/
extension String {
public func urlEncode() -> String {
let encodedURL = CFURLCreateStringByAddingPercentEscapes(nil,
self as NSString,
nil,
"!@#$%&*'();:=+,/?[]" as CFString!,
CFStringBuiltInEncodings.UTF8.rawValue)
return encodedURL as! String
}
}
public func merge(_ one: [String: String]?, _ two: [String:String]?) -> [String: String]? {
var dict: [String: String]?
if let one = one {
dict = one
if let two = two {
for (key, value) in two {
dict![key] = value
}
}
} else {
dict = two
}
return dict
}
| 3aaeff5a22c6fa32e41262a5113170df | 27.22449 | 91 | 0.62979 | false | false | false | false |
AlexChekanov/Gestalt | refs/heads/dev | 05-filtering-operators/starter/RxSwiftPlayground/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift | apache-2.0 | 102 | //
// WithLatestFrom.swift
// RxSwift
//
// Created by Yury Korolev on 10/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any.
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- parameter second: Second observable source.
- parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<SecondO: ObservableConvertibleType, ResultType>(_ second: SecondO, resultSelector: @escaping (E, SecondO.E) throws -> ResultType) -> Observable<ResultType> {
return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: resultSelector)
}
/**
Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emitts an element.
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- parameter second: Second observable source.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<SecondO: ObservableConvertibleType>(_ second: SecondO) -> Observable<SecondO.E> {
return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: { $1 })
}
}
final fileprivate class WithLatestFromSink<FirstType, SecondType, O: ObserverType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias ResultType = O.E
typealias Parent = WithLatestFrom<FirstType, SecondType, ResultType>
typealias E = FirstType
fileprivate let _parent: Parent
var _lock = RecursiveLock()
fileprivate var _latest: SecondType?
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let sndSubscription = SingleAssignmentDisposable()
let sndO = WithLatestFromSecond(parent: self, disposable: sndSubscription)
sndSubscription.setDisposable(_parent._second.subscribe(sndO))
let fstSubscription = _parent._first.subscribe(self)
return Disposables.create(fstSubscription, sndSubscription)
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
switch event {
case let .next(value):
guard let latest = _latest else { return }
do {
let res = try _parent._resultSelector(value, latest)
forwardOn(.next(res))
} catch let e {
forwardOn(.error(e))
dispose()
}
case .completed:
forwardOn(.completed)
dispose()
case let .error(error):
forwardOn(.error(error))
dispose()
}
}
}
final fileprivate class WithLatestFromSecond<FirstType, SecondType, O: ObserverType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias ResultType = O.E
typealias Parent = WithLatestFromSink<FirstType, SecondType, O>
typealias E = SecondType
private let _parent: Parent
private let _disposable: Disposable
var _lock: RecursiveLock {
return _parent._lock
}
init(parent: Parent, disposable: Disposable) {
_parent = parent
_disposable = disposable
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
switch event {
case let .next(value):
_parent._latest = value
case .completed:
_disposable.dispose()
case let .error(error):
_parent.forwardOn(.error(error))
_parent.dispose()
}
}
}
final fileprivate class WithLatestFrom<FirstType, SecondType, ResultType>: Producer<ResultType> {
typealias ResultSelector = (FirstType, SecondType) throws -> ResultType
fileprivate let _first: Observable<FirstType>
fileprivate let _second: Observable<SecondType>
fileprivate let _resultSelector: ResultSelector
init(first: Observable<FirstType>, second: Observable<SecondType>, resultSelector: @escaping ResultSelector) {
_first = first
_second = second
_resultSelector = resultSelector
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == ResultType {
let sink = WithLatestFromSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| b95df806e48c23817f27db556adac0ab | 35.38255 | 201 | 0.665375 | false | true | false | false |
threemonkee/VCLabs | refs/heads/master | Pods/Colours/Colours.swift | gpl-2.0 | 1 | //
// Colours.swift
// ColoursDemo
//
// Created by Ben Gordon on 12/27/14.
// Copyright (c) 2014 Ben Gordon. All rights reserved.
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
public typealias Color = UIColor
#else
import AppKit
public typealias Color = NSColor
#endif
public extension Color {
// MARK: - Closure
typealias TransformBlock = CGFloat -> CGFloat
// MARK: - Enums
enum ColorScheme:Int {
case Analagous = 0, Monochromatic, Triad, Complementary
}
enum ColorFormulation:Int {
case RGBA = 0, HSBA, LAB, CMYK
}
enum ColorDistance:Int {
case CIE76 = 0, CIE94, CIE2000
}
enum ColorComparison:Int {
case Darkness = 0, Lightness, Desaturated, Saturated, Red, Green, Blue
}
// MARK: - Color from Hex/RGBA/HSBA/CIE_LAB/CMYK
convenience init(hex: String) {
var rgbInt: UInt64 = 0
let newHex = hex.stringByReplacingOccurrencesOfString("#", withString: "")
let scanner = NSScanner(string: newHex)
scanner.scanHexLongLong(&rgbInt)
let r: CGFloat = CGFloat((rgbInt & 0xFF0000) >> 16)/255.0
let g: CGFloat = CGFloat((rgbInt & 0x00FF00) >> 8)/255.0
let b: CGFloat = CGFloat(rgbInt & 0x0000FF)/255.0
self.init(red: r, green: g, blue: b, alpha: 1.0)
}
convenience init(rgba: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)) {
self.init(red: rgba.r, green: rgba.g, blue: rgba.b, alpha: rgba.a)
}
convenience init(hsba: (h: CGFloat, s: CGFloat, b: CGFloat, a: CGFloat)) {
self.init(hue: hsba.h, saturation: hsba.s, brightness: hsba.b, alpha: hsba.a)
}
convenience init(CIE_LAB: (l: CGFloat, a: CGFloat, b: CGFloat, alpha: CGFloat)) {
// Set Up
var Y = (CIE_LAB.l + 16.0)/116.0
var X = CIE_LAB.a/500 + Y
var Z = Y - CIE_LAB.b/200
// Transform XYZ
let deltaXYZ: TransformBlock = { k in
return (pow(k, 3.0) > 0.008856) ? pow(k, 3.0) : (k - 4/29.0)/7.787
}
X = deltaXYZ(X)*0.95047
Y = deltaXYZ(Y)*1.000
Z = deltaXYZ(Z)*1.08883
// Convert XYZ to RGB
let R = X*3.2406 + (Y * -1.5372) + (Z * -0.4986)
let G = (X * -0.9689) + Y*1.8758 + Z*0.0415
let B = X*0.0557 + (Y * -0.2040) + Z*1.0570
let deltaRGB: TransformBlock = { k in
return (k > 0.0031308) ? 1.055 * (pow(k, (1/2.4))) - 0.055 : k * 12.92
}
self.init(rgba: (deltaRGB(R), deltaRGB(G), deltaRGB(B), CIE_LAB.alpha))
}
convenience init(cmyk: (c: CGFloat, m: CGFloat, y: CGFloat, k: CGFloat)) {
let cmyTransform: TransformBlock = { x in
return x * (1 - cmyk.k) + cmyk.k
}
let C = cmyTransform(cmyk.c)
let M = cmyTransform(cmyk.m)
let Y = cmyTransform(cmyk.y)
self.init(rgba: (1 - C, 1 - M, 1 - Y, 1.0))
}
// MARK: - Color to Hex/RGBA/HSBA/CIE_LAB/CMYK
func hexString() -> String {
let rgbaT = rgba()
let r: Int = Int(rgbaT.r * 255)
let g: Int = Int(rgbaT.g * 255)
let b: Int = Int(rgbaT.b * 255)
let red = NSString(format: "%02x", r)
let green = NSString(format: "%02x", g)
let blue = NSString(format: "%02x", b)
return "#\(red)\(green)\(blue)"
}
func rgba() -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if self.respondsToSelector("getRed:green:blue:alpha:") {
self.getRed(&r, green: &g, blue: &b, alpha: &a)
} else {
let components = CGColorGetComponents(self.CGColor)
r = components[0]
g = components[1]
b = components[2]
a = components[3]
}
return (r, g, b, a)
}
func hsba() -> (h: CGFloat, s: CGFloat, b: CGFloat, a: CGFloat) {
var h: CGFloat = 0
var s: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if self.respondsToSelector("getHue:saturation:brightness:alpha:") {
self.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
}
return (h, s, b, a)
}
func CIE_LAB() -> (l: CGFloat, a: CGFloat, b: CGFloat, alpha: CGFloat) {
// Get XYZ
let xyzT = xyz()
let x = xyzT.x/95.047
let y = xyzT.y/100.000
let z = xyzT.z/108.883
// Transfrom XYZ to L*a*b
let deltaF: TransformBlock = { f in
let transformation = (f > pow((6.0/29.0), 3.0)) ? pow(f, 1.0/3.0) : (1/3) * pow((29.0/6.0), 2.0) * f + 4/29.0
return (transformation)
}
let X = deltaF(x)
let Y = deltaF(y)
let Z = deltaF(z)
let L = 116*Y - 16
let a = 500 * (X - Y)
let b = 200 * (Y - Z)
return (L, a, b, xyzT.alpha)
}
func xyz() -> (x: CGFloat, y: CGFloat, z: CGFloat, alpha: CGFloat) {
// Get RGBA values
let rgbaT = rgba()
// Transfrom values to XYZ
let deltaR: TransformBlock = { R in
return (R > 0.04045) ? pow((R + 0.055)/1.055, 2.40) : (R/12.92)
}
let R = deltaR(rgbaT.r)
let G = deltaR(rgbaT.g)
let B = deltaR(rgbaT.b)
let X = (R*41.24 + G*35.76 + B*18.05)
let Y = (R*21.26 + G*71.52 + B*7.22)
let Z = (R*1.93 + G*11.92 + B*95.05)
return (X, Y, Z, rgbaT.a)
}
func cmyk() -> (c: CGFloat, m: CGFloat, y: CGFloat, k: CGFloat) {
// Convert RGB to CMY
let rgbaT = rgba()
let C = 1 - rgbaT.r
let M = 1 - rgbaT.g
let Y = 1 - rgbaT.b
// Find K
let K = min(1, min(C, min(Y, M)))
if (K == 1) {
return (0, 0, 0, 1)
}
// Convert cmyk
let newCMYK: TransformBlock = { x in
return (x - K)/(1 - K)
}
return (newCMYK(C), newCMYK(M), newCMYK(Y), K)
}
// MARK: - Color Components
func red() -> CGFloat {
return rgba().r
}
func green() -> CGFloat {
return rgba().g
}
func blue() -> CGFloat {
return rgba().b
}
func alpha() -> CGFloat {
return rgba().a
}
func hue() -> CGFloat {
return hsba().h
}
func saturation() -> CGFloat {
return hsba().s
}
func brightness() -> CGFloat {
return hsba().b
}
func CIE_Lightness() -> CGFloat {
return CIE_LAB().l
}
func CIE_a() -> CGFloat {
return CIE_LAB().a
}
func CIE_b() -> CGFloat {
return CIE_LAB().b
}
func cyan() -> CGFloat {
return cmyk().c
}
func magenta() -> CGFloat {
return cmyk().m
}
func yellow() -> CGFloat {
return cmyk().y
}
func keyBlack() -> CGFloat {
return cmyk().k
}
// MARK: - Lighten/Darken Color
func lightenedColor(percentage: CGFloat) -> Color {
return modifiedColor(percentage + 1.0)
}
func darkenedColor(percentage: CGFloat) -> Color {
return modifiedColor(1.0 - percentage)
}
private func modifiedColor(percentage: CGFloat) -> Color {
let hsbaT = hsba()
return Color(hsba: (hsbaT.h, hsbaT.s, hsbaT.b * percentage, hsbaT.a))
}
// MARK: - Contrasting Color
func blackOrWhiteContrastingColor() -> Color {
let rgbaT = rgba()
let value = 1 - ((0.299 * rgbaT.r) + (0.587 * rgbaT.g) + (0.114 * rgbaT.b));
return value > 0.5 ? Color.blackColor() : Color.whiteColor()
}
// MARK: - Complementary Color
func complementaryColor() -> Color {
let hsbaT = hsba()
let newH = Color.addDegree(180.0, staticDegree: hsbaT.h*360.0)
return Color(hsba: (newH, hsbaT.s, hsbaT.b, hsbaT.a))
}
// MARK: - Color Scheme
func colorScheme(type: ColorScheme) -> [Color] {
switch (type) {
case .Analagous:
return Color.analgousColors(self.hsba())
case .Monochromatic:
return Color.monochromaticColors(self.hsba())
case .Triad:
return Color.triadColors(self.hsba())
default:
return Color.complementaryColors(self.hsba())
}
}
private class func analgousColors(hsbaT: (h: CGFloat, s: CGFloat, b: CGFloat, a: CGFloat)) -> [Color] {
return [Color(hsba: (self.addDegree(30, staticDegree: hsbaT.h*360)/360.0, hsbaT.s-0.05, hsbaT.b-0.1, hsbaT.a)),
Color(hsba: (self.addDegree(15, staticDegree: hsbaT.h*360)/360.0, hsbaT.s-0.05, hsbaT.b-0.05, hsbaT.a)),
Color(hsba: (self.addDegree(-15, staticDegree: hsbaT.h*360)/360.0, hsbaT.s-0.05, hsbaT.b-0.05, hsbaT.a)),
Color(hsba: (self.addDegree(-30, staticDegree: hsbaT.h*360)/360.0, hsbaT.s-0.05, hsbaT.b-0.1, hsbaT.a))]
}
private class func monochromaticColors(hsbaT: (h: CGFloat, s: CGFloat, b: CGFloat, a: CGFloat)) -> [Color] {
return [Color(hsba: (hsbaT.h, hsbaT.s/2, hsbaT.b/3, hsbaT.a)),
Color(hsba: (hsbaT.h, hsbaT.s, hsbaT.b/2, hsbaT.a)),
Color(hsba: (hsbaT.h, hsbaT.s/3, 2*hsbaT.b/3, hsbaT.a)),
Color(hsba: (hsbaT.h, hsbaT.s, 4*hsbaT.b/5, hsbaT.a))]
}
private class func triadColors(hsbaT: (h: CGFloat, s: CGFloat, b: CGFloat, a: CGFloat)) -> [Color] {
return [Color(hsba: (self.addDegree(120, staticDegree: hsbaT.h*360)/360.0, 2*hsbaT.s/3, hsbaT.b-0.05, hsbaT.a)),
Color(hsba: (self.addDegree(120, staticDegree: hsbaT.h*360)/360.0, hsbaT.s, hsbaT.b, hsbaT.a)),
Color(hsba: (self.addDegree(240, staticDegree: hsbaT.h*360)/360.0, hsbaT.s, hsbaT.b, hsbaT.a)),
Color(hsba: (self.addDegree(240, staticDegree: hsbaT.h*360)/360.0, 2*hsbaT.s/3, hsbaT.b-0.05, hsbaT.a))]
}
private class func complementaryColors(hsbaT: (h: CGFloat, s: CGFloat, b: CGFloat, a: CGFloat)) -> [Color] {
return [Color(hsba: (hsbaT.h, hsbaT.s, 4*hsbaT.b/5, hsbaT.a)),
Color(hsba: (hsbaT.h, 5*hsbaT.s/7, hsbaT.b, hsbaT.a)),
Color(hsba: (self.addDegree(180, staticDegree: hsbaT.h*360)/360.0, hsbaT.s, hsbaT.b, hsbaT.a)),
Color(hsba: (self.addDegree(180, staticDegree: hsbaT.h*360)/360.0, 5*hsbaT.s/7, hsbaT.b, hsbaT.a))]
}
// MARK: - Predefined Colors
// MARK: -
// MARK: System Colors
class func infoBlueColor() -> Color
{
return self.colorWith(47, G:112, B:225, A:1.0)
}
class func successColor() -> Color
{
return self.colorWith(83, G:215, B:106, A:1.0)
}
class func warningColor() -> Color
{
return self.colorWith(221, G:170, B:59, A:1.0)
}
class func dangerColor() -> Color
{
return self.colorWith(229, G:0, B:15, A:1.0)
}
// MARK: Whites
class func antiqueWhiteColor() -> Color
{
return self.colorWith(250, G:235, B:215, A:1.0)
}
class func oldLaceColor() -> Color
{
return self.colorWith(253, G:245, B:230, A:1.0)
}
class func ivoryColor() -> Color
{
return self.colorWith(255, G:255, B:240, A:1.0)
}
class func seashellColor() -> Color
{
return self.colorWith(255, G:245, B:238, A:1.0)
}
class func ghostWhiteColor() -> Color
{
return self.colorWith(248, G:248, B:255, A:1.0)
}
class func snowColor() -> Color
{
return self.colorWith(255, G:250, B:250, A:1.0)
}
class func linenColor() -> Color
{
return self.colorWith(250, G:240, B:230, A:1.0)
}
// MARK: Grays
class func black25PercentColor() -> Color
{
return Color(white:0.25, alpha:1.0)
}
class func black50PercentColor() -> Color
{
return Color(white:0.5, alpha:1.0)
}
class func black75PercentColor() -> Color
{
return Color(white:0.75, alpha:1.0)
}
class func warmGrayColor() -> Color
{
return self.colorWith(133, G:117, B:112, A:1.0)
}
class func coolGrayColor() -> Color
{
return self.colorWith(118, G:122, B:133, A:1.0)
}
class func charcoalColor() -> Color
{
return self.colorWith(34, G:34, B:34, A:1.0)
}
// MARK: Blues
class func tealColor() -> Color
{
return self.colorWith(28, G:160, B:170, A:1.0)
}
class func steelBlueColor() -> Color
{
return self.colorWith(103, G:153, B:170, A:1.0)
}
class func robinEggColor() -> Color
{
return self.colorWith(141, G:218, B:247, A:1.0)
}
class func pastelBlueColor() -> Color
{
return self.colorWith(99, G:161, B:247, A:1.0)
}
class func turquoiseColor() -> Color
{
return self.colorWith(112, G:219, B:219, A:1.0)
}
class func skyBlueColor() -> Color
{
return self.colorWith(0, G:178, B:238, A:1.0)
}
class func indigoColor() -> Color
{
return self.colorWith(13, G:79, B:139, A:1.0)
}
class func denimColor() -> Color
{
return self.colorWith(67, G:114, B:170, A:1.0)
}
class func blueberryColor() -> Color
{
return self.colorWith(89, G:113, B:173, A:1.0)
}
class func cornflowerColor() -> Color
{
return self.colorWith(100, G:149, B:237, A:1.0)
}
class func babyBlueColor() -> Color
{
return self.colorWith(190, G:220, B:230, A:1.0)
}
class func midnightBlueColor() -> Color
{
return self.colorWith(13, G:26, B:35, A:1.0)
}
class func fadedBlueColor() -> Color
{
return self.colorWith(23, G:137, B:155, A:1.0)
}
class func icebergColor() -> Color
{
return self.colorWith(200, G:213, B:219, A:1.0)
}
class func waveColor() -> Color
{
return self.colorWith(102, G:169, B:251, A:1.0)
}
// MARK: Greens
class func emeraldColor() -> Color
{
return self.colorWith(1, G:152, B:117, A:1.0)
}
class func grassColor() -> Color
{
return self.colorWith(99, G:214, B:74, A:1.0)
}
class func pastelGreenColor() -> Color
{
return self.colorWith(126, G:242, B:124, A:1.0)
}
class func seafoamColor() -> Color
{
return self.colorWith(77, G:226, B:140, A:1.0)
}
class func paleGreenColor() -> Color
{
return self.colorWith(176, G:226, B:172, A:1.0)
}
class func cactusGreenColor() -> Color
{
return self.colorWith(99, G:111, B:87, A:1.0)
}
class func chartreuseColor() -> Color
{
return self.colorWith(69, G:139, B:0, A:1.0)
}
class func hollyGreenColor() -> Color
{
return self.colorWith(32, G:87, B:14, A:1.0)
}
class func oliveColor() -> Color
{
return self.colorWith(91, G:114, B:34, A:1.0)
}
class func oliveDrabColor() -> Color
{
return self.colorWith(107, G:142, B:35, A:1.0)
}
class func moneyGreenColor() -> Color
{
return self.colorWith(134, G:198, B:124, A:1.0)
}
class func honeydewColor() -> Color
{
return self.colorWith(216, G:255, B:231, A:1.0)
}
class func limeColor() -> Color
{
return self.colorWith(56, G:237, B:56, A:1.0)
}
class func cardTableColor() -> Color
{
return self.colorWith(87, G:121, B:107, A:1.0)
}
// MARK: Reds
class func salmonColor() -> Color
{
return self.colorWith(233, G:87, B:95, A:1.0)
}
class func brickRedColor() -> Color
{
return self.colorWith(151, G:27, B:16, A:1.0)
}
class func easterPinkColor() -> Color
{
return self.colorWith(241, G:167, B:162, A:1.0)
}
class func grapefruitColor() -> Color
{
return self.colorWith(228, G:31, B:54, A:1.0)
}
class func pinkColor() -> Color
{
return self.colorWith(255, G:95, B:154, A:1.0)
}
class func indianRedColor() -> Color
{
return self.colorWith(205, G:92, B:92, A:1.0)
}
class func strawberryColor() -> Color
{
return self.colorWith(190, G:38, B:37, A:1.0)
}
class func coralColor() -> Color
{
return self.colorWith(240, G:128, B:128, A:1.0)
}
class func maroonColor() -> Color
{
return self.colorWith(80, G:4, B:28, A:1.0)
}
class func watermelonColor() -> Color
{
return self.colorWith(242, G:71, B:63, A:1.0)
}
class func tomatoColor() -> Color
{
return self.colorWith(255, G:99, B:71, A:1.0)
}
class func pinkLipstickColor() -> Color
{
return self.colorWith(255, G:105, B:180, A:1.0)
}
class func paleRoseColor() -> Color
{
return self.colorWith(255, G:228, B:225, A:1.0)
}
class func crimsonColor() -> Color
{
return self.colorWith(187, G:18, B:36, A:1.0)
}
// MARK: Purples
class func eggplantColor() -> Color
{
return self.colorWith(105, G:5, B:98, A:1.0)
}
class func pastelPurpleColor() -> Color
{
return self.colorWith(207, G:100, B:235, A:1.0)
}
class func palePurpleColor() -> Color
{
return self.colorWith(229, G:180, B:235, A:1.0)
}
class func coolPurpleColor() -> Color
{
return self.colorWith(140, G:93, B:228, A:1.0)
}
class func violetColor() -> Color
{
return self.colorWith(191, G:95, B:255, A:1.0)
}
class func plumColor() -> Color
{
return self.colorWith(139, G:102, B:139, A:1.0)
}
class func lavenderColor() -> Color
{
return self.colorWith(204, G:153, B:204, A:1.0)
}
class func raspberryColor() -> Color
{
return self.colorWith(135, G:38, B:87, A:1.0)
}
class func fuschiaColor() -> Color
{
return self.colorWith(255, G:20, B:147, A:1.0)
}
class func grapeColor() -> Color
{
return self.colorWith(54, G:11, B:88, A:1.0)
}
class func periwinkleColor() -> Color
{
return self.colorWith(135, G:159, B:237, A:1.0)
}
class func orchidColor() -> Color
{
return self.colorWith(218, G:112, B:214, A:1.0)
}
// MARK: Yellows
class func goldenrodColor() -> Color
{
return self.colorWith(215, G:170, B:51, A:1.0)
}
class func yellowGreenColor() -> Color
{
return self.colorWith(192, G:242, B:39, A:1.0)
}
class func bananaColor() -> Color
{
return self.colorWith(229, G:227, B:58, A:1.0)
}
class func mustardColor() -> Color
{
return self.colorWith(205, G:171, B:45, A:1.0)
}
class func buttermilkColor() -> Color
{
return self.colorWith(254, G:241, B:181, A:1.0)
}
class func goldColor() -> Color
{
return self.colorWith(139, G:117, B:18, A:1.0)
}
class func creamColor() -> Color
{
return self.colorWith(240, G:226, B:187, A:1.0)
}
class func lightCreamColor() -> Color
{
return self.colorWith(240, G:238, B:215, A:1.0)
}
class func wheatColor() -> Color
{
return self.colorWith(240, G:238, B:215, A:1.0)
}
class func beigeColor() -> Color
{
return self.colorWith(245, G:245, B:220, A:1.0)
}
// MARK: Oranges
class func peachColor() -> Color
{
return self.colorWith(242, G:187, B:97, A:1.0)
}
class func burntOrangeColor() -> Color
{
return self.colorWith(184, G:102, B:37, A:1.0)
}
class func pastelOrangeColor() -> Color
{
return self.colorWith(248, G:197, B:143, A:1.0)
}
class func cantaloupeColor() -> Color
{
return self.colorWith(250, G:154, B:79, A:1.0)
}
class func carrotColor() -> Color
{
return self.colorWith(237, G:145, B:33, A:1.0)
}
class func mandarinColor() -> Color
{
return self.colorWith(247, G:145, B:55, A:1.0)
}
// MARK: Browns
class func chiliPowderColor() -> Color
{
return self.colorWith(199, G:63, B:23, A:1.0)
}
class func burntSiennaColor() -> Color
{
return self.colorWith(138, G:54, B:15, A:1.0)
}
class func chocolateColor() -> Color
{
return self.colorWith(94, G:38, B:5, A:1.0)
}
class func coffeeColor() -> Color
{
return self.colorWith(141, G:60, B:15, A:1.0)
}
class func cinnamonColor() -> Color
{
return self.colorWith(123, G:63, B:9, A:1.0)
}
class func almondColor() -> Color
{
return self.colorWith(196, G:142, B:72, A:1.0)
}
class func eggshellColor() -> Color
{
return self.colorWith(252, G:230, B:201, A:1.0)
}
class func sandColor() -> Color
{
return self.colorWith(222, G:182, B:151, A:1.0)
}
class func mudColor() -> Color
{
return self.colorWith(70, G:45, B:29, A:1.0)
}
class func siennaColor() -> Color
{
return self.colorWith(160, G:82, B:45, A:1.0)
}
class func dustColor() -> Color
{
return self.colorWith(236, G:214, B:197, A:1.0)
}
// MARK: - Private Helpers
private class func colorWith(R: CGFloat, G: CGFloat, B: CGFloat, A: CGFloat) -> Color {
return Color(rgba: (R/255.0, G/255.0, B/255.0, A))
}
private class func addDegree(addDegree: CGFloat, staticDegree: CGFloat) -> CGFloat {
let s = staticDegree + addDegree;
if (s > 360) {
return s - 360;
}
else if (s < 0) {
return -1 * s;
}
else {
return s;
}
}
}
| 4e41b740ff58120b7a7e1796914375df | 24.923963 | 121 | 0.52222 | false | false | false | false |
CoderYK/PhotoBrowser | refs/heads/master | PhotoBrowser/photoBrowser/Classes/PhotoBrowser/BrowserViewCell.swift | apache-2.0 | 1 | //
// BrowserViewCell.swift
// photoBrowser
//
// Created by yk on 16/6/19.
// Copyright © 2016年 coderYK. All rights reserved.
//
import UIKit
import SDWebImage
class BrowserViewCell: UICollectionViewCell {
// MARK:- 定义属性
var shop : Shop? {
didSet {
// 1.空值校验
guard let shop = shop else {
return
}
// 2.取出 Image 对象
var image = SDWebImageManager.sharedManager().imageCache.imageFromMemoryCacheForKey(shop.q_pic_url)
if image == nil {
image = UIImage(named: "empty_picture")
}
// 3.根据图片计算 imageView 的大小
imageView.frame = calculateImageViewFrame(image)
// 4.设置 imageView 的图片
guard let url = NSURL(string: shop.z_pic_url) else {
imageView.image = image
return
}
imageView.sd_setImageWithURL(url, placeholderImage: image) { (image, _, _, _) in
//重新计算图片的尺寸
self.imageView.frame = calculateImageViewFrame(image)
}
}
}
// MARK:- 懒加载属性
lazy var imageView : UIImageView = UIImageView()
// MARK:- 构造函数
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(imageView)
}
//required: 如果有实现父类的某一个构造函数,那么必须同时实现使用required修饰的构造函数
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
contentView.addSubview(imageView)
}
}
| 71f50651047068bee3ca48b4f2e19517 | 25.196721 | 111 | 0.534418 | false | false | false | false |
smud/TextUserInterface | refs/heads/master | Sources/TextUserInterface/Commands/AdminCommands.swift | apache-2.0 | 1 | //
// AdminCommands.swift
//
// This source file is part of the SMUD open source project
//
// Copyright (c) 2016 SMUD project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SMUD project authors
//
import Foundation
import Smud
class AdminCommands {
func register(with router: CommandRouter) {
router["area list"] = areaList
router["area build"] = areaBuild
router["area edit"] = areaEdit
router["area save"] = areaSave
router["area"] = area
router["room list"] = roomList
router["room info"] = roomInfo
router["room"] = room
router["dig north"] = { return self.dig(.north, $0) }
router["dig east"] = { return self.dig(.east, $0) }
router["dig south"] = { return self.dig(.south, $0) }
router["dig west"] = { return self.dig(.west, $0) }
router["dig up"] = { return self.dig(.up, $0) }
router["dig down"] = { return self.dig(.down, $0) }
router["dig"] = dig
}
func areaList(context: CommandContext) -> CommandAction {
context.send("List of areas:")
let areas = context.world.areasById.sorted { lhs, rhs in
lhs.value.title.caseInsensitiveCompare(rhs.value.title) == .orderedAscending }
let areaList = areas.map { v in " #\(v.value.id) \(v.value.title)" }.joined(separator: "\n")
context.send(areaList.isEmpty ? " none." : areaList)
return .accept
}
func areaBuild(context: CommandContext) -> CommandAction {
guard let player = context.creature as? Player else { return .next }
guard let currentRoom = context.creature.room else {
context.send("You are not standing in any area.")
return .accept
}
let newInstance = currentRoom.areaInstance.area.createInstance(mode: .forEditing)
newInstance.buildMap()
let room: Room
if let previousRoom = newInstance.roomsById[currentRoom.id] {
room = previousRoom
} else {
context.send("Can't find your current room in newly created instance. Probably it has been removed. Relocating to area's default room")
guard let defaultRoom = newInstance.roomsById.values.first else {
context.send("Area \(newInstance.area.id) is empty")
newInstance.area.removeInstance(newInstance)
return .accept
}
room = defaultRoom
}
player.room = room
player.editedInstances.insert(newInstance)
context.send("Relocated to \(Link(room: room)) (editing mode).")
context.creature.look()
return .accept
}
func areaEdit(context: CommandContext) -> CommandAction {
guard let player = context.creature as? Player else { return .next }
guard let room = player.room else {
context.send("You are not standing in any area.")
return .accept
}
let instance = room.areaInstance
guard !player.editedInstances.contains(instance) else {
context.send("Already editing #\(instance.area.id):\(instance.index).")
return .accept
}
player.editedInstances.insert(instance)
context.send("Enabled editing on #\(instance.area.id):\(instance.index).")
context.creature.look()
return .accept
}
func areaSave(context: CommandContext) -> CommandAction {
guard let area = context.area else {
context.send("You aren't standing in any area.")
return .accept
}
area.scheduleForSaving()
context.send("Area #\(area.id) scheduled for saving.")
return .accept
}
func area(context: CommandContext) -> CommandAction {
var result = ""
if let subcommand = context.args.scanWord() {
result += "Unknown subcommand: \(subcommand)\n"
}
result += "Available subcommands: delete, list, new, rename"
return .showUsage(result)
}
func roomList(context: CommandContext) throws -> CommandAction {
guard let areaInstance = context.scanAreaInstance(optional: true) else { return .accept }
context.send("List of #\(areaInstance.area.id):\(areaInstance.index) rooms:")
let rooms = areaInstance.roomsById.values
.sorted { $0.id < $1.id }
.map { return " #\($0.id) \($0.title)" }
.joined(separator: "\n")
context.send(rooms.isEmpty ? " none." : rooms)
return .accept
}
func roomInfo(context: CommandContext) -> CommandAction {
let room: Room
if let link = context.args.scanLink() {
guard let resolvedRoom = context.world.resolveRoom(link: link, defaultInstance: context.creature.room?.areaInstance) else {
context.send("Cant find room \(link)")
return .accept
}
room = resolvedRoom
} else {
guard let currentRoom = context.creature.room else {
context.send("You are not standing in any room.")
return .accept
}
if let directionWord = context.args.scanWord() {
guard let direction = Direction(rawValue: directionWord) else {
context.send("Expected link or direction.")
return .accept
}
guard let neighborLink = currentRoom.exits[direction] else {
context.send("There's no room in that direction from you.")
return .accept
}
guard let neighborRoom = currentRoom.resolveLink(link: neighborLink) else {
context.send("Can't find neighbor room.")
return .accept
}
room = neighborRoom
} else {
room = currentRoom
}
}
var fields = [(title: String, content: String)]()
fields.append((title: "Link", content: "\(Link(room: room))"))
for direction in Direction.orderedDirections {
let directionName = direction.rawValue.capitalizingFirstLetter()
let directionLink = room.exits[direction]?.description ?? "none"
fields.append((title: directionName, content: directionLink))
}
context.send(fields.map{ "\($0.title): \($0.content)" }.joined(separator: "\n"))
return .accept
}
func room(context: CommandContext) -> CommandAction {
var result = ""
if let subcommand = context.args.scanWord() {
result += "Unknown subcommand: \(subcommand)\n"
}
result += "Available subcommands: delete, list, new, rename"
return .showUsage(result)
}
func dig(_ direction: Direction, _ context: CommandContext) -> CommandAction {
return dig(direction: direction, context: context)
}
func dig(direction: Direction, context: CommandContext) -> CommandAction {
guard let player = context.creature as? Player else { return .next }
guard let currentRoom = context.creature.room else {
context.send("You are not standing in any room, there's nowhere to dig.")
return .accept
}
guard player.editedInstances.contains(currentRoom.areaInstance) else {
context.send("Editing is disabled on this area instance. Consider 'area edit' and 'area build' commands to enter editing mode.")
return .accept
}
guard let roomId = context.args.scanWord() else {
context.send("Expected room identifier.")
return .accept
}
guard let destinationRoom = currentRoom.areaInstance.digRoom(from: currentRoom, direction: direction, id: roomId) else {
context.send("Failed to dig room.")
return .accept
}
context.creature.room = destinationRoom
context.creature.look()
return .accept
}
func dig(context: CommandContext) -> CommandAction {
var result = ""
if let subcommand = context.args.scanWord() {
result += "Unknown subcommand: \(subcommand)\n"
}
result += "Available subcommands:\n"
result += " north <room id>\n";
result += " south <room id>\n";
result += " east <room id>\n";
result += " west <room id>\n";
result += " up <room id>\n";
result += " down <room id>";
return .showUsage(result)
}
}
| deaf9ff11fce0f096b12faebe95f4cdf | 36.166667 | 147 | 0.585719 | false | false | false | false |
jondwillis/ReactiveReSwift-Router | refs/heads/master | ReactiveReSwiftRouter/NavigationActions.swift | mit | 1 | //
// NavigationAction.swift
// Meet
//
// Created by Benjamin Encz on 11/27/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import ReactiveReSwift
/// Exports the type map needed for using ReSwiftRouter with a Recording Store
public let typeMap: [String: StandardActionConvertible.Type] =
["RE_SWIFT_ROUTER_SET_ROUTE": SetRouteAction.self]
public struct SetRouteAction: StandardActionConvertible {
let route: Route
let animated: Bool
public static let type = "RE_SWIFT_ROUTER_SET_ROUTE"
public init (_ route: Route, animated: Bool = true) {
self.route = route
self.animated = animated
}
public init(_ action: StandardAction) {
self.route = action.payload!["route"] as! Route
self.animated = action.payload!["animated"] as! Bool
}
public func toStandardAction() -> StandardAction {
return StandardAction(
type: SetRouteAction.type,
payload: ["route": route as AnyObject, "animated": animated as AnyObject],
isTypedAction: true
)
}
}
public struct SetRouteSpecificData: Action {
let route: Route
let data: Any
public init(route: Route, data: Any) {
self.route = route
self.data = data
}
}
| 306b5a2d6388e5f2390fcb2f70e9b0d9 | 24.979592 | 86 | 0.649647 | false | false | false | false |
jesselucas/UILabel-Animate.swift | refs/heads/master | UILabel+Animate.swift | mit | 1 | //
// UILabel+Animate.swift
//
// Created by Jesse Lucas on 1/8/15.
// Copyright (c) 2015 Jesse Lucas. All rights reserved.
//
import Foundation
class TimerManager {
var timers = [NSObject : dispatch_source_t]()
func createTimer(key keyName:NSObject) -> dispatch_source_t {
let timer:dispatch_source_t = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue())
timers[keyName] = timer
return timer
}
func getTimer(key keyName:NSObject) -> dispatch_source_t {
return timers[keyName]!
}
func removeTimer(key keyName:NSObject) {
//remove timer from dictionary
timers.removeValueForKey(keyName)
}
}
let timers = TimerManager()
public extension UILabel {
public func animate(from fromValue:Int, to toValue:Int, duration durationValue:Double = 0.4, useTimeFormat useTimeFromatValue:Bool = false, numberFormatter numberFormatterValue:NSNumberFormatter! = nil, appendText appendTextValue:String = "") {
self.text = String(fromValue.hashValue)
let interval:Double = 10/30
let nsec:UInt64 = UInt64(interval) * NSEC_PER_SEC
let dispatchTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(nsec))
var previousProgress:NSTimeInterval = 0
var progress:NSTimeInterval = 0
var lastUpdate:NSTimeInterval = NSDate.timeIntervalSinceReferenceDate();
var displayValue:Double = Double(fromValue)
var percent:Double = 0
var now:NSTimeInterval = 0
//create timer
timers.createTimer(key: self)
func update() {
now = NSDate.timeIntervalSinceReferenceDate()
progress += now - lastUpdate
lastUpdate = now
if (progress >= durationValue) {
dispatch_source_cancel(timers.getTimer(key: self))
timers.removeTimer(key: self)
progress = durationValue;
}
let percent = progress / durationValue
let change:Double = Double(toValue) - Double(fromValue)
var easedValue:Double = Easing.easeOutExpo(time: durationValue * percent, start: Double(fromValue), change: change, duration: durationValue)
if (useTimeFromatValue == true) {
self.text = Int(easedValue).time + appendTextValue
} else {
if (numberFormatterValue != nil) {
self.text = numberFormatterValue.stringFromNumber(easedValue)! + appendTextValue
} else {
self.text = "\(Int(easedValue))\(appendTextValue)"
}
}
}
dispatch_source_set_timer(timers.getTimer(key: self), dispatchTime, nsec, 0)
dispatch_source_set_event_handler(timers.getTimer(key: self), update)
//start timer
dispatch_resume(timers.getTimer(key: self))
//call update right away
update()
}
} | 342f754662739f8e295ddd24bd8293b2 | 35.046512 | 248 | 0.601162 | false | false | false | false |
cwwise/CWWeChat | refs/heads/master | CWWeChat/MainClass/Base/CWTableViewManager/CWTableViewCell.swift | mit | 2 | //
// CWTableViewCell.swift
// CWWeChat
//
// Created by wei chen on 2017/2/11.
// Copyright © 2017年 chenwei. All rights reserved.
//
import UIKit
import SnapKit
public protocol CWTableViewCellDelegate: NSObjectProtocol {
func cellDidSelect()
}
public enum CWCellLineStyle {
case none
case `default`
case fill
}
public class CWTableViewCell: UITableViewCell {
public weak var delegate: CWTableViewCellDelegate?
public var item: CWTableViewItem!
public var leftSeparatorSpace: CGFloat = 15 {
didSet {
self.setNeedsDisplay()
}
}
public var rightSeparatorSpace: CGFloat = 0 {
didSet {
self.setNeedsDisplay()
}
}
public var topLineStyle: CWCellLineStyle = .none {
didSet {
self.setNeedsDisplay()
}
}
public var bottomLineStyle: CWCellLineStyle = .none {
didSet {
self.setNeedsDisplay()
}
}
lazy var titleLabel:UILabel = {
let titleLabel = UILabel()
titleLabel.textColor = UIColor.black
titleLabel.font = kCWItemTitleFont
return titleLabel
}()
lazy var rightLabel:UILabel = {
let rightLabel = UILabel()
rightLabel.textColor = UIColor.gray
rightLabel.font = kCWItemsubTitleFont
return rightLabel
}()
lazy var rightImageView:UIImageView = {
let rightImageView = UIImageView()
rightImageView.contentMode = .scaleAspectFill
rightImageView.clipsToBounds = true
rightImageView.layer.cornerRadius = 5
return rightImageView
}()
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(titleLabel)
self.contentView.addSubview(rightLabel)
self.contentView.addSubview(rightImageView)
_addSnap()
}
//MARK: 添加约束
func _addSnap() {
self.titleLabel.snp.makeConstraints { (make) in
make.centerY.equalTo(self.contentView)
make.left.equalTo(self.contentView).offset(kCWCellLeftMargin)
}
self.rightLabel.snp.makeConstraints { (make) in
make.right.equalTo(self.contentView)
make.centerY.equalTo(self.contentView)
make.left.greaterThanOrEqualTo(self.titleLabel.snp.right).offset(20)
}
self.rightImageView.snp.makeConstraints { (make) in
make.centerY.equalTo(self.contentView)
make.top.equalTo(10)
make.width.equalTo(self.rightImageView.snp.height)
make.right.equalTo(self.rightLabel.snp.left).offset(-2)
}
}
///设置item对象
public func cellWillAppear() {
titleLabel.text = item.title
rightLabel.text = item.subTitle
if item.showDisclosureIndicator == false {
self.accessoryType = .none
self.rightLabel.snp.updateConstraints({ (make) in
make.right.equalTo(self.contentView).offset(-kCWCellLeftMargin)
})
} else {
self.accessoryType = .disclosureIndicator
self.rightLabel.snp.updateConstraints({ (make) in
make.right.equalTo(self.contentView)
})
}
rightImageView.kf.setImage(with: item.rightImageURL, placeholder: nil)
if item.disableHighlight {
self.selectionStyle = .none
} else {
self.selectionStyle = .default
}
}
public override func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else {
return
}
context.setLineWidth(1)
context.setStrokeColor(UIColor(hex: "#e9e9e9").cgColor)
if self.topLineStyle != .none {
context.beginPath()
let startX = self.topLineStyle == .fill ? 0 : leftSeparatorSpace
let endX = self.width - self.rightSeparatorSpace
context.move(to: CGPoint(x: startX, y: 0))
context.addLine(to: CGPoint(x: endX, y: 0))
context.strokePath()
}
if self.bottomLineStyle != .none {
context.beginPath()
let startX = self.topLineStyle == .fill ? 0 : leftSeparatorSpace
let endX = self.width - self.rightSeparatorSpace
context.move(to: CGPoint(x: startX, y: self.height))
context.addLine(to: CGPoint(x: endX, y: self.height))
context.strokePath()
}
}
}
| 85be2c60c57e5ee4649b6c58c1244c68 | 27.781065 | 80 | 0.590255 | false | false | false | false |
Anvics/Amber | refs/heads/master | Example/Pods/Differ/Sources/Differ/NestedDiff.swift | mit | 2 | public struct NestedDiff: DiffProtocol {
public typealias Index = Int
public enum Element {
case deleteSection(Int)
case insertSection(Int)
case deleteElement(Int, section: Int)
case insertElement(Int, section: Int)
}
/// Returns the position immediately after the given index.
///
/// - Parameters:
/// - i: A valid index of the collection. `i` must be less than `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Int) -> Int {
return i + 1
}
public let elements: [Element]
}
public extension Collection
where Iterator.Element: Collection {
/// Creates a diff between the callee and `other` collection. It diffs elements two levels deep (therefore "nested")
///
/// - Parameters:
/// - other: a collection to compare the calee to
/// - Returns: a `NestedDiff` between the calee and `other` collection
public func nestedDiff(
to: Self,
isEqualSection: EqualityChecker<Self>,
isEqualElement: NestedElementEqualityChecker<Self>
) -> NestedDiff {
let diffTraces = outputDiffPathTraces(to: to, isEqual: isEqualSection)
// Diff sections
let sectionDiff = Diff(traces: diffTraces).map { element -> NestedDiff.Element in
switch element {
case let .delete(at):
return .deleteSection(at)
case let .insert(at):
return .insertSection(at)
}
}
// Diff matching sections (moves, deletions, insertions)
let filterMatchPoints = { (trace: Trace) -> Bool in
if case .matchPoint = trace.type() {
return true
}
return false
}
// offset & section
let matchingSectionTraces = diffTraces
.filter(filterMatchPoints)
let fromSections = matchingSectionTraces.map {
itemOnStartIndex(advancedBy: $0.from.x)
}
let toSections = matchingSectionTraces.map {
to.itemOnStartIndex(advancedBy: $0.from.y)
}
let elementDiff = zip(zip(fromSections, toSections), matchingSectionTraces)
.flatMap { (args) -> [NestedDiff.Element] in
let (sections, trace) = args
return sections.0.diff(sections.1, isEqual: isEqualElement).map { diffElement -> NestedDiff.Element in
switch diffElement {
case let .delete(at):
return .deleteElement(at, section: trace.from.x)
case let .insert(at):
return .insertElement(at, section: trace.from.y)
}
}
}
return NestedDiff(elements: sectionDiff + elementDiff)
}
}
public extension Collection
where Iterator.Element: Collection,
Iterator.Element.Iterator.Element: Equatable {
/// - SeeAlso: `nestedDiff(to:isEqualSection:isEqualElement:)`
public func nestedDiff(
to: Self,
isEqualSection: EqualityChecker<Self>
) -> NestedDiff {
return nestedDiff(
to: to,
isEqualSection: isEqualSection,
isEqualElement: { $0 == $1 }
)
}
}
public extension Collection
where Iterator.Element: Collection,
Iterator.Element: Equatable {
/// - SeeAlso: `nestedDiff(to:isEqualSection:isEqualElement:)`
public func nestedDiff(
to: Self,
isEqualElement: NestedElementEqualityChecker<Self>
) -> NestedDiff {
return nestedDiff(
to: to,
isEqualSection: { $0 == $1 },
isEqualElement: isEqualElement
)
}
}
public extension Collection
where Iterator.Element: Collection,
Iterator.Element: Equatable,
Iterator.Element.Iterator.Element: Equatable {
/// - SeeAlso: `nestedDiff(to:isEqualSection:isEqualElement:)`
public func nestedDiff(to: Self) -> NestedDiff {
return nestedDiff(
to: to,
isEqualSection: { $0 == $1 },
isEqualElement: { $0 == $1 }
)
}
}
extension NestedDiff.Element: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case let .deleteElement(row, section):
return "DE(\(row),\(section))"
case let .deleteSection(section):
return "DS(\(section))"
case let .insertElement(row, section):
return "IE(\(row),\(section))"
case let .insertSection(section):
return "IS(\(section))"
}
}
}
| f881c154c4f1f5431443d53df486c69a | 30.181208 | 120 | 0.586741 | false | false | false | false |
delbert06/DYZB | refs/heads/master | DYZB/DYZB/AnChorModel.swift | mit | 1 | //
// AnChorModel.swift
// DYZB
//
// Created by 胡迪 on 2016/12/14.
// Copyright © 2016年 D.Huhu. All rights reserved.
//
import UIKit
class AnChorModel: NSObject {
// 房间ID
var room_id : Int = 0
// 房间图片对应的URL
var vertical_src : String = ""
// 判断手机直播还是电脑直播 0是电脑 1是手机
var isVertical : Int = 0
// 房间名称
var room_name = ""
// 昵称
var nickname = ""
var anchor_city : String = ""
//在线人数
var online = 0
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| 5d1cd415a91c2d679a08184f9ada310e | 16.102564 | 73 | 0.532234 | false | false | false | false |
vadymmarkov/PitchAssistant | refs/heads/master | Source/Transform/Strategies/FFTTransformer.swift | mit | 1 | import AVFoundation
import Accelerate
final class FFTTransformer: Transformer {
func transform(buffer: AVAudioPCMBuffer) throws -> Buffer {
let frameCount = buffer.frameLength
let log2n = UInt(round(log2(Double(frameCount))))
let bufferSizePOT = Int(1 << log2n)
let inputCount = bufferSizePOT / 2
let fftSetup = vDSP_create_fftsetup(log2n, Int32(kFFTRadix2))
var realp = [Float](repeating: 0, count: inputCount)
var imagp = [Float](repeating: 0, count: inputCount)
var output = DSPSplitComplex(realp: &realp, imagp: &imagp)
let windowSize = bufferSizePOT
var transferBuffer = [Float](repeating: 0, count: windowSize)
var window = [Float](repeating: 0, count: windowSize)
vDSP_hann_window(&window, vDSP_Length(windowSize), Int32(vDSP_HANN_NORM))
vDSP_vmul((buffer.floatChannelData?.pointee)!, 1, window,
1, &transferBuffer, 1, vDSP_Length(windowSize))
let temp = UnsafePointer<Float>(transferBuffer)
temp.withMemoryRebound(to: DSPComplex.self, capacity: transferBuffer.count) { (typeConvertedTransferBuffer) -> Void in
vDSP_ctoz(typeConvertedTransferBuffer, 2, &output, 1, vDSP_Length(inputCount))
}
vDSP_fft_zrip(fftSetup!, &output, 1, log2n, FFTDirection(FFT_FORWARD))
var magnitudes = [Float](repeating: 0.0, count: inputCount)
vDSP_zvmags(&output, 1, &magnitudes, 1, vDSP_Length(inputCount))
var normalizedMagnitudes = [Float](repeating: 0.0, count: inputCount)
vDSP_vsmul(sqrtq(magnitudes), 1, [2.0 / Float(inputCount)],
&normalizedMagnitudes, 1, vDSP_Length(inputCount))
let buffer = Buffer(elements: normalizedMagnitudes)
vDSP_destroy_fftsetup(fftSetup)
return buffer
}
// MARK: - Helpers
func sqrtq(_ x: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vvsqrtf(&results, x, [Int32(x.count)])
return results
}
}
| cf07ed7dd9020635b38fa399e7bdfaef | 34.148148 | 122 | 0.69705 | false | false | false | false |
King-Wizard/Swift-Spotify-Like-Carousel | refs/heads/master | PagesTest/PagesTest/ViewController.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015
// King-Wizard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class ViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var pageViewController: UIPageViewController!
var pageControl: UIPageControl!
let arrayInformationMessages = [(title:"title 1", description:"description for \n title 1"),
(title:"title 2", description:"description for \n title 2"),
(title:"title 3", description:"description for \n title 3"),
(title:"title 4", description:"description for \n title 4")]
var arrayViewControllers: [UIViewController] = []
override func viewDidLoad() {
super.viewDidLoad()
// Array containing UIViewControllers which are in fact under the hood
// downcasted ContentViewControllers.
self.initArrayViewControllers()
// UIPageViewController initialization and configuration.
let toolbarHeight: CGFloat = 60.0
self.initPageViewController(toolbarHeight)
// Retrieving UIPageControl
self.initPageControl()
}
// Required UIPageViewControllerDataSource method
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var index: Int = (viewController as! ContentViewController).index
if index == self.arrayViewControllers.count - 1 {
return self.arrayViewControllers[0]
}
return self.arrayViewControllers[++index]
}
// Required UIPageViewControllerDataSource method
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var index: Int = (viewController as! ContentViewController).index
if index == 0 {
return self.arrayViewControllers[self.arrayViewControllers.count - 1]
}
return self.arrayViewControllers[--index]
}
// Optional UIPageViewControllerDataSource method
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return self.arrayInformationMessages.count
}
// Optional UIPageViewControllerDataSource method
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
/*
Optional UIPageViewControllerDelegate method
Sent when a gesture-initiated transition ends. The 'finished' parameter indicates whether
the animation finished, while the 'completed' parameter indicates whether the transition completed or bailed out (if the user let go early).
*/
func pageViewController(pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [AnyObject],
transitionCompleted completed: Bool)
{
// Turn is either finished or aborted
if (completed && finished) {
// let previousViewController = previousViewControllers[0] as ContentViewController
let currentDisplayedViewController = self.pageViewController!.viewControllers[0] as! ContentViewController
self.pageControl.currentPage = currentDisplayedViewController.index
}
}
private func initArrayViewControllers() {
for (var i = 0; i < self.arrayInformationMessages.count; i++) {
let contentViewController = self.storyboard!.instantiateViewControllerWithIdentifier("ContentViewControllerID") as! ContentViewController
contentViewController.index = i
contentViewController.titleText = self.arrayInformationMessages[i].title
contentViewController.descriptionText = self.arrayInformationMessages[i].description
self.arrayViewControllers.append(contentViewController)
}
}
private func initPageViewController(let toolbarHeight: CGFloat) {
// self.pageViewController = self.storyboard!.instantiateViewControllerWithIdentifier("PagesWidgetID") as! UIPageViewController
self.pageViewController = UIPageViewController(transitionStyle: UIPageViewControllerTransitionStyle.Scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.Horizontal, options: nil)
if let pageViewController = self.pageViewController {
let initViewController = self.arrayViewControllers[0] as! ContentViewController
let vcArray = [initViewController]
let frame = self.view.frame
pageViewController.dataSource = self
pageViewController.delegate = self
pageViewController.view.frame = CGRectMake(0, 0, frame.width, frame.height - toolbarHeight)
pageViewController.setViewControllers(vcArray, direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
self.addChildViewController(pageViewController)
self.view.addSubview(pageViewController.view)
// pageViewController.view.clipsToBounds = true
pageViewController.didMoveToParentViewController(self)
}
}
private func initPageControl() {
let subviews: Array = self.pageViewController.view.subviews
var pageControl: UIPageControl! = nil
for (var i = 0; i < subviews.count; i++) {
if (subviews[i] is UIPageControl) {
pageControl = subviews[i] as! UIPageControl
break
}
}
self.pageControl = pageControl
}
}
| 8ac565e04a1ca3290bab926d176a0341 | 45.594595 | 206 | 0.697651 | false | false | false | false |
nalexn/ViewInspector | refs/heads/master | Tests/ViewInspectorTests/ViewHostingTests.swift | mit | 1 | import XCTest
import SwiftUI
#if canImport(UIKit)
import UIKit
#endif
@testable import ViewInspector
#if os(macOS)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
final class ViewHostingTests: XCTestCase {
func testNSViewUpdate() throws {
let exp = XCTestExpectation(description: "updateNSView")
exp.expectedFulfillmentCount = 2
exp.assertForOverFulfill = true
var sut = NSTestView.WrapperView(flag: false, didUpdate: {
exp.fulfill()
})
sut.didAppear = { view in
view.flag.toggle()
ViewHosting.expel()
}
ViewHosting.host(view: sut)
wait(for: [exp], timeout: 0.1)
}
func testNSViewExtraction() throws {
let exp = XCTestExpectation(description: "extractNSView")
let flag = Binding(wrappedValue: false)
let sut = NSTestView(flag: flag, didUpdate: { })
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
sut.inspect { view in
let nsView = try view.actualView().nsView()
XCTAssertEqual(nsView.viewTag, NSViewWithTag.offTag)
ViewHosting.expel()
exp.fulfill()
}
}
ViewHosting.host(view: sut)
wait(for: [exp], timeout: 0.2)
}
func testNSViewExtractionAfterStateUpdate() throws {
let exp = XCTestExpectation(description: "extractNSView")
var sut = NSTestView.WrapperView(flag: false, didUpdate: { })
sut.didAppear = { wrapper in
wrapper.inspect { wrapper in
let view = try wrapper.view(NSTestView.self)
XCTAssertThrows(
try view.actualView().nsView(),
"View for NSTestView is absent")
try wrapper.actualView().flag.toggle()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
let uiView = try? view.actualView().nsView()
XCTAssertNotNil(uiView)
XCTAssertEqual(uiView?.viewTag, NSViewWithTag.onTag)
ViewHosting.expel()
exp.fulfill()
}
}
}
ViewHosting.host(view: sut)
wait(for: [exp], timeout: 0.2)
}
func testNSViewControllerExtraction() throws {
let exp = XCTestExpectation(description: "extractNSViewController")
let sut = NSTestVC()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
sut.inspect { view in
XCTAssertNoThrow(try view.actualView().viewController())
ViewHosting.expel()
exp.fulfill()
}
}
ViewHosting.host(view: sut)
wait(for: [exp], timeout: 0.2)
}
}
#elseif os(iOS) || os(tvOS)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
final class ViewHostingTests: XCTestCase {
func testUIViewUpdate() throws {
let exp = XCTestExpectation(description: "updateUIView")
exp.expectedFulfillmentCount = 2
var sut = UITestView.WrapperView(flag: false, didUpdate: {
exp.fulfill()
})
sut.didAppear = { view in
view.flag.toggle()
ViewHosting.expel()
}
ViewHosting.host(view: sut)
wait(for: [exp], timeout: 0.1)
}
func testUIViewExtraction() throws {
let exp = XCTestExpectation(description: "extractUIView")
let flag = Binding(wrappedValue: false)
let sut = UITestView(flag: flag, didUpdate: { })
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
sut.inspect { view in
let uiView = try view.actualView().uiView()
XCTAssertEqual(uiView.tag, UITestView.offTag)
ViewHosting.expel()
exp.fulfill()
}
}
ViewHosting.host(view: sut)
wait(for: [exp], timeout: 0.2)
}
func testUIViewExtractionAfterStateUpdate() throws {
let exp = XCTestExpectation(description: "extractUIView")
var sut = UITestView.WrapperView(flag: false, didUpdate: { })
sut.didAppear = { wrapper in
wrapper.inspect { wrapper in
let view = try wrapper.view(UITestView.self)
XCTAssertThrows(
try view.actualView().uiView(),
"View for UITestView is absent")
try wrapper.actualView().flag.toggle()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
let uiView = try? view.actualView().uiView()
XCTAssertNotNil(uiView)
XCTAssertEqual(uiView?.tag, UITestView.onTag)
ViewHosting.expel()
exp.fulfill()
}
}
}
ViewHosting.host(view: sut)
wait(for: [exp], timeout: 0.2)
}
func testUIViewControllerExtraction() throws {
let exp = XCTestExpectation(description: "extractUIViewController")
let sut = UITestVC()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
sut.inspect { view in
XCTAssertNoThrow(try view.actualView().viewController())
ViewHosting.expel()
exp.fulfill()
}
}
ViewHosting.host(view: sut)
wait(for: [exp], timeout: 0.2)
}
}
#elseif os(watchOS)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *)
@available(watchOS, deprecated: 7.0)
final class ViewHostingTests: XCTestCase {
func testWKTestView() throws {
let exp = XCTestExpectation(description: #function)
exp.expectedFulfillmentCount = 2
var sut = WKTestView.WrapperView(didUpdate: {
exp.fulfill()
})
sut.didAppear = { view in
ViewHosting.expel()
}
ViewHosting.host(view: sut)
wait(for: [exp], timeout: 0.1)
}
func testWKViewExtraction() throws {
let exp = XCTestExpectation(description: #function)
let sut = WKTestView(didUpdate: { })
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
sut.inspect { view in
XCTAssertNoThrow(try view.actualView().interfaceObject())
ViewHosting.expel()
exp.fulfill()
}
}
ViewHosting.host(view: sut)
wait(for: [exp], timeout: 1)
}
}
#endif
// MARK: - Test Views
#if os(macOS)
private class NSViewWithTag: NSView {
var viewTag: Int = NSViewWithTag.offTag
static let offTag: Int = 42
static let onTag: Int = 43
}
private struct NSTestView: NSViewRepresentable, Inspectable {
typealias UpdateContext = NSViewRepresentableContext<Self>
@Binding var flag: Bool
var didUpdate: () -> Void
func makeNSView(context: UpdateContext) -> NSViewWithTag {
return NSViewWithTag()
}
func updateNSView(_ nsView: NSViewWithTag, context: UpdateContext) {
nsView.viewTag = flag ? NSViewWithTag.onTag : NSViewWithTag.offTag
didUpdate()
}
}
extension NSTestView {
struct WrapperView: View, Inspectable {
@State var flag: Bool
var didAppear: ((Self) -> Void)?
var didUpdate: () -> Void
var body: some View {
NSTestView(flag: $flag, didUpdate: didUpdate)
.onAppear { self.didAppear?(self) }
}
}
}
#elseif os(iOS) || os(tvOS)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private struct UITestView: UIViewRepresentable, Inspectable {
typealias UpdateContext = UIViewRepresentableContext<Self>
@Binding var flag: Bool
var didUpdate: () -> Void
func makeUIView(context: UpdateContext) -> UIView {
return UIView()
}
func updateUIView(_ uiView: UIView, context: UpdateContext) {
uiView.tag = flag ? UITestView.onTag : UITestView.offTag
didUpdate()
}
static let offTag: Int = 42
static let onTag: Int = 43
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension UITestView {
struct WrapperView: View, Inspectable {
@State var flag: Bool
var didAppear: ((Self) -> Void)?
var didUpdate: () -> Void
var body: some View {
UITestView(flag: $flag, didUpdate: didUpdate)
.onAppear { self.didAppear?(self) }
}
}
}
#elseif os(watchOS)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *)
@available(watchOS, deprecated: 7.0)
private struct WKTestView: WKInterfaceObjectRepresentable, Inspectable {
var didUpdate: () -> Void
typealias Context = WKInterfaceObjectRepresentableContext<WKTestView>
func makeWKInterfaceObject(context: Context) -> some WKInterfaceObject {
return WKInterfaceMap()
}
func updateWKInterfaceObject(_ wkInterfaceObject: WKInterfaceObjectType, context: Context) {
didUpdate()
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 7.0, *)
@available(watchOS, deprecated: 7.0)
extension WKTestView {
struct WrapperView: View, Inspectable {
var didAppear: ((Self) -> Void)?
var didUpdate: () -> Void
var body: some View {
WKTestView(didUpdate: didUpdate)
.onAppear { self.didAppear?(self) }
}
}
}
#endif
#if os(macOS)
private struct NSTestVC: NSViewControllerRepresentable, Inspectable {
class TestVC: NSViewController {
override func loadView() {
view = NSView()
}
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError()
}
}
typealias UpdateContext = NSViewControllerRepresentableContext<Self>
func makeNSViewController(context: UpdateContext) -> TestVC {
let vc = TestVC()
updateNSViewController(vc, context: context)
return vc
}
func updateNSViewController(_ nsViewController: TestVC, context: UpdateContext) {
}
}
#elseif os(iOS) || os(tvOS)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private struct UITestVC: UIViewControllerRepresentable, Inspectable {
class TestVC: UIViewController { }
typealias UpdateContext = UIViewControllerRepresentableContext<Self>
func makeUIViewController(context: UpdateContext) -> TestVC {
let vc = TestVC()
updateUIViewController(vc, context: context)
return vc
}
func updateUIViewController(_ uiViewController: TestVC, context: UpdateContext) {
}
}
#endif
| d57a36971def9b02fe019033ca7ceb4b | 30.204082 | 96 | 0.586004 | false | true | false | false |
kello711/HackingWithSwift | refs/heads/master | project14/Project14/GameScene.swift | unlicense | 1 | //
// GameScene.swift
// Project14
//
// Created by Hudzilla on 15/09/2015.
// Copyright (c) 2015 Paul Hudson. All rights reserved.
//
import GameplayKit
import SpriteKit
class GameScene: SKScene {
var slots = [WhackSlot]()
var popupTime = 0.85
var numRounds = 0
var gameScore: SKLabelNode!
var score: Int = 0 {
didSet {
gameScore.text = "Score: \(score)"
}
}
override func didMoveToView(view: SKView) {
let background = SKSpriteNode(imageNamed: "whackBackground")
background.position = CGPoint(x: 512, y: 384)
background.blendMode = .Replace
background.zPosition = -1
addChild(background)
gameScore = SKLabelNode(fontNamed: "Chalkduster")
gameScore.text = "Score: 0"
gameScore.position = CGPoint(x: 8, y: 8)
gameScore.horizontalAlignmentMode = .Left
gameScore.fontSize = 48
addChild(gameScore)
for i in 0 ..< 5 { createSlotAt(CGPoint(x: 100 + (i * 170), y: 410)) }
for i in 0 ..< 4 { createSlotAt(CGPoint(x: 180 + (i * 170), y: 320)) }
for i in 0 ..< 5 { createSlotAt(CGPoint(x: 100 + (i * 170), y: 230)) }
for i in 0 ..< 4 { createSlotAt(CGPoint(x: 180 + (i * 170), y: 140)) }
RunAfterDelay(1) { [unowned self] in
self.createEnemy()
}
}
func createSlotAt(pos: CGPoint) {
let slot = WhackSlot()
slot.configureAtPosition(pos)
addChild(slot)
slots.append(slot)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let location = touch.locationInNode(self)
let nodes = nodesAtPoint(location)
for node in nodes {
if node.name == "charFriend" {
let whackSlot = node.parent!.parent as! WhackSlot
if !whackSlot.visible { continue }
if whackSlot.isHit { continue }
whackSlot.hit()
score -= 5
runAction(SKAction.playSoundFileNamed("whackBad.caf", waitForCompletion:false))
} else if node.name == "charEnemy" {
let whackSlot = node.parent!.parent as! WhackSlot
if !whackSlot.visible { continue }
if whackSlot.isHit { continue }
whackSlot.charNode.xScale = 0.85
whackSlot.charNode.yScale = 0.85
whackSlot.hit()
score += 1
runAction(SKAction.playSoundFileNamed("whack.caf", waitForCompletion:false))
}
}
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
func createEnemy() {
numRounds += 1
if numRounds >= 30 {
for slot in slots {
slot.hide()
}
let gameOver = SKSpriteNode(imageNamed: "gameOver")
gameOver.position = CGPoint(x: 512, y: 384)
gameOver.zPosition = 1
addChild(gameOver)
return
}
popupTime *= 0.991
slots = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(slots) as! [WhackSlot]
slots[0].show(hideTime: popupTime)
if RandomInt(min: 0, max: 12) > 4 { slots[1].show(hideTime: popupTime) }
if RandomInt(min: 0, max: 12) > 8 { slots[2].show(hideTime: popupTime) }
if RandomInt(min: 0, max: 12) > 10 { slots[3].show(hideTime: popupTime) }
if RandomInt(min: 0, max: 12) > 11 { slots[4].show(hideTime: popupTime) }
let minDelay = popupTime / 2.0
let maxDelay = popupTime * 2
RunAfterDelay(RandomDouble(min: minDelay, max: maxDelay)) { [unowned self] in
self.createEnemy()
}
}
}
| c211ec3ad0c7dab255fde08c4547fa88 | 25.128 | 93 | 0.662584 | false | false | false | false |
slimane-swift/SessionMiddleware | refs/heads/master | Sources/SessionMiddleware.swift | mit | 1 | //
// Middleware.swift
// SlimaneMiddleware
//
// Created by Yuki Takei on 4/11/16.
// Copyright © 2016 MikeTOKYO. All rights reserved.
//
@_exported import HTTP
@_exported import Time
@_exported import Crypto
@_exported import Suv
func makeKey(_ key: String) -> String {
return "Slimane.SessionMiddleware.\(key)"
}
extension Request {
public var session: Session? {
get {
guard let session = storage[makeKey("session")] else {
return nil
}
return session as? Session
}
set {
storage[makeKey("session")] = newValue
}
}
}
public struct SessionMiddleware: AsyncMiddleware {
var session: Session
public init(config: SessionConfig){
session = Session(config: config)
}
public func respond(to request: Request, chainingTo next: AsyncResponder, result: @escaping ((Void) throws -> Response) -> Void) {
var req = request
req.storage[makeKey("session")] = session
let onThread: (QueueWorkContext) -> Void = { ctx in
// Parse signedCookies
ctx.storage["signedCookies"] = signedCookies(req.cookies, secret: self.session.secret)
if shouldSetCookie(req, self.session) {
do {
let cookie = try createCookieForSet(self.session)
let setCookie = Set<AttributedCookie>([cookie])
ctx.storage["session.setCookie"] = setCookie
ctx.storage["session.id"] = signedCookies(Set([Cookie(name: cookie.name, value: cookie.value)]), secret: self.session.secret)[self.session.keyName]
} catch {
ctx.storage["session.error"] = error
}
}
}
let onFinish: (QueueWorkContext) -> Void = { ctx in
if let error = ctx.storage["session.error"] as? Error {
result { throw error }
return
}
if let cookie = ctx.storage["session.setCookie"] as? Set<AttributedCookie> {
req.session?.id = ctx.storage["session.id"] as? String
next.respond(to: req) { getResponse in
result {
var response = try getResponse()
response.cookies = cookie
return response
}
}
return
}
guard let sessionId = (ctx.storage["signedCookies"] as? [String: String])?[self.session.keyName] , !sessionId.isEmpty else {
next.respond(to: req, result: result)
return
}
req.session?.id = sessionId
req.session?.load() { getData in
req.session?.values = [:]
do {
let data = try getData()
req.session?.values = data
} catch {
return result {
throw error
}
}
next.respond(to: req, result: result)
}
}
Process.qwork(onThread: onThread, onFinish: onFinish)
}
}
private func shouldSetCookie(_ req: Request, _ session: Session) -> Bool {
guard let cookieValue = req.cookies.filter({ $0.name.trim() == session.keyName }).map({ $0.value }).first else {
return true
}
do {
let dec = try signedCookie(cookieValue, secret: session.secret)
let sesId = try decode(cookieValue)
return dec != sesId
} catch {
return true
}
}
private func createCookieForSet(_ session: Session) throws -> AttributedCookie {
let sessionId = try signSync(Session.generateId().hexadecimalString(), secret: session.secret)
var maxAge: AttributedCookie.Expiration?
if let ttl = session.ttl {
maxAge = .maxAge(ttl)
} else {
maxAge = nil
}
return AttributedCookie(name: session.keyName, value: sessionId, expiration: maxAge , domain: session.domain, path: session.path, secure: session.secure, httpOnly: session.httpOnly)
}
| e81793c62f4b4eb149a8563fef4508c0 | 30.969697 | 185 | 0.540284 | false | false | false | false |
RenanGreca/Advent-of-Code | refs/heads/master | AdventOfCode.playground/Pages/DayFour.xcplaygroundpage/Sources/MD5.swift | mit | 1 | //
// MD5.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 06/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
extension NSData {
public func md5() -> NSData? {
return MD5(self).calculate()
}
public func toHexString() -> String {
let count = self.length / sizeof(UInt8)
var bytesArray = [UInt8](count: count, repeatedValue: 0)
self.getBytes(&bytesArray, length:count * sizeof(UInt8))
var s:String = "";
for byte in bytesArray {
s = s + String(format:"%02x", byte)
}
return s
}
}
extension String {
public func md5() -> String? {
return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.md5()?.toHexString()
}
}
extension NSMutableData {
/** Convenient way to append bytes */
internal func appendBytes(arrayOfBytes: [UInt8]) {
self.appendBytes(arrayOfBytes, length: arrayOfBytes.count)
}
}
struct NSDataSequence: SequenceType {
let chunkSize: Int
let data: NSData
func generate() -> AnyGenerator<NSData> {
var offset:Int = 0
return anyGenerator {
let result = self.data.subdataWithRange(NSRange(location: offset, length: min(self.chunkSize, self.data.length - offset)))
offset += result.length
return result.length > 0 ? result : nil
}
}
}
func rotateLeft(v:UInt32, n:UInt32) -> UInt32 {
return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
}
public class MD5 {
var size:Int = 16 // 128 / 8
let message: NSData
init (_ message: NSData) {
self.message = message
}
/** specifies the per-round shift amounts */
private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let k: [UInt32] = [0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,
0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,
0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,
0x6b901122,0xfd987193,0xa679438e,0x49b40821,
0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,
0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8,
0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,
0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,
0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,
0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,
0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05,
0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,
0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,
0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,
0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,
0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391]
private let h:[UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
private func prepare(len:Int) -> NSMutableData {
let tmpMessage: NSMutableData = NSMutableData(data: self.message)
// Step 1. Append Padding Bits
tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
var msgLength = tmpMessage.length
var counter = 0
while msgLength % len != (len - 8) {
counter++
msgLength++
}
let bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8)))
tmpMessage.appendBytes(bufZeros, length: counter)
bufZeros.destroy()
bufZeros.dealloc(1)
return tmpMessage
}
private func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] {
let totalBytes = length ?? sizeof(T)
let valuePointer = UnsafeMutablePointer<T>.alloc(1)
valuePointer.memory = value
let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer)
var bytes = [UInt8](count: totalBytes, repeatedValue: 0)
for j in 0..<min(sizeof(T),totalBytes) {
bytes[totalBytes - 1 - j] = (bytesPointer + j).memory
}
valuePointer.destroy()
valuePointer.dealloc(1)
return bytes
}
public func calculate() -> NSData {
let tmpMessage = prepare(64)
// hash values
var hh = h
// Step 2. Append Length a 64-bit representation of lengthInBits
let lengthInBits = (message.length * 8)
let lengthBytes = arrayOfBytes(lengthInBits, length: 64 / 8)
tmpMessage.appendBytes(Array(lengthBytes.reverse())); //FIXME: Array?
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
for chunk in NSDataSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
var M = [UInt32](count: 16, repeatedValue: 0)
let range = NSRange(location:0, length: M.count * sizeof(UInt32))
chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range)
// Initialize hash value for this chunk:
var A:UInt32 = hh[0]
var B:UInt32 = hh[1]
var C:UInt32 = hh[2]
var D:UInt32 = hh[3]
var dTemp:UInt32 = 0
// Main loop
for j in 0..<k.count {
var g = 0
var F:UInt32 = 0
switch (j) {
case 0...15:
F = (B & C) | ((~B) & D)
g = j
break
case 16...31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32...47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48...63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), n: s[j])
A = dTemp
}
hh[0] = hh[0] &+ A
hh[1] = hh[1] &+ B
hh[2] = hh[2] &+ C
hh[3] = hh[3] &+ D
}
let buf: NSMutableData = NSMutableData();
hh.forEach({ (item) -> () in
var i:UInt32 = item.littleEndian
buf.appendBytes(&i, length: sizeofValue(i))
})
return buf.copy() as! NSData
}
}
| 654b9b0218a982250ecd3c02d48c0418 | 32.583333 | 134 | 0.509926 | false | false | false | false |
apple/swift-experimental-string-processing | refs/heads/main | Sources/_StringProcessing/Engine/Instruction.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A single instruction for the matching engine to execute
///
/// Instructions are 64-bits, consisting of an 8-bit opcode
/// and a 56-bit payload, which packs operands.
///
struct Instruction: RawRepresentable, Hashable {
var rawValue: UInt64
init(rawValue: UInt64){
self.rawValue = rawValue
}
}
extension Instruction {
enum OpCode: UInt64 {
case invalid = 0
// MARK: - General Purpose
/// Move an immediate value into a register
///
/// moveImmediate(_ i: Int, into: IntReg)
///
/// Operands:
/// - Immediate value to move
/// - Int register to move into
///
case moveImmediate
/// Move the current position into a register
///
/// moveCurrentPosition(into: PositionRegister)
///
/// Operands:
/// - Position register to move into
case moveCurrentPosition
// MARK: General Purpose: Control flow
/// Branch to a new instruction
///
/// branch(to: InstAddr)
///
/// Operand: instruction address to branch to
case branch
/// Conditionally branch if zero, otherwise decrement
///
/// condBranch(
/// to: InstAddr, ifZeroElseDecrement: IntReg)
///
/// Operands:
/// - Instruction address to branch to, if zero
/// - Int register to check for zero, otherwise decrease
///
case condBranchZeroElseDecrement
/// Conditionally branch if the current position is the same as the register
///
/// condBranch(
/// to: InstAddr, ifSamePositionAs: PositionRegister)
///
/// Operands:
/// - Instruction address to branch to, if the position in the register is the same as currentPosition
/// - Position register to check against
case condBranchSamePosition
// TODO: Function calls
// MARK: - Matching
/// Advance the input position.
///
/// advance(_ amount: Distance)
///
/// Operand: Amount to advance by.
case advance
// TODO: Is the amount useful here? Is it commonly more than 1?
/// Composite assert-advance else restore.
///
/// match(_: EltReg, isCaseInsensitive: Bool)
///
/// Operands:
/// - Element register to compare against.
/// - Boolean for if we should match in a case insensitive way
case match
/// Match against a scalar and possibly perform a boundary check or match in a case insensitive way
///
/// matchScalar(_: Unicode.Scalar, isCaseInsensitive: Bool, boundaryCheck: Bool)
///
/// Operands: Scalar value to match against and booleans
case matchScalar
/// Match a character or a scalar against a set of valid ascii values stored in a bitset
///
/// matchBitset(_: AsciiBitsetRegister, isScalar: Bool)
///
/// Operand:
/// - Ascii bitset register containing the bitset
/// - Boolean for if we should match by scalar value
case matchBitset
/// Match against a built-in character class
///
/// matchBuiltin(_: CharacterClassPayload)
///
/// Operand: the payload contains
/// - The character class
/// - If it is inverted
/// - If it strictly matches only ascii values
case matchBuiltin
/// Matches any non newline character
/// Operand: If we are in scalar mode or not
case matchAnyNonNewline
// MARK: Extension points
/// Advance the input position based on the result by calling the consume
/// function.
///
/// Operand: Consume function register to call.
case consumeBy
/// Lookaround assertion operation. Performs a zero width assertion based on
/// the assertion type and options stored in the payload
///
/// assert(_:AssertionPayload)
///
/// Operands: AssertionPayload containing assertion type and options
case assertBy
/// Custom value-creating consume operation.
///
/// match(
/// _ matchFunction: (
/// input: Input,
/// bounds: Range<Position>
/// ) -> (Position, Any),
/// into: ValueReg
/// )
///
///
case matchBy
// MARK: Matching: Save points
/// Add a save point
///
/// Operand: instruction address to resume from
///
/// A save point is:
/// - a position in the input to restore
/// - a position in the call stack to cut off
/// - an instruction address to resume from
///
/// TODO: Consider if separating would improve generality
case save
///
/// Add a save point that doesn't preserve input position
///
/// NOTE: This is a prototype for now, but exposes
/// flaws in our formulation of back tracking. We could
/// instead have an instruction to update the top
/// most saved position instead
case saveAddress
/// Remove the most recently saved point
///
/// Precondition: There is a save point to remove
case clear
/// Remove save points up to and including the operand
///
/// Operand: instruction address to look for
///
/// Precondition: The operand is in the save point list
case clearThrough
/// Fused save-and-branch.
///
/// split(to: target, saving: backtrackPoint)
///
case splitSaving
/// Fused quantify, execute, save instruction
/// Quantifies the stored instruction in an inner loop instead of looping through instructions in processor
/// Only quantifies specific nodes
///
/// quantify(_:QuantifyPayload)
///
case quantify
/// Begin the given capture
///
/// beginCapture(_:CapReg)
///
case beginCapture
/// End the given capture
///
/// endCapture(_:CapReg)
///
case endCapture
/// Transform a captured value, saving the built value
///
/// transformCapture(_:CapReg, _:TransformReg)
///
case transformCapture
/// Save a value into a capture register
///
/// captureValue(_: ValReg, into _: CapReg)
case captureValue
/// Match a previously captured value
///
/// backreference(_:CapReg)
///
case backreference
// MARK: Matching: State transitions
// TODO: State transitions need more work. We want
// granular core but also composite ones that will
// interact with save points
/// Transition into ACCEPT and halt
case accept
/// Signal failure (currently same as `restore`)
case fail
// TODO: Fused assertions. It seems like we often want to
// branch based on assertion fail or success.
}
}
internal var _opcodeMask: UInt64 { 0xFF00_0000_0000_0000 }
var _payloadMask: UInt64 { ~_opcodeMask }
extension Instruction {
var opcodeMask: UInt64 { 0xFF00_0000_0000_0000 }
var opcode: OpCode {
get {
OpCode(
rawValue: (rawValue & _opcodeMask) &>> 56
).unsafelyUnwrapped
}
set {
assert(newValue != .invalid, "consider hoisting this")
assert(newValue.rawValue < 256)
self.rawValue &= ~_opcodeMask
self.rawValue |= newValue.rawValue &<< 56
}
}
var payload: Payload {
get { Payload(rawValue: rawValue & ~opcodeMask) }
set {
self.rawValue &= opcodeMask
self.rawValue |= newValue.rawValue
}
}
var destructure: (opcode: OpCode, payload: Payload) {
get { (opcode, payload) }
set { self = Self(opcode, payload) }
}
init(_ opcode: OpCode, _ payload: Payload/* = Payload()*/) {
self.init(rawValue: 0)
self.opcode = opcode
self.payload = payload
// TODO: check invariants
}
init(_ opcode: OpCode) {
self.init(rawValue: 0)
self.opcode = opcode
//self.payload = payload
// TODO: check invariants
// TODO: placeholder bit pattern for fill-in-later
}
}
/*
This is in need of more refactoring and design, the following
are a rough listing of TODOs:
- Save point and call stack interactions should be more formalized.
- It's too easy to have unbalanced save/clears amongst function calls
- Nominal type for conditions with an invert bit
- Better bit allocation and layout for operand, instruction, etc
- Use spare bits for better assertions
- Check low-level compiler code gen for switches
- Consider relative addresses instead of absolute addresses
- Explore a predication bit
- Explore using SIMD
- Explore a larger opcode, so that we can have variant flags
- E.g., opcode-local bits instead of flattening opcode space
We'd like to eventually design:
- A general-purpose core (future extensibility)
- A matching-specific instruction area carved out
- Leave a large area for future usage of run-time bytecode interpretation
- Debate: allow for future variable-width instructions
We'd like a testing / performance setup that lets us
- Define new instructions in terms of old ones (testing, perf)
- Version our instruction set in case we need future fixes
*/
// TODO: replace with instruction formatters...
extension Instruction {
var instructionAddress: InstructionAddress? {
switch opcode {
case .branch, .save, .saveAddress:
return payload.addr
default: return nil
}
}
var elementRegister: ElementRegister? {
switch opcode {
case .match:
return payload.elementPayload.1
default: return nil
}
}
var consumeFunctionRegister: ConsumeFunctionRegister? {
switch opcode {
case .consumeBy: return payload.consumer
default: return nil
}
}
}
extension Instruction: InstructionProtocol {
var operandPC: InstructionAddress? { instructionAddress }
}
// TODO: better names for accept/fail/etc. Instruction
// conflates backtracking with signaling failure or success,
// could be clearer.
enum State {
/// Still running
case inProgress
/// FAIL: halt and signal failure
case fail
/// ACCEPT: halt and signal success
case accept
}
| 29a2e645eb3ce446a246be2fa0acf149 | 26.525333 | 111 | 0.633792 | false | false | false | false |
Drusy/auvergne-webcams-ios | refs/heads/master | Carthage/Checkouts/SwiftiumKit/SwiftiumKit/NSDataExtensions.swift | apache-2.0 | 1 | //
// NSDataExtensions.swift
// SwiftiumKit
//
// Created by Richard Bergoin on 14/03/16.
// Copyright © 2016 Openium. All rights reserved.
//
import Foundation
import CommonCrypto
// MARK: AES encrypt/decrypt
private typealias SKCryptOperationFunction = (Data, String) -> Data?
func sk_crypto_operate(operation: CCOperation, keySize: Int, data: Data, keyData: Data) -> Data? {
let keyBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: keySize)
keyBytes.initialize(to: 0)
keyData.withUnsafeBytes { (bytes) in
for index in 0..<min(keySize, keyData.count) {
keyBytes[index] = bytes[index]
}
}
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
let cryptLength = data.count + kCCBlockSizeAES128
var cryptData = Data(count: cryptLength)
var numBytesEncrypted = 0
let cryptStatus = cryptData.withUnsafeMutableBytes { (cryptBytes) -> CCCryptorStatus in
data.withUnsafeBytes { (dataBytes) -> CCCryptorStatus in
CCCrypt(operation,
CCAlgorithm(kCCAlgorithmAES),
CCOptions(kCCOptionPKCS7Padding),
keyBytes, keySize,
nil,
dataBytes.baseAddress, data.count,
cryptBytes.baseAddress, cryptLength,
&numBytesEncrypted)
}
}
if cryptStatus == kCCSuccess {
cryptData.count = numBytesEncrypted
return cryptData
}
return nil
}
func sk_crypto_encrypt_aes128(data: Data, key: String) -> Data? {
return sk_crypto_operate(operation: CCOperation(kCCEncrypt), keySize: kCCKeySizeAES128, data: data, keyData: Data(Array<UInt8>(key.utf8)))
}
func sk_crypto_encrypt_aes192(data: Data, key: String) -> Data? {
return sk_crypto_operate(operation: CCOperation(kCCEncrypt), keySize: kCCKeySizeAES192, data: data, keyData: Data(Array<UInt8>(key.utf8)))
}
func sk_crypto_encrypt_aes256(data: Data, key: String) -> Data? {
return sk_crypto_operate(operation: CCOperation(kCCEncrypt), keySize: kCCKeySizeAES256, data: data, keyData: Data(Array<UInt8>(key.utf8)))
}
func sk_crypto_decrypt_aes128(data: Data, key: String) -> Data? {
return sk_crypto_operate(operation: CCOperation(kCCDecrypt), keySize: kCCKeySizeAES128, data: data, keyData: Data(Array<UInt8>(key.utf8)))
}
func sk_crypto_decrypt_aes192(data: Data, key: String) -> Data? {
return sk_crypto_operate(operation: CCOperation(kCCDecrypt), keySize: kCCKeySizeAES192, data: data, keyData: Data(Array<UInt8>(key.utf8)))
}
func sk_crypto_decrypt_aes256(data: Data, key: String) -> Data? {
return sk_crypto_operate(operation: CCOperation(kCCDecrypt), keySize: kCCKeySizeAES256, data: data, keyData: Data(Array<UInt8>(key.utf8)))
}
private enum EncryptionAlgorithm {
case aes128, aes192, aes256
var encryptFunction: SKCryptOperationFunction {
var encryptFunction: SKCryptOperationFunction
switch self {
case .aes128: encryptFunction = sk_crypto_encrypt_aes128
case .aes192: encryptFunction = sk_crypto_encrypt_aes192
case .aes256: encryptFunction = sk_crypto_encrypt_aes256
}
return encryptFunction
}
var decryptFunction: SKCryptOperationFunction {
var decryptFunction: SKCryptOperationFunction
switch self {
case .aes128: decryptFunction = sk_crypto_decrypt_aes128
case .aes192: decryptFunction = sk_crypto_decrypt_aes192
case .aes256: decryptFunction = sk_crypto_decrypt_aes256
}
return decryptFunction
}
}
extension Data {
public init?(base16EncodedString: String) {
let dataLen = base16EncodedString.count / 2
let bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: dataLen)
let charactersAsUInt8 = base16EncodedString.map {
UInt8( strtoul((String($0)), nil, 16))
}
var strIdx = 0
for idx in 0..<dataLen {
let c1 = charactersAsUInt8[strIdx]
let c2 = charactersAsUInt8[strIdx + 1]
//bytes[idx]
bytes[idx] = UInt8((c1<<4) + c2)
strIdx += 2
}
self.init(bytesNoCopy: bytes, count: dataLen, deallocator: .free)
}
public init?(bytesArray: Array<UInt8>) {
let dataLen = bytesArray.count
let bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: dataLen)
var idx = 0
for byte in bytesArray {
bytes[idx] = byte
idx += 1
}
self.init(bytesNoCopy: bytes, count: dataLen, deallocator: .free)
}
public func base16EncodedString() -> String {
var hex = String()
let bytes = (self as NSData).bytes.bindMemory(to: UInt8.self, capacity: self.count)
for idx in 0..<self.count {
let value: UInt8 = UnsafePointer<UInt8>(bytes)[idx]
hex.append(value.toHexaString())
}
return hex
}
fileprivate func aesOperation(_ key: String, operation: SKCryptOperationFunction) -> Data? {
return operation(self, key)
}
/// Encrypts an Array\<AESEncryptable> using provided `key` (utf8 data) with AES256
/// :returns: Bytes array of encrypted data
public func aes256Encrypt(_ key: String) -> Data? {
return aesOperation(key, operation: EncryptionAlgorithm.aes256.encryptFunction)
}
/// Decrypts an Array\<AESEncryptable> using provided `key` (utf8 data) with AES256
/// :returns: Bytes array of decrypted data
public func aes256Decrypt(_ key: String) -> Data? {
return aesOperation(key, operation: EncryptionAlgorithm.aes256.decryptFunction)
}
/// Encrypts an Array\<AESEncryptable> using provided `key` (utf8 data) with AES192
/// :returns: Bytes array of encrypted data
public func aes192Encrypt(_ key: String) -> Data? {
return aesOperation(key, operation: EncryptionAlgorithm.aes192.encryptFunction)
}
/// Decrypts an Array\<AESEncryptable> using provided `key` (utf8 data) with AES192
/// :returns: Bytes array of decrypted data
public func aes192Decrypt(_ key: String) -> Data? {
return aesOperation(key, operation: EncryptionAlgorithm.aes192.decryptFunction)
}
/// Encrypts an Array\<AESEncryptable> using provided `key` (utf8 data) with AES128
/// :returns: Bytes array of encrypted data
public func aes128Encrypt(_ key: String) -> Data? {
return aesOperation(key, operation: EncryptionAlgorithm.aes128.encryptFunction)
}
/// Decrypts an Array\<AESEncryptable> using provided `key` (utf8 data) with AES128
/// :returns: Bytes array of decrypted data
public func aes128Decrypt(_ key: String) -> Data? {
return aesOperation(key, operation: EncryptionAlgorithm.aes128.decryptFunction)
}
}
| 021b9ea3eb814d6c5a86aaa9d3ab6f53 | 36.902703 | 142 | 0.658157 | false | false | false | false |
akaimo/LNFloatingActionButton | refs/heads/master | LNFloatingActionButton-Example/LNFloatingActionButton-Example/EllipseCellViewController.swift | mit | 1 | //
// EllipseCellViewController.swift
// LNFloatingActionButton-Example
//
// Created by Shuhei Kawaguchi on 2017/10/01.
// Copyright © 2017年 Shuhei Kawaguchi. All rights reserved.
//
import UIKit
import LNFloatingActionButton
class EllipseCellViewController: UIViewController {
var cells: [LNFloatingActionButtonCell] = []
override func viewDidLoad() {
super.viewDidLoad()
let ellipseCell: LNFloatingActionButtonEllipseCell = {
let cell = LNFloatingActionButtonEllipseCell()
cell.ellipseSize = CGSize(width: 150, height: 30)
cell.titleTextAlignment = .center
cell.title = "like button"
cell.image = UIImage(named: "like")
return cell
}()
cells.append(ellipseCell)
let ellipse2Cell: LNFloatingActionButtonEllipseCell = {
let cell = LNFloatingActionButtonEllipseCell()
cell.ellipseSize = CGSize(width: 150, height: 30)
cell.titleTextAlignment = .center
cell.title = "home button"
cell.image = UIImage(named: "home")
return cell
}()
cells.append(ellipse2Cell)
let fab: LNFloatingActionButton = {
let button = LNFloatingActionButton(x: view.frame.size.width - 100, y: view.frame.size.height - 100)
button.delegate = self
button.dataSource = self
button.color = .white
button.shadowOffset = CGSize(width: 0.0, height: 2.0)
button.shadowOpacity = 0.5
button.shadowRadius = 2.0
button.shadowPath = button.circlePath
button.closedImage = UIImage(named: "plus")
button.cellHorizontalAlign = .right
button.isBackgroundView = true
return button
}()
view.addSubview(fab)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension EllipseCellViewController: LNFloatingActionButtonDelegate {
func floatingActionButton(_ floatingActionButton: LNFloatingActionButton, didSelectItemAtIndex index: Int) {
print(index)
floatingActionButton.close()
}
}
extension EllipseCellViewController: LNFloatingActionButtonDataSource {
func numberOfCells(_ floatingActionButton: LNFloatingActionButton) -> Int {
return cells.count
}
func cellForIndex(_ index: Int) -> LNFloatingActionButtonCell {
return cells[index]
}
}
| 359bd92a9e6ff3b54a17fe12baa597bf | 31.582278 | 112 | 0.640249 | false | false | false | false |
bnickel/bite-swift | refs/heads/master | Bite/Take.swift | mit | 1 | //
// Take.swift
// Bite
//
// Created by Brian Nickel on 6/11/14.
// Copyright (c) 2014 Brian Nickel. All rights reserved.
//
public struct TakeGenerator<T where T:GeneratorType> : GeneratorType {
var remaining:Int
var source:T
init(_ source:T, count: Int) {
self.remaining = count
self.source = source
}
public mutating func next() -> T.Element? {
if remaining <= 0 { return nil }
remaining -= 1
return source.next()
}
}
public struct TakeSequence<T where T:SequenceType> : SequenceType {
let count:Int
let source:T
init(_ source:T, count: Int) {
self.count = count
self.source = source
}
public func generate() -> TakeGenerator<T.Generator> {
return TakeGenerator(source.generate(), count: count)
}
}
| 0c69608d583c54464ea9b527d9eddc5e | 21.289474 | 70 | 0.595041 | false | false | false | false |
Subsets and Splits