repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
Dewire/SwiftCommon | SwiftCommon/Dictionary.swift | 1 | 895 | //
// Dictionary.swift
// SwiftCommon
//
// Created by Kalle Lindström on 20/01/16.
// Copyright © 2016 Dewire. All rights reserved.
//
import Foundation
// MARK: merge
public extension Dictionary {
/**
Updates self with the values from other.
Example:
```
var d = ["a": "1", "b": "2"]
d.merge(["a": "newa", "c": "3"])
d // => ["a": "newa", "b": "2", "c": "3"]
```
*/
public mutating func merge(_ other: Dictionary<Key, Value>) {
for (key, value) in other {
self.updateValue(value, forKey: key)
}
}
/**
Returns a new Dictionary based on self with updates values
from the other Dictionary.
Example:
```
["a": "1", "b": "2"].merge(["a": "3"])["a"] // => 3
```
*/
public func merged(_ other: Dictionary<Key, Value>) -> Dictionary<Key, Value> {
var copy = self
copy.merge(other)
return copy
}
}
| mit |
tinysun212/swift-windows | test/APINotes/versioned-objc.swift | 1 | 1439 | // RUN: rm -rf %t && mkdir -p %t
// RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 4 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-4 %s
// RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 3 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-3 %s
// REQUIRES: objc_interop
import APINotesFrameworkTest
// CHECK-DIAGS-4-NOT: versioned-objc.swift:[[@LINE-1]]:
class ProtoWithVersionedUnavailableMemberImpl: ProtoWithVersionedUnavailableMember {
// CHECK-DIAGS-3: versioned-objc.swift:[[@LINE-1]]:7: error: type 'ProtoWithVersionedUnavailableMemberImpl' cannot conform to protocol 'ProtoWithVersionedUnavailableMember' because it has requirements that cannot be satisfied
func requirement() -> Any? { return nil }
}
func testNonGeneric() {
// CHECK-DIAGS-3:[[@LINE+1]]:{{[0-9]+}}: error: cannot convert value of type 'Any' to specified type 'Int'
let _: Int = NewlyGenericSub.defaultElement()
// CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: generic parameter 'Element' could not be inferred
// CHECK-DIAGS-3:[[@LINE+1]]:{{[0-9]+}}: error: cannot specialize non-generic type 'NewlyGenericSub'
let _: Int = NewlyGenericSub<Base>.defaultElement()
// CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: cannot convert value of type 'Base' to specified type 'Int'
}
let unrelatedDiagnostic: Int = nil
| apache-2.0 |
hzalaz/analytics-ios | Example/Tests/FileStorageTest.swift | 1 | 3867 | //
// FileStorageTest.swift
// Analytics
//
// Copyright © 2016 Segment. All rights reserved.
//
import Quick
import Nimble
import Analytics
class FileStorageTest : QuickSpec {
override func spec() {
var storage : SEGFileStorage!
beforeEach {
let url = SEGFileStorage.applicationSupportDirectoryURL()
expect(url).toNot(beNil())
expect(url?.lastPathComponent) == "Application Support"
storage = SEGFileStorage(folder: url!, crypto: nil)
}
it("creates folder if none exists") {
let tempDir = NSURL(fileURLWithPath: NSTemporaryDirectory())
let url = tempDir.URLByAppendingPathComponent(NSUUID().UUIDString)
expect(url.checkResourceIsReachableAndReturnError(nil)) == false
_ = SEGFileStorage(folder: url, crypto: nil)
var isDir: ObjCBool = false
let exists = NSFileManager.defaultManager().fileExistsAtPath(url.path!, isDirectory: &isDir)
expect(exists) == true
expect(Bool(isDir)) == true
}
it("persists and loads data") {
let dataIn = "segment".dataUsingEncoding(NSUTF8StringEncoding)!
storage.setData(dataIn, forKey: "mydata")
let dataOut = storage.dataForKey("mydata")
expect(dataOut) == dataIn
let strOut = String(data: dataOut!, encoding: NSUTF8StringEncoding)
expect(strOut) == "segment"
}
it("persists and loads string") {
let str = "san francisco"
storage.setString(str, forKey: "city")
expect(storage.stringForKey("city")) == str
storage.removeKey("city")
expect(storage.stringForKey("city")).to(beNil())
}
it("persists and loads array") {
let array = [
"san francisco",
"new york",
"tallinn",
]
storage.setArray(array, forKey: "cities")
expect(storage.arrayForKey("cities") as? Array<String>) == array
storage.removeKey("cities")
expect(storage.arrayForKey("cities")).to(beNil())
}
it("persists and loads dictionary") {
let dict = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
storage.setDictionary(dict, forKey: "cityMap")
expect(storage.dictionaryForKey("cityMap") as? Dictionary<String, String>) == dict
storage.removeKey("cityMap")
expect(storage.dictionaryForKey("cityMap")).to(beNil())
}
it("saves file to disk and removes from disk") {
let key = "input.txt"
let url = storage.urlForKey(key)
expect(url.checkResourceIsReachableAndReturnError(nil)) == false
storage.setString("sloth", forKey: key)
expect(url.checkResourceIsReachableAndReturnError(nil)) == true
storage.removeKey(key)
expect(url.checkResourceIsReachableAndReturnError(nil)) == false
}
it("should be binary compatible with old SDKs") {
let key = "traits.plist"
let dictIn = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
(dictIn as NSDictionary).writeToURL(storage.urlForKey(key), atomically: true)
let dictOut = storage.dictionaryForKey(key)
expect(dictOut as? [String: String]) == dictIn
}
it("should work with crypto") {
let url = SEGFileStorage.applicationSupportDirectoryURL()
let crypto = SEGAES256Crypto(password: "thetrees")
let s = SEGFileStorage(folder: url!, crypto: crypto)
let dict = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
s.setDictionary(dict, forKey: "cityMap")
expect(s.dictionaryForKey("cityMap") as? Dictionary<String, String>) == dict
s.removeKey("cityMap")
expect(s.dictionaryForKey("cityMap")).to(beNil())
}
afterEach {
storage.resetAll()
}
}
}
| mit |
tsolomko/SWCompression | Sources/swcomp/Extensions/FileSystemType+CustomStringConvertible.swift | 1 | 551 | // Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
import SWCompression
extension FileSystemType: CustomStringConvertible {
public var description: String {
switch self {
case .fat:
return "FAT"
case .macintosh:
return "old Macintosh file system"
case .ntfs:
return "NTFS"
case .unix:
return "UNIX-like"
case .other:
return "other/unknown"
}
}
}
| mit |
Snowgan/WeiboDemo | WeiboDemo/XLImageTool.swift | 1 | 153 | //
// XLImageTool.swift
// WeiboDemo
//
// Created by Jennifer on 11/12/15.
// Copyright © 2015 Snowgan. All rights reserved.
//
import Foundation
| mit |
developerY/Active-Learning-Swift-2.0_DEMO | ActiveLearningSwift2.playground/Pages/Generics.xcplaygroundpage/Contents.swift | 3 | 10757 | //: [Previous](@previous)
// ------------------------------------------------------------------------------------------------
// Things to know:
//
// * Generics allow flexible, reusable functions and types that can work with any type, subject
// to restrictions that you define.
//
// * Swift's Array and Dictionary are both Generics.
//
// * Generics can be applied to Functions, Structures, Classes and Enumerations.
// ------------------------------------------------------------------------------------------------
// The problem that Generics solve
//
// Consider the following function which can swap two Ints.
func swapTwoInts(inout a: Int, inout b: Int)
{
let tmp = a
a = b
b = tmp
}
// What if we wanted to swap Strings? Or any other type? We would need to write a lot of different
// swap functions. Instead, let's use Generics. Consider the following generic function:
func swapTwoValues<T>(inout a: T, inout b: T)
{
let tmp = a
a = b
b = tmp
}
// The 'swapTwoValues()' function is a generic function in a sense that some or all of the types
// that it works on are generic (i.e., specific only to the calls placed on that function.)
//
// Study the first line of the function and notice the use of <T> and the type for 'a' and 'b' as
// type T. In this case, T is just a placeholder for a type and by studying this function, we can
// see that both 'a' and 'b' are the same type.
//
// If we call this function with two Integers, it will treat the function as one declared to accept
// two Ints, but if we pass in two Strings, it will work on Strings.
//
// If we study the body of the function, we'll see that it is coded in such a way as to work with
// any type passed in: The 'tmp' parameter's type is inferred by the value 'a' and 'a' and 'b' must
// be assignable. If any of this criteria are not met, a compilation error will appear for the
// function call the tries to call swapTwoValues() with a type that doesn't meet this criteria.
//
// Although we're using T as the name for our type placeholder, we can use any name we wish, though
// T is a common placeholder for single type lists. If we were to create a new implementation of
// the Dictionary class, we would want to use two type parameters and name them effectively, such
// as <KeyType, ValueType>.
//
// A type placholder can also be used to define the return type.
//
// Let's call it a few times to see it in action:
var aInt = 3
var bInt = 4
swapTwoValues(&aInt, &bInt)
aInt
bInt
var aDouble = 3.3
var bDouble = 4.4
swapTwoValues(&aDouble, &bDouble)
aDouble
bDouble
var aString = "three"
var bString = "four"
swapTwoValues(&aString, &bString)
aString
bString
// ------------------------------------------------------------------------------------------------
// Generic Types
//
// So far we've seen how to apply Generics to a function, let's see how they can be applied to
// a struct. We'll define a standard 'stack' implementation which works like an array that can
// "push" an element to the end of the array, or "pop" an element off of the end of the array.
//
// As you can see, the type placeholder, once defined for a struct, can be used anywhere in that
// struct to represent the given type. In the code below, the the type placeholder is used as the
// type for a property, the input parameter for a method and the return value for a method.
struct Stack<T>
{
var items = [T]()
mutating func push(item: T)
{
items.append(item)
}
mutating func pop() -> T
{
return items.removeLast()
}
}
// Let's use our new Stack:
var stackOfStrings = Stack<String>()
stackOfStrings.push("uno")
stackOfStrings.push("dos")
stackOfStrings.push("tres")
stackOfStrings.push("cuatro")
stackOfStrings.pop()
stackOfStrings.pop()
stackOfStrings.pop()
stackOfStrings.pop()
// ------------------------------------------------------------------------------------------------
// Type constraints
//
// So far, our type parameters are completely Generic - they can represent any given type.
// Sometimes we may want to apply constraints to those types. For example, the Swift Dictionary
// type uses generics and places a constraint on the key's type that it must be hashable (i.e., it
// must conform to the Hashable protocol, defined in the Swift standard library.)
//
// Constraints are defined with the following syntax:
func doSomethingWithKeyValue<KeyType: Hashable, ValueType>(someKey: KeyType, someValue: ValueType)
{
// Our keyType is known to be a Hashable, so we can use the hashValue defined by that protocol
// shown here:
someKey.hashValue
// 'someValue' is an unknown type to us, we'll just drop it here in case it's ever used so we
// can see the value
someValue
}
// Let's see type constraints in action. We'll create a function that finds a given value within
// an array and returns an optional index into the array where the first element was found.
//
// Take notice the constraint "Equatable" on the type T, which is key to making this function
// compile. Without it, we would get an error on the conditional statement used to compare each
// element from the array with the value being searched for. By including the Equatable, we tell
// the generic function that it is guaranteed to receive only values that meet that specific
// criteria.
func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int?
{
for (index, value) in enumerate(array)
{
if value == valueToFind
{
return index
}
}
return nil
}
// Let's try a few different inputs
let doubleIndex = findIndex([3.14159, 0.1, 0.25], 9.3)
let stringIndex = findIndex(["Mike", "Malcolm", "Andrea"], "Andrea")
// ------------------------------------------------------------------------------------------------
// Associated types
//
// Protocols use a different method of defining generic types, called Associated Types, which use
// type inference combined with Type Aliases.
//
// Let's jump right into some code:
protocol Container
{
typealias ItemType
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
// In the example above, we declare a Type Alias called ItemType, but because we're declaring
// a protocol, we're only declaring the requirement for the conforming target to provide the
// actual type alias.
//
// With Generics, the type of ItemType can actually be inferred, such that it provides the correct
// types for the append() and the subscript implementations.
//
// Let's see this in action as we turn our Stack into a container:
struct StackContainer<T> : Container
{
// Here we find our original stack implementation, unmodified
var items = [T]()
mutating func push(item: T)
{
items.append(item)
}
mutating func pop() -> T
{
return items.removeLast()
}
// Below, we conform to the protocol
mutating func append(item: T)
{
self.push(item)
}
var count: Int
{
return items.count
}
subscript(i: Int) -> T
{
return items[i]
}
}
// The new StackContainer is now ready to go. You may notice that it does not include the
// typealias that was required as part of the Container protocol. This is because the all of the
// places where an ItemType would be used are using T. This allows Swift to perform a backwards
// inferrence that ItemType must be a type T, and it allows this requirement to be met.
//
// Let's verify our work:
var stringStack = StackContainer<String>()
stringStack.push("Albert")
stringStack.push("Andrew")
stringStack.push("Betty")
stringStack.push("Jacob")
stringStack.pop()
stringStack.count
var doubleStack = StackContainer<Double>()
doubleStack.push(3.14159)
doubleStack.push(42.0)
doubleStack.push(1_000_000)
doubleStack.pop()
doubleStack.count
// We can also extend an existing types to conform to our new generic protocol. As it turns out
// Swift's built-in Array class already supports the requirements of our Container.
//
// Also, since the protocol's type inferrence method of implementing Generics, we can extend
// String without the need to modify String other than to extend it to conform to the protocol:
extension Array: Container {}
// ------------------------------------------------------------------------------------------------
// Where Clauses
//
// We can further extend our constraints on a type by including where clauses as part of a type
// parameter list. Where clauses provide a means for more constraints on associated types and/or
// one or more equality relationships between types and associated types.
//
// Let's take a look at a where clause in action. We'll define a function that works on two
// different containers that that must contain the same type of item.
func allItemsMatch
<C1: Container, C2: Container where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
(someContainer: C1, anotherContainer: C2) -> Bool
{
// Check that both containers contain the same number of items
if someContainer.count != anotherContainer.count
{
return false
}
// Check each pair of items to see if they are equivalent
for i in 0..<someContainer.count
{
if someContainer[i] != anotherContainer[i]
{
return false
}
}
// All items match, so return true
return true
}
// The function's type parameter list places the following restrictions on the types allowed:
//
// * C1 must conform to the Container protocol (C1: Container)
// * C2 must also conform to the Container protocol (C1: Container)
// * The ItemType for C1 must be the same as the ItemType for C2 (C1.ItemType == C2.ItemType)
// * The ItemType for C1 must conform to the Equatable protocol (C1.ItemType: Equatable)
//
// Note that we only need to specify that C1.ItemType conforms to Equatable because the code
// only calls the != operator (part of the Equatable protocol) on someContainer, which is the
// type C1.
//
// Let's test this out by passing the same value for each parameter which should definitely
// return true:
allItemsMatch(doubleStack, doubleStack)
// We can compare stringStack against an array of type String[] because we've extended Swift's
// Array type to conform to our Container protocol:
allItemsMatch(stringStack, ["Alpha", "Beta", "Theta"])
// Finally, if we attempt to call allItemsMatch with a stringStack and a doubleStack, we would get
// a compiler error because they do not store the same ItemType as defined in the function's
// where clause.
//
// The following line of code does not compile:
//
// allItemsMatch(stringStack, doubleStack)
//: [Next](@next)
| apache-2.0 |
natecook1000/swift-compiler-crashes | fixed/26459-swift-printingdiagnosticconsumer-handlediagnostic.swift | 7 | 212 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
[d{}
{class a{{{({{{{{([{t("
}{class
case,
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/01417-swift-extensiondecl-create.swift | 12 | 269 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func f<T : A {
class a {
}
((bytes: a {
func e() {
}
protocol e = {
extension A : c<T : start: 1]
}
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/17112-swift-sourcemanager-getmessage.swift | 11 | 250 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A {
enum b {
let a {
d[ {
class A {
extension NSData {
{
}
class
case ,
| mit |
lumoslabs/realm-cocoa | examples/ios/swift-2.0/Migration/AppDelegate.swift | 1 | 5364 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm 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 RealmSwift
// Old data models
/* V0
class Person: Object {
dynamic var firstName = ""
dynamic var lastName = ""
dynamic var age = 0
}
*/
/* V1
class Person: Object {
dynamic var fullName = "" // combine firstName and lastName into single field
dynamic var age = 0
}
*/
/* V2 */
class Pet: Object {
dynamic var name = ""
dynamic var type = ""
}
class Person: Object {
dynamic var fullName = ""
dynamic var age = 0
let pets = List<Pet>() // Add pets field
}
func bundlePath(path: String) -> String? {
let resourcePath = NSBundle.mainBundle().resourcePath as NSString?
return resourcePath?.stringByAppendingPathComponent(path)
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = UIViewController()
window?.makeKeyAndVisible()
// copy over old data files for migration
let defaultPath = Realm.defaultPath
let defaultParentPath = (defaultPath as NSString).stringByDeletingLastPathComponent
if let v0Path = bundlePath("default-v0.realm") {
try! NSFileManager.defaultManager().removeItemAtPath(defaultPath)
try! NSFileManager.defaultManager().copyItemAtPath(v0Path, toPath: defaultPath)
}
// define a migration block
// you can define this inline, but we will reuse this to migrate realm files from multiple versions
// to the most current version of our data model
let migrationBlock: MigrationBlock = { migration, oldSchemaVersion in
if oldSchemaVersion < 1 {
migration.enumerate(Person.className()) { oldObject, newObject in
if oldSchemaVersion < 1 {
// combine name fields into a single field
let firstName = oldObject!["firstName"] as! String
let lastName = oldObject!["lastName"] as! String
newObject?["fullName"] = "\(firstName) \(lastName)"
}
}
}
if oldSchemaVersion < 2 {
migration.enumerate(Person.className()) { oldObject, newObject in
// give JP a dog
if newObject?["fullName"] as? String == "JP McDonald" {
let jpsDog = migration.create(Pet.className(), value: ["Jimbo", "dog"])
let dogs = newObject?["pets"] as? List<MigrationObject>
dogs?.append(jpsDog)
}
}
}
print("Migration complete.")
}
setDefaultRealmSchemaVersion(3, migrationBlock: migrationBlock)
// print out all migrated objects in the default realm
// migration is performed implicitly on Realm access
print("Migrated objects in the default Realm: \(try! Realm().objects(Person))")
//
// Migrate a realms at a custom paths
//
if let v1Path = bundlePath("default-v1.realm"), v2Path = bundlePath("default-v2.realm") {
let realmv1Path = (defaultParentPath as NSString).stringByAppendingPathComponent("default-v1.realm")
let realmv2Path = (defaultParentPath as NSString).stringByAppendingPathComponent("default-v2.realm")
setSchemaVersion(3, realmPath: realmv1Path, migrationBlock: migrationBlock)
setSchemaVersion(3, realmPath: realmv2Path, migrationBlock: migrationBlock)
try! NSFileManager.defaultManager().removeItemAtPath(realmv1Path)
try! NSFileManager.defaultManager().copyItemAtPath(v1Path, toPath: realmv1Path)
try! NSFileManager.defaultManager().removeItemAtPath(realmv2Path)
try! NSFileManager.defaultManager().copyItemAtPath(v2Path, toPath: realmv2Path)
// migrate realms at realmv1Path manually, realmv2Path is migrated automatically on access
migrateRealm(realmv1Path)
// print out all migrated objects in the migrated realms
let realmv1 = try! Realm(path: realmv1Path)
print("Migrated objects in the Realm migrated from v1: \(realmv1.objects(Person))")
let realmv2 = try! Realm(path: realmv2Path)
print("Migrated objects in the Realm migrated from v2: \(realmv2.objects(Person))")
}
return true
}
}
| apache-2.0 |
devxoul/allkdic | LauncherApplication/AppDelegate.swift | 1 | 1025 | //
// AppDelegate.swift
// LauncherApplication
//
// Created by Jeong on 2017. 1. 27..
// Copyright © 2017년 Allkdic. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
let mainAppIdentifier = "kr.xoul.allkdic"
let runningApps = NSWorkspace.shared().runningApplications
let alreadyRunning = runningApps.filter { $0.bundleIdentifier == mainAppIdentifier }.count > 0
if !alreadyRunning {
let path = Bundle.main.bundlePath as NSString
var components = path.pathComponents
components.removeLast()
components.removeLast()
components.removeLast()
components.append("MacOS")
components.append("Allkdic")
let newPath = NSString.path(withComponents: components)
NSWorkspace.shared().launchApplication(newPath)
}
self.terminate()
}
func terminate() {
NSApp.terminate(nil)
}
}
| mit |
mercadopago/px-ios | ExampleSwift/ExampleSwift/Controllers/CustomCheckoutWithPostPaymentController.swift | 1 | 10141 | import UIKit
import MercadoPagoSDKV4
enum CustomCheckoutTestCase: String, CaseIterable {
case approved
case rejected
case error
var genericPayment: PXGenericPayment {
switch self {
case .approved:
return PXGenericPayment(
status: "approved",
statusDetail: "Pago aprobado desde procesadora custom!",
paymentId: "1234",
paymentMethodId: nil,
paymentMethodTypeId: nil
)
case .rejected:
return PXGenericPayment(
paymentStatus: .REJECTED,
statusDetail: "cc_amount_rate_limit_exceeded"
)
case .error:
fatalError("genericPayment no debe ser invocado para este caso")
}
}
}
final class CustomCheckoutWithPostPaymentController: UIViewController {
// MARK: - Outlets
@IBOutlet private var localeTextField: UITextField!
@IBOutlet private var publicKeyTextField: UITextField!
@IBOutlet private var preferenceIdTextField: UITextField!
@IBOutlet private var accessTokenTextField: UITextField!
@IBOutlet private var oneTapSwitch: UISwitch!
@IBOutlet private var testCasePicker: UIPickerView!
@IBOutlet private var customProcessorSwitch: UISwitch!
// MARK: - Variables
private var checkout: MercadoPagoCheckout?
// Collector Public Key
private var publicKey: String = "TEST-a463d259-b561-45fe-9dcc-0ce320d1a42f"
// Preference ID
private var preferenceId: String = "737302974-34e65c90-62ad-4b06-9f81-0aa08528ec53"
// Payer private key - Access Token
private var privateKey: String = "TEST-982391008451128-040514-b988271bf377ab11b0ace4f1ef338fe6-737303098"
// MARK: - Actions
@IBAction private func initCheckout(_ sender: Any) {
guard localeTextField.text?.count ?? 0 > 0,
publicKeyTextField.text?.count ?? 0 > 0,
preferenceIdTextField.text?.count ?? 0 > 0 else {
let alert = UIAlertController(
title: "Error",
message: "Complete los campos requeridos para continuar",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
present(alert, animated: true)
return
}
if customProcessorSwitch.isOn {
runMercadoPagoCheckoutWithLifecycleAndCustomProcessor()
} else {
runMercadoPagoCheckoutWithLifecycle()
}
}
@IBAction private func resetData(_ sender: Any) {
localeTextField.text = ""
publicKeyTextField.text = ""
preferenceIdTextField.text = ""
accessTokenTextField.text = ""
oneTapSwitch.setOn(true, animated: true)
}
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
let gradient = CAGradientLayer()
gradient.frame = view.bounds
let col1 = UIColor(red: 34.0 / 255.0, green: 211 / 255.0, blue: 198 / 255.0, alpha: 1)
let col2 = UIColor(red: 145 / 255.0, green: 72.0 / 255.0, blue: 203 / 255.0, alpha: 1)
gradient.colors = [col1.cgColor, col2.cgColor]
view.layer.insertSublayer(gradient, at: 0)
if let path = Bundle.main.path(forResource: "Info", ofType: "plist"),
let infoPlist = NSDictionary(contentsOfFile: path) {
// Initialize values from config
publicKeyTextField.text = infoPlist["PX_COLLECTOR_PUBLIC_KEY"] as? String
accessTokenTextField.text = infoPlist["PX_PAYER_PRIVATE_KEY"] as? String
}
localeTextField.text = "es-AR"
preferenceIdTextField.text = preferenceId
publicKeyTextField.text = publicKey
accessTokenTextField.text = privateKey
self.testCasePicker.delegate = self
self.testCasePicker.dataSource = self
}
// MARK: - Checkout Setup
private func runMercadoPagoCheckoutWithLifecycle() {
guard let publicKey = publicKeyTextField.text,
let preferenceId = preferenceIdTextField.text,
let language = localeTextField.text else {
return
}
let builder = MercadoPagoCheckoutBuilder(publicKey: publicKey, preferenceId: preferenceId).setLanguage(language)
if let privateKey = accessTokenTextField.text {
builder.setPrivateKey(key: privateKey)
}
if oneTapSwitch.isOn {
let advancedConfiguration = PXAdvancedConfiguration()
builder.setAdvancedConfiguration(config: advancedConfiguration)
}
let postPaymentConfig = PXPostPaymentConfiguration()
postPaymentConfig.postPaymentNotificationName = .init("example postpayment")
builder.setPostPaymentConfiguration(config: postPaymentConfig)
suscribeToPostPaymentNotification(postPaymentConfig: postPaymentConfig)
let checkout = MercadoPagoCheckout(builder: builder)
if let myNavigationController = navigationController {
checkout.start(navigationController: myNavigationController, lifeCycleProtocol: self)
}
}
private func runMercadoPagoCheckoutWithLifecycleAndCustomProcessor() {
// Create charge rules
let pxPaymentTypeChargeRules = [
PXPaymentTypeChargeRule.init(
paymentTypeId: PXPaymentTypes.CREDIT_CARD.rawValue,
amountCharge: 10.00
)
]
// Create an instance of your custom payment processor
let row = testCasePicker.selectedRow(inComponent: 0)
let testCase = CustomCheckoutTestCase.allCases[row]
let paymentProcessor: PXPaymentProcessor = CustomPostPaymentProcessor(with: testCase)
// Create a payment configuration instance using the recently created payment processor
let paymentConfiguration = PXPaymentConfiguration(paymentProcessor: paymentProcessor)
// Add charge rules
_ = paymentConfiguration.addChargeRules(charges: pxPaymentTypeChargeRules)
let checkoutPreference = PXCheckoutPreference(
siteId: "MLA",
payerEmail: "[email protected]",
items: [
PXItem(
title: "iPhone 12",
quantity: 1,
unitPrice: 150.0
)
]
)
// Add excluded methods
checkoutPreference.addExcludedPaymentMethod("master")
guard let publicKey = publicKeyTextField.text,
let privateKey = accessTokenTextField.text,
let language = localeTextField.text else {
return
}
let builder = MercadoPagoCheckoutBuilder(
publicKey: publicKey,
checkoutPreference: checkoutPreference,
paymentConfiguration: paymentConfiguration
)
builder.setLanguage(language)
builder.setPrivateKey(key: privateKey)
// Adding a post payment notification and suscribed it
let postPaymentConfig = PXPostPaymentConfiguration()
postPaymentConfig.postPaymentNotificationName = .init("example postpayment")
builder.setPostPaymentConfiguration(config: postPaymentConfig)
suscribeToPostPaymentNotification(postPaymentConfig: postPaymentConfig)
// Instantiate a configuration object
let configuration = PXAdvancedConfiguration()
// Add custom PXDynamicViewController component
configuration.dynamicViewControllersConfiguration = [CustomPXDynamicComponent()]
// Configure the builder object
builder.setAdvancedConfiguration(config: configuration)
// Set the payer private key
builder.setPrivateKey(key: privateKey)
// Create Checkout reference
checkout = MercadoPagoCheckout(builder: builder)
// Start with your navigation controller.
if let myNavigationController = navigationController {
checkout?.start(navigationController: myNavigationController, lifeCycleProtocol: self)
}
}
func suscribeToPostPaymentNotification(postPaymentConfig: PXPostPaymentConfiguration) {
MercadoPagoCheckout.NotificationCenter.SubscribeTo.postPaymentAction(
forName: postPaymentConfig.postPaymentNotificationName ?? .init("")
) { [weak self] _, resultBlock in
let postPayment = PostPaymentViewController(with: resultBlock)
self?.present(
UINavigationController(rootViewController: postPayment),
animated: true,
completion: nil
)
}
}
}
// MARK: Optional Lifecycle protocol implementation example.
extension CustomCheckoutWithPostPaymentController: PXLifeCycleProtocol {
func finishCheckout() -> ((PXResult?) -> Void)? {
return nil
}
func cancelCheckout() -> (() -> Void)? {
return nil
}
func changePaymentMethodTapped() -> (() -> Void)? {
return { () in
print("px - changePaymentMethodTapped")
}
}
}
extension CustomCheckoutWithPostPaymentController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.text = ""
}
func textField(
_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String
) -> Bool {
return string != " "
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.text = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
extension CustomCheckoutWithPostPaymentController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return CustomCheckoutTestCase.allCases.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return CustomCheckoutTestCase.allCases[row].rawValue
}
}
| mit |
takamashiro/XDYZB | XDYZB/XDYZB/Classes/Home/ViewModel/AmuseViewModel.swift | 1 | 408 | //
// AmuseViewModel.swift
// XDYZB
//
// Created by takamashiro on 2016/10/11.
// Copyright © 2016年 com.takamashiro. All rights reserved.
//
import UIKit
class AmuseViewModel: BaseViewModel {
}
extension AmuseViewModel {
func loadAmuseData(finishedCallback : @escaping () -> ()) {
loadAnchorData(isGroupData: true, URLString: kGetAmuseData, finishedCallback: finishedCallback)
}
}
| mit |
epv44/EVTopTabBar | Example/EVTopTabBar/ViewController.swift | 1 | 2425 | //
// ViewController.swift
// EVTopTabBar
//
// Created by Eric Vennaro on 02/29/2016.
// Copyright (c) 2016 Eric Vennaro. All rights reserved.
//
import UIKit
import EVTopTabBar
class ViewController: UIViewController, EVTabBar {
var pageController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
var topTabBar: EVPageViewTopTabBar? {
didSet {
topTabBar?.fontColors = (selectedColor: UIColor.gray, unselectedColor: UIColor.lightGray)
topTabBar?.rightButtonText = "Events"
topTabBar?.leftButtonText = "Contacts"
topTabBar?.middleButtonText = "Tasks"
topTabBar?.middleRightButtonText = "Locations"
topTabBar?.labelFont = UIFont(name: "Helvetica", size: 11)!
topTabBar?.indicatorViewColor = UIColor.blue
topTabBar?.backgroundColor = UIColor.white
topTabBar?.delegate = self
}
}
var subviewControllers: [UIViewController] = []
var shadowView = UIImageView(image: #imageLiteral(resourceName: "filter-background-image"))
override func viewDidLoad() {
super.viewDidLoad()
topTabBar = EVPageViewTopTabBar(for: .four, withIndicatorStyle: .textWidth)
let firstVC = FirstViewController(nibName:"FirstViewController", bundle: nil)
let secondVC = SecondViewController(nibName:"SecondViewController", bundle: nil)
let thirdVC = ThirdViewController(nibName: "ThirdViewController", bundle: nil)
let fourthVC = FourthViewController(nibName: "FourthViewController", bundle: nil)
subviewControllers = [firstVC, secondVC, thirdVC, fourthVC]
setupPageView()
setupConstraints()
self.title = "EVTopTabBar"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
//MARK: EVTabBarDataSource
extension ViewController: EVTabBarDelegate {
func willSelectViewControllerAtIndex(_ index: Int, direction: UIPageViewController.NavigationDirection) {
if index > subviewControllers.count {
pageController.setViewControllers([subviewControllers[subviewControllers.count - 1]], direction: direction, animated: true, completion: nil)
} else {
pageController.setViewControllers([subviewControllers[index]], direction: direction, animated: true, completion: nil)
}
}
}
| mit |
apple/swift-nio-ssl | Tests/NIOSSLTests/ByteBufferBIOTest.swift | 1 | 12483 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import NIOCore
@_implementationOnly import CNIOBoringSSL
@testable import NIOSSL
final class ByteBufferBIOTest: XCTestCase {
override func setUp() {
guard boringSSLIsInitialized else {
fatalError("Cannot run tests without BoringSSL")
}
}
/// This leaks on purpose!
private func retainedBIO() -> UnsafeMutablePointer<BIO> {
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
swiftBIO.close()
return swiftBIO.retainedBIO()
}
func testExtractingBIOWrite() throws {
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
let cBIO = swiftBIO.retainedBIO()
defer {
CNIOBoringSSL_BIO_free(cBIO)
swiftBIO.close()
}
XCTAssertNil(swiftBIO.outboundCiphertext())
var bytesToWrite: [UInt8] = [1, 2, 3, 4, 5]
let rc = CNIOBoringSSL_BIO_write(cBIO, &bytesToWrite, 5)
XCTAssertEqual(rc, 5)
guard let extractedBytes = swiftBIO.outboundCiphertext().flatMap({ $0.getBytes(at: $0.readerIndex, length: $0.readableBytes) }) else {
XCTFail("No received bytes")
return
}
XCTAssertEqual(extractedBytes, bytesToWrite)
XCTAssertNil(swiftBIO.outboundCiphertext())
}
func testManyBIOWritesAreCoalesced() throws {
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
let cBIO = swiftBIO.retainedBIO()
defer {
CNIOBoringSSL_BIO_free(cBIO)
swiftBIO.close()
}
XCTAssertNil(swiftBIO.outboundCiphertext())
var bytesToWrite: [UInt8] = [1, 2, 3, 4, 5]
var expectedBytes = [UInt8]()
for _ in 0..<10 {
let rc = CNIOBoringSSL_BIO_write(cBIO, &bytesToWrite, 5)
XCTAssertEqual(rc, 5)
expectedBytes.append(contentsOf: bytesToWrite)
}
guard let extractedBytes = swiftBIO.outboundCiphertext().flatMap({ $0.getBytes(at: $0.readerIndex, length: $0.readableBytes) }) else {
XCTFail("No received bytes")
return
}
XCTAssertEqual(extractedBytes, expectedBytes)
XCTAssertNil(swiftBIO.outboundCiphertext())
}
func testReadWithNoDataInBIO() throws {
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
let cBIO = swiftBIO.retainedBIO()
defer {
CNIOBoringSSL_BIO_free(cBIO)
swiftBIO.close()
}
var targetBuffer = [UInt8](repeating: 0, count: 512)
let rc = CNIOBoringSSL_BIO_read(cBIO, &targetBuffer, 512)
XCTAssertEqual(rc, -1)
XCTAssertTrue(CNIOBoringSSL_BIO_should_retry(cBIO) != 0)
XCTAssertTrue(CNIOBoringSSL_BIO_should_read(cBIO) != 0)
XCTAssertEqual(targetBuffer, [UInt8](repeating: 0, count: 512))
}
func testReadWithDataInBIO() throws {
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
let cBIO = swiftBIO.retainedBIO()
defer {
CNIOBoringSSL_BIO_free(cBIO)
swiftBIO.close()
}
var inboundBytes = ByteBufferAllocator().buffer(capacity: 1024)
inboundBytes.writeBytes([1, 2, 3, 4, 5])
swiftBIO.receiveFromNetwork(buffer: inboundBytes)
var receivedBytes = ByteBufferAllocator().buffer(capacity: 1024)
let rc = receivedBytes.writeWithUnsafeMutableBytes(minimumWritableBytes: 1024) { pointer in
let innerRC = CNIOBoringSSL_BIO_read(cBIO, pointer.baseAddress!, CInt(pointer.count))
XCTAssertTrue(innerRC > 0)
return innerRC > 0 ? Int(innerRC) : 0
}
XCTAssertEqual(rc, 5)
XCTAssertEqual(receivedBytes, inboundBytes)
let secondRC = receivedBytes.withUnsafeMutableWritableBytes { pointer in
CNIOBoringSSL_BIO_read(cBIO, pointer.baseAddress!, CInt(pointer.count))
}
XCTAssertEqual(secondRC, -1)
XCTAssertTrue(CNIOBoringSSL_BIO_should_retry(cBIO) != 0)
XCTAssertTrue(CNIOBoringSSL_BIO_should_read(cBIO) != 0)
}
func testShortReads() throws {
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
let cBIO = swiftBIO.retainedBIO()
defer {
CNIOBoringSSL_BIO_free(cBIO)
swiftBIO.close()
}
var inboundBytes = ByteBufferAllocator().buffer(capacity: 1024)
inboundBytes.writeBytes([1, 2, 3, 4, 5])
swiftBIO.receiveFromNetwork(buffer: inboundBytes)
var receivedBytes = ByteBufferAllocator().buffer(capacity: 1024)
for _ in 0..<5 {
let rc = receivedBytes.writeWithUnsafeMutableBytes(minimumWritableBytes: 1024) { pointer in
let innerRC = CNIOBoringSSL_BIO_read(cBIO, pointer.baseAddress!, 1)
XCTAssertTrue(innerRC > 0)
return innerRC > 0 ? Int(innerRC) : 0
}
XCTAssertEqual(rc, 1)
}
XCTAssertEqual(receivedBytes, inboundBytes)
let secondRC = receivedBytes.withUnsafeMutableWritableBytes { pointer in
CNIOBoringSSL_BIO_read(cBIO, pointer.baseAddress!, CInt(pointer.count))
}
XCTAssertEqual(secondRC, -1)
XCTAssertTrue(CNIOBoringSSL_BIO_should_retry(cBIO) != 0)
XCTAssertTrue(CNIOBoringSSL_BIO_should_read(cBIO) != 0)
}
func testDropRefToBaseObjectOnRead() throws {
let cBIO = self.retainedBIO()
let receivedBytes = ByteBufferAllocator().buffer(capacity: 1024)
receivedBytes.withVeryUnsafeBytes { pointer in
let rc = CNIOBoringSSL_BIO_read(cBIO, UnsafeMutableRawPointer(mutating: pointer.baseAddress!), 1)
XCTAssertEqual(rc, -1)
XCTAssertTrue(CNIOBoringSSL_BIO_should_retry(cBIO) == 0)
}
}
func testDropRefToBaseObjectOnWrite() throws {
let cBIO = self.retainedBIO()
var receivedBytes = ByteBufferAllocator().buffer(capacity: 1024)
receivedBytes.writeBytes([1, 2, 3, 4, 5])
receivedBytes.withVeryUnsafeBytes { pointer in
let rc = CNIOBoringSSL_BIO_write(cBIO, pointer.baseAddress!, 1)
XCTAssertEqual(rc, -1)
XCTAssertTrue(CNIOBoringSSL_BIO_should_retry(cBIO) == 0)
}
}
func testZeroLengthReadsAlwaysSucceed() throws {
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
let cBIO = swiftBIO.retainedBIO()
defer {
CNIOBoringSSL_BIO_free(cBIO)
swiftBIO.close()
}
var targetBuffer = [UInt8](repeating: 0, count: 512)
let rc = CNIOBoringSSL_BIO_read(cBIO, &targetBuffer, 0)
XCTAssertEqual(rc, 0)
XCTAssertEqual(targetBuffer, [UInt8](repeating: 0, count: 512))
}
func testWriteWhenHoldingBufferTriggersCoW() throws {
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
let cBIO = swiftBIO.retainedBIO()
defer {
CNIOBoringSSL_BIO_free(cBIO)
swiftBIO.close()
}
var bytesToWrite: [UInt8] = [1, 2, 3, 4, 5]
let rc = CNIOBoringSSL_BIO_write(cBIO, &bytesToWrite, 5)
XCTAssertEqual(rc, 5)
guard let firstWrite = swiftBIO.outboundCiphertext() else {
XCTFail("Did not write")
return
}
let secondRC = CNIOBoringSSL_BIO_write(cBIO, &bytesToWrite, 5)
XCTAssertEqual(secondRC, 5)
guard let secondWrite = swiftBIO.outboundCiphertext() else {
XCTFail("Did not write second time")
return
}
XCTAssertNotEqual(firstWrite.baseAddress(), secondWrite.baseAddress())
}
func testWriteWhenDroppedBufferDoesNotTriggerCoW() {
func writeAddress(swiftBIO: ByteBufferBIO, cBIO: UnsafeMutablePointer<BIO>) -> UInt? {
var bytesToWrite: [UInt8] = [1, 2, 3, 4, 5]
let rc = CNIOBoringSSL_BIO_write(cBIO, &bytesToWrite, 5)
XCTAssertEqual(rc, 5)
return swiftBIO.outboundCiphertext()?.baseAddress()
}
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
let cBIO = swiftBIO.retainedBIO()
defer {
CNIOBoringSSL_BIO_free(cBIO)
swiftBIO.close()
}
let firstAddress = writeAddress(swiftBIO: swiftBIO, cBIO: cBIO)
let secondAddress = writeAddress(swiftBIO: swiftBIO, cBIO: cBIO)
XCTAssertNotNil(firstAddress)
XCTAssertNotNil(secondAddress)
XCTAssertEqual(firstAddress, secondAddress)
}
func testZeroLengthWriteIsNoOp() {
// This test works by emulating testWriteWhenHoldingBufferTriggersCoW, but
// with the second write at zero length. This will not trigger a CoW, as no
// actual write will occur.
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
let cBIO = swiftBIO.retainedBIO()
defer {
CNIOBoringSSL_BIO_free(cBIO)
swiftBIO.close()
}
var bytesToWrite: [UInt8] = [1, 2, 3, 4, 5]
let rc = CNIOBoringSSL_BIO_write(cBIO, &bytesToWrite, 5)
XCTAssertEqual(rc, 5)
guard let firstWrite = swiftBIO.outboundCiphertext() else {
XCTFail("Did not write")
return
}
withExtendedLifetime(firstWrite) {
let secondRC = CNIOBoringSSL_BIO_write(cBIO, &bytesToWrite, 0)
XCTAssertEqual(secondRC, 0)
XCTAssertNil(swiftBIO.outboundCiphertext())
}
}
func testSimplePuts() {
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
let cBIO = swiftBIO.retainedBIO()
defer {
CNIOBoringSSL_BIO_free(cBIO)
swiftBIO.close()
}
XCTAssertNil(swiftBIO.outboundCiphertext())
let stringToWrite = "Hello, world!"
let rc = stringToWrite.withCString {
CNIOBoringSSL_BIO_puts(cBIO, $0)
}
XCTAssertEqual(rc, 13)
let extractedString = swiftBIO.outboundCiphertext().flatMap { $0.getString(at: $0.readerIndex, length: $0.readableBytes) }
XCTAssertEqual(extractedString, stringToWrite)
XCTAssertNil(swiftBIO.outboundCiphertext())
}
func testGetsNotSupported() {
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
let cBIO = swiftBIO.retainedBIO()
defer {
CNIOBoringSSL_BIO_free(cBIO)
swiftBIO.close()
}
var buffer = ByteBufferAllocator().buffer(capacity: 1024)
buffer.writeStaticString("Hello, world!")
swiftBIO.receiveFromNetwork(buffer: buffer)
var output = Array<CChar>(repeating: 0, count: 1024)
output.withUnsafeMutableBufferPointer { pointer in
let rc = CNIOBoringSSL_BIO_gets(cBIO, pointer.baseAddress, CInt(pointer.count))
XCTAssertEqual(rc, -2)
XCTAssertTrue(CNIOBoringSSL_BIO_should_retry(cBIO) == 0)
}
}
func testBasicCtrlDance() {
let swiftBIO = ByteBufferBIO(allocator: ByteBufferAllocator())
let cBIO = swiftBIO.retainedBIO()
defer {
CNIOBoringSSL_BIO_free(cBIO)
swiftBIO.close()
}
let originalShutdown = CNIOBoringSSL_BIO_ctrl(cBIO, BIO_CTRL_GET_CLOSE, 0, nil)
XCTAssertEqual(originalShutdown, CLong(BIO_CLOSE))
let rc = CNIOBoringSSL_BIO_set_close(cBIO, CInt(BIO_NOCLOSE))
XCTAssertEqual(rc, 1)
let newShutdown = CNIOBoringSSL_BIO_ctrl(cBIO, BIO_CTRL_GET_CLOSE, 0, nil)
XCTAssertEqual(newShutdown, CLong(BIO_NOCLOSE))
let rc2 = CNIOBoringSSL_BIO_set_close(cBIO, CInt(BIO_CLOSE))
XCTAssertEqual(rc2, 1)
let newShutdown2 = CNIOBoringSSL_BIO_ctrl(cBIO, BIO_CTRL_GET_CLOSE, 0, nil)
XCTAssertEqual(newShutdown2, CLong(BIO_CLOSE))
}
}
extension ByteBuffer {
func baseAddress() -> UInt {
return self.withVeryUnsafeBytes { return UInt(bitPattern: $0.baseAddress! )}
}
}
| apache-2.0 |
b0oh/mal | swift/reader.swift | 1 | 7075 | //******************************************************************************
// MAL - reader
//******************************************************************************
import Foundation
let kSymbolWithMeta = MalSymbol(symbol: "with-meta")
let kSymbolDeref = MalSymbol(symbol: "deref")
let token_pattern =
"[[:space:],]*" + // Skip whitespace: a sequence of zero or more commas or [:space:]'s
"(" +
"~@" + // Literal "~@"
"|" +
"[\\[\\]{}()`'~^@]" + // Punctuation: Any one of []{}()`'~^@
"|" +
"\"(?:\\\\.|[^\\\\\"])*\"" + // Quoted string: characters other than \ or ", or any escaped characters
"|" +
";.*" + // Comment: semicolon followed by anything
"|" +
"[^[:space:]\\[\\]{}()`'\",;]*" + // Symbol, keyword, number, nil, true, false: any sequence of chars but [:space:] or []{}()`'",;
")"
let atom_pattern =
"(^;.*$)" + // Comment
"|" +
"(^-?[0-9]+$)" + // Integer
"|" +
"(^-?[0-9][0-9.]*$)" + // Float
"|" +
"(^nil$)" + // nil
"|" +
"(^true$)" + // true
"|" +
"(^false$)" + // false
"|" +
"(^\".*\"$)" + // String
"|" +
"(:.*)" + // Keyword
"|" +
"(^[^\"]*$)" // Symbol
var token_regex: NSRegularExpression = NSRegularExpression(pattern:token_pattern, options:.allZeros, error:nil)!
var atom_regex: NSRegularExpression = NSRegularExpression(pattern:atom_pattern, options:.allZeros, error:nil)!
class Reader {
init(_ tokens: [String]) {
self.tokens = tokens
self.index = 0
}
func next() -> String? {
let token = peek()
increment()
return token
}
func peek() -> String? {
if index < tokens.count {
return tokens[index]
}
return nil
}
private func increment() {
++index
}
private let tokens: [String]
private var index: Int
}
func tokenizer(s: String) -> [String] {
var tokens = [String]()
let range = NSMakeRange(0, s.utf16Count)
let matches = token_regex.matchesInString(s, options:.allZeros, range:range)
for match in matches as [NSTextCheckingResult] {
if match.range.length > 0 {
let token = (s as NSString).substringWithRange(match.rangeAtIndex(1))
tokens.append(token)
}
}
return tokens
}
private func have_match_at(match: NSTextCheckingResult, index:Int) -> Bool {
return Int64(match.rangeAtIndex(index).location) < LLONG_MAX
}
func read_atom(token: String) -> MalVal {
let range = NSMakeRange(0, token.utf16Count)
let matches = atom_regex.matchesInString(token, options:.allZeros, range:range)
for match in matches as [NSTextCheckingResult] {
if have_match_at(match, 1) { // Comment
return MalComment(comment: token)
} else if have_match_at(match, 2) { // Integer
if let value = NSNumberFormatter().numberFromString(token)?.longLongValue {
return MalInteger(value: value)
}
return MalError(message: "invalid integer: \(token)")
} else if have_match_at(match, 3) { // Float
if let value = NSNumberFormatter().numberFromString(token)?.doubleValue {
return MalFloat(value: value)
}
return MalError(message: "invalid float: \(token)")
} else if have_match_at(match, 4) { // nil
return MalNil()
} else if have_match_at(match, 5) { // true
return MalTrue()
} else if have_match_at(match, 6) { // false
return MalFalse()
} else if have_match_at(match, 7) { // String
return MalString(escaped: token)
} else if have_match_at(match, 8) { // Keyword
return MalKeyword(keyword: dropFirst(token))
} else if have_match_at(match, 9) { // Symbol
return MalSymbol(symbol: token)
}
}
return MalError(message: "Unknown token=\(token)")
}
func read_elements(r: Reader, open: String, close: String) -> ([MalVal]?, MalVal?) {
var list = [MalVal]()
while let token = r.peek() {
if token == close {
r.increment() // Consume the closing paren
return (list, nil)
} else {
let item = read_form(r)
if is_error(item) {
return (nil, item)
}
if item.type != .TypeComment {
list.append(item)
}
}
}
return (nil, MalError(message: "ran out of tokens -- possibly unbalanced ()'s"))
}
func read_list(r: Reader) -> MalVal {
let (list, err) = read_elements(r, "(", ")")
return err != nil ? err! : MalList(array: list!)
}
func read_vector(r: Reader) -> MalVal {
let (list, err) = read_elements(r, "[", "]")
return err != nil ? err! : MalVector(array: list!)
}
func read_hashmap(r: Reader) -> MalVal {
let (list, err) = read_elements(r, "{", "}")
return err != nil ? err! : MalHashMap(array: list!)
}
func common_quote(r: Reader, symbol: String) -> MalVal {
let next = read_form(r)
if is_error(next) { return next }
return MalList(objects: MalSymbol(symbol: symbol), next)
}
func read_form(r: Reader) -> MalVal {
if let token = r.next() {
switch token {
case "(":
return read_list(r)
case ")":
return MalError(message: "unexpected \")\"")
case "[":
return read_vector(r)
case "]":
return MalError(message: "unexpected \"]\"")
case "{":
return read_hashmap(r)
case "}":
return MalError(message: "unexpected \"}\"")
case "`":
return common_quote(r, "quasiquote")
case "'":
return common_quote(r, "quote")
case "~":
return common_quote(r, "unquote")
case "~@":
return common_quote(r, "splice-unquote")
case "^":
let meta = read_form(r)
if is_error(meta) { return meta }
let form = read_form(r)
if is_error(form) { return form }
return MalList(objects: kSymbolWithMeta, form, meta)
case "@":
let form = read_form(r)
if is_error(form) { return form }
return MalList(objects: kSymbolDeref, form)
default:
return read_atom(token)
}
}
return MalError(message: "ran out of tokens -- possibly unbalanced ()'s")
}
func read_str(s: String) -> MalVal {
let tokens = tokenizer(s)
let reader = Reader(tokens)
let obj = read_form(reader)
return obj
}
| mpl-2.0 |
kitasuke/SwiftProtobufSample | Client/Carthage/Checkouts/swift-protobuf/Tests/SwiftProtobufTests/unittest_import_lite.pb.swift | 2 | 4793 | /*
* DO NOT EDIT.
*
* Generated by the protocol buffer compiler.
* Source: google/protobuf/unittest_import_lite.proto
*
*/
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: [email protected] (Kenton Varda)
//
// This is like unittest_import.proto but with optimize_for = LITE_RUNTIME.
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _1: SwiftProtobuf.ProtobufAPIVersion_1 {}
typealias Version = _1
}
enum ProtobufUnittestImport_ImportEnumLite: SwiftProtobuf.Enum {
typealias RawValue = Int
case importLiteFoo // = 7
case importLiteBar // = 8
case importLiteBaz // = 9
init() {
self = .importLiteFoo
}
init?(rawValue: Int) {
switch rawValue {
case 7: self = .importLiteFoo
case 8: self = .importLiteBar
case 9: self = .importLiteBaz
default: return nil
}
}
var rawValue: Int {
switch self {
case .importLiteFoo: return 7
case .importLiteBar: return 8
case .importLiteBaz: return 9
}
}
}
struct ProtobufUnittestImport_ImportMessageLite: SwiftProtobuf.Message {
static let protoMessageName: String = _protobuf_package + ".ImportMessageLite"
fileprivate var _d: Int32? = nil
var d: Int32 {
get {return _d ?? 0}
set {_d = newValue}
}
var hasD: Bool {
return self._d != nil
}
mutating func clearD() {
self._d = nil
}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt32Field(value: &self._d)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._d {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "protobuf_unittest_import"
extension ProtobufUnittestImport_ImportEnumLite: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
7: .same(proto: "IMPORT_LITE_FOO"),
8: .same(proto: "IMPORT_LITE_BAR"),
9: .same(proto: "IMPORT_LITE_BAZ"),
]
}
extension ProtobufUnittestImport_ImportMessageLite: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "d"),
]
func _protobuf_generated_isEqualTo(other: ProtobufUnittestImport_ImportMessageLite) -> Bool {
if self._d != other._d {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
| mit |
nottombrown/HausClock | HausClock/AppDelegate.swift | 2 | 2413 | //
// AppDelegate.swift
// HausClock
//
// Created by Tom Brown on 7/13/14.
// Copyright (c) 2014 not. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
// Override point for customization after application launch.
UIApplication.sharedApplication().idleTimerDisabled = true
return true
}
func applicationWillResignActive(application: UIApplication!) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
game.state.value = .Paused // Pause the game when the app is moved to the background
}
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.
game.state.value = .Paused // Pause the game when the app is moved to the background
}
func applicationWillEnterForeground(application: UIApplication!) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication!) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication!) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
Tonkpils/SpaceRun | SpaceRun/GameViewController.swift | 1 | 2107 | //
// GameViewController.swift
// SpaceRun
//
// Created by Leonardo Correa on 11/29/15.
// Copyright (c) 2015 Leonardo Correa. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
var easyMode : Bool?
override func viewDidLoad() {
super.viewDidLoad()
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
let blackScene = SKScene(size: skView.bounds.size)
blackScene.backgroundColor = UIColor.blackColor()
skView.presentScene(blackScene)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let skView = self.view as! SKView
let openingScene = OpeningScene(size: skView.bounds.size)
openingScene.scaleMode = .AspectFill
let transition = SKTransition.fadeWithDuration(1)
skView.presentScene(openingScene, transition: transition)
openingScene.sceneEndCallback = {
[unowned self] in
let scene : GameScene = GameScene(size: skView.bounds.size)
scene.endGameCallback = {
self.navigationController?.popViewControllerAnimated(true)
}
scene.easyMode = self.easyMode
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit |
PGSSoft/3DSnakeAR | 3DSnake/common classes/Mushroom.swift | 1 | 1151 | //
// Mushroom.swift
// 3DSnake
//
// Created by Michal Kowalski on 20.07.2017.
// Copyright © 2017 PGS Software. All rights reserved.
//
import SceneKit
final class Mushroom: SCNNode {
var mushroomNode: SCNNode?
// MARK: - Lifecycle
override init() {
super.init()
if let scene = SCNScene(named: "mushroom.scn"), let mushroomNode = scene.rootNode.childNode(withName: "mushroom", recursively: true) {
addChildNode(mushroomNode)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("not implemented")
}
//MARK - Animations
func runAppearAnimation() {
mushroomNode?.position.y = -1
removeAllActions()
removeAllParticleSystems()
scale = SCNVector3(0.1, 0.1, 0.1)
addParticleSystem(SCNParticleSystem(named: "mushroom-appear", inDirectory: nil)!)
let scaleAction = SCNAction.scale(to: 1.0, duration: 1.0)
let removeParticle = SCNAction.run { _ in
self.removeAllParticleSystems()
}
let sequence = SCNAction.sequence([scaleAction, removeParticle])
runAction(sequence)
}
}
| mit |
QuiverApps/PiPass-iOS | PiPass-iOS/GetPiPassConfig.swift | 1 | 1162 | //
// GetPiPassConfig.swift
// PiPass-iOS
//
// Created by Jeremy Roberts on 11/22/15.
// Copyright © 2015 Jeremy Roberts. All rights reserved.
//
import Alamofire
import Mantle
public class GetPiPassConfig: NSObject {
public static func doApiCall(rpiAddress:String, success:(PiPassConfig) -> Void, failure:() -> Void) {
let cache = Int(arc4random_uniform(999) + 1)
let address = String(format: Constants.JsonEnpoints.PIPASS_CONFIG, arguments: [rpiAddress,cache])
Alamofire.request(.GET, address)
.responseJSON { response in
var piPassConfig:PiPassConfig = PiPassConfig()
if(response.result.isSuccess) {
if let responseValue = response.result.value {
let JSON = responseValue as! [NSObject : AnyObject]
piPassConfig = PiPassConfig.deserializeObjectFromJSON(JSON) as! PiPassConfig
success(piPassConfig)
}
} else {
failure()
}
}
}
} | mit |
dreamsxin/swift | validation-test/compiler_crashers_fixed/00761-swift-diagnosticengine-flushactivediagnostic.swift | 11 | 433 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
struct Q<T where T : d {
override func b
| apache-2.0 |
0xfeedface1993/Xs8-Safari-Block-Extension-Mac | Sex8BlockExtension/Sex8BlockExtension/Webservice/Webservice.swift | 1 | 5962 | //
// Webservice.swift
// S8Blocker
//
// Created by virus1993 on 2017/10/12.
// Copyright © 2017年 ascp. All rights reserved.
//
import AppKit
enum WebserviceError : Error {
case badURL(message: String)
case badSendJson(message: String)
case badResponseJson(message: String)
case emptyResponseData(message: String)
}
enum WebServiceMethod : String {
case post = "POST"
case get = "GET"
}
enum WebserviceBaseURL : String {
case main = "http://14d8856q96.imwork.net"
case aliyun = "http://120.78.89.159/api"
case debug = "http://127.0.0.1"
func url(method: WebserviceMethodPath) -> URL {
return URL(string: self.rawValue + method.rawValue)!
}
}
enum WebserviceMethodPath : String {
case registerDevice = "/api/v1/addDevice"
case findDevice = "/api/v1/findDevice"
case push = "/api/v1/pushAll"
}
class WebserviceCaller<T: Codable, X: Codable> {
var baseURL : WebserviceBaseURL
var way : WebServiceMethod
var method : WebserviceMethodPath
var paras : X?
var rawData : Data?
var execute : ((T?, Error?, ErrorResponse?)->())?
init(url: WebserviceBaseURL, way: WebServiceMethod, method: WebserviceMethodPath) {
self.baseURL = url
self.way = way
self.method = method
}
}
class Webservice {
static let share = Webservice()
var runningTask = [URLSessionDataTask]()
private var session : URLSession = {
let configuration = URLSessionConfiguration.default
return URLSession(configuration: configuration)
}()
func read<P : Codable, X: Codable>(caller : WebserviceCaller<P, X>) throws {
let responseHandler : (Data?, URLResponse?, Error?) -> Swift.Void = { (data, response, err) in
if let e = err {
caller.execute?(nil, e, nil)
return
}
let jsonDecoder = JSONDecoder()
guard let good = data else {
caller.execute?(nil, WebserviceError.badResponseJson(message: "返回数据为空"), nil)
return
}
if let errorResult = try? jsonDecoder.decode(ErrorResponse.self, from: good) {
caller.execute?(nil, nil, errorResult)
return
}
do {
let json = try jsonDecoder.decode(P.self, from: good)
caller.execute?(json, nil, nil)
} catch {
caller.execute?(nil, WebserviceError.badResponseJson(message: "错误的解析对象!请检查返回的JSON字符串是否符合解析的对象类型。\n\(String(data: good, encoding: .utf8) ?? "empty")"), nil)
}
}
func handler(task: URLSessionDataTask) -> ((Data?, URLResponse?, Error?) -> Swift.Void) {
return { (data, response, err) in
if let index = self.runningTask.enumerated().map({ return $0.offset }).first {
self.runningTask.remove(at: index)
}
if let e = err {
caller.execute?(nil, e, nil)
return
}
let jsonDecoder = JSONDecoder()
guard let good = data else {
caller.execute?(nil, WebserviceError.badResponseJson(message: "返回数据为空"), nil)
return
}
if let errorResult = try? jsonDecoder.decode(ErrorResponse.self, from: good) {
caller.execute?(nil, nil, errorResult)
return
}
do {
let json = try jsonDecoder.decode(P.self, from: good)
caller.execute?(json, nil, nil)
} catch {
caller.execute?(nil, WebserviceError.badResponseJson(message: "错误的解析对象!请检查返回的JSON字符串是否符合解析的对象类型。\n\(String(data: good, encoding: .utf8) ?? "empty")"), nil)
}
}
}
switch caller.way {
case .get:
let urlString = caller.baseURL.rawValue.appending("?method=\(caller.method.rawValue)")
if let url = URL(string: urlString) {
var request = URLRequest(url: url)
request.httpMethod = caller.way.rawValue
let task = session.dataTask(with: request, completionHandler: responseHandler)
task.resume()
runningTask.append(task)
return
}
throw WebserviceError.badURL(message: "错误的url:" + urlString)
case .post:
let urlString = caller.baseURL.url(method: caller.method).absoluteString
do {
var data : Data?
if let paras = caller.paras {
let encoder = JSONEncoder()
data = try? encoder.encode(paras)
} else if let raw = caller.rawData {
data = raw
}
if let url = URL(string: urlString) {
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = data
request.httpMethod = caller.way.rawValue
let task = session.dataTask(with: request, completionHandler: responseHandler)
task.resume()
runningTask.append(task)
return
}
throw WebserviceError.badURL(message: "错误的url:" + urlString)
} catch {
caller.execute?(nil, error, nil)
return
}
}
}
func cancelAllTask() {
runningTask.forEach { (task) in
task.cancel()
}
runningTask.removeAll()
}
}
| apache-2.0 |
emilstahl/swift | validation-test/compiler_crashers_fixed/26425-std-function-func-swift-constraints-constraintsystem-simplifytype.swift | 13 | 226 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
""[{({{}}()
| apache-2.0 |
darwin/textyourmom | TextYourMom/MapController.swift | 1 | 10755 | import UIKit
import MapKit
struct DebugLocation {
var description : String = ""
var latitude: Double = 0.0
var longitude: Double = 0.0
init(_ description: String, _ latitude: Double, _ longitude: Double) {
self.description = description
self.latitude = latitude
self.longitude = longitude
}
}
let debugLocations = [
DebugLocation("DONT OVERRIDE", 0.0, 0.0), // #0
DebugLocation("x no-mans-land", 48, 14),
DebugLocation("x surf office Las Palmas",28.1286,-15.4452),
DebugLocation("x surf office Santa Cruz",36.9624,-122.0310),
DebugLocation("SFO-inner-Milbrae-inner",37.6145,-122.3776),
DebugLocation("SFO-outer-Milbrae-outer",37.6231,-122.4166),
DebugLocation("SFO-outer-Milbrae-inner",37.6008,-122.4067),
DebugLocation("SFO-inner-Milbrae-outer",37.6356,-122.3677),
DebugLocation("SFO-outer",37.6547,-122.3687),
DebugLocation("Milbrae-outer",37.5679,-122.3944),
DebugLocation("Ceske Budejovice",48.946381,14.427464),
DebugLocation("Caslav",49.939653,15.381808),
DebugLocation("Hradec Kralove",50.2532,15.845228),
DebugLocation("Horovice",49.848111,13.893506),
DebugLocation("Kbely",50.121367,14.543642),
DebugLocation("Kunovice",49.029444,17.439722),
DebugLocation("Karlovy Vary",50.202978,12.914983),
DebugLocation("Plzen Line",49.675172,13.274617)
]
class AirportOverlay: MKCircle {
var type : AirportPerimeter = .Inner
func setupRenderer(renderer: MKCircleRenderer) {
let innerColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.05)
let outerColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.05)
if type == .Inner {
renderer.fillColor = innerColor
renderer.strokeColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.1)
renderer.lineWidth = 1
} else {
renderer.fillColor = outerColor
}
}
}
class FakeLocationAnnotation : MKPointAnnotation {
}
class CenterLocationAnnotation : MKPointAnnotation {
}
class MapController: BaseViewController {
@IBOutlet weak var locationPicker: UIPickerView!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var centerLabel: UILabel!
var overlaysDefined = false
var manualDragging = false
var fakeLocationAnnotation = FakeLocationAnnotation()
var centerLocationAnnotation = CenterLocationAnnotation()
override func viewDidLoad() {
super.viewDidLoad()
locationPicker.selectRow(overrideLocation, inComponent:0, animated:false)
// last known location
let londonLocation = CLLocationCoordinate2D(latitude: lastLatitude, longitude: lastLongitude)
// this is here just to prevent slow map loading because of extreme zoom-out
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: londonLocation, span: span)
mapView.setRegion(region, animated: true)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
mapController = self
manualDragging = false
mapView.removeAnnotation(centerLocationAnnotation)
defineAirportOverlays(masterController.airportsProvider)
}
override func viewDidDisappear(animated: Bool) {
mapController = nil
super.viewDidDisappear(animated)
}
func defineAirportOverlays(provider:AirportsProvider) {
if overlaysDefined {
return
}
func buildAirportOverlay(airport: Airport, perimeter: AirportPerimeter) -> AirportOverlay {
let center = CLLocationCoordinate2D(latitude:airport.latitude, longitude:airport.longitude)
let radius = CLLocationDistance(perimeter==AirportPerimeter.Inner ? innerAirportPerimeterDistance : outerAirportPerimeterDistance)
var overlay = AirportOverlay(centerCoordinate: center, radius: radius)
overlay.type = perimeter
return overlay
}
let airports = provider.airports
var overlays : [AirportOverlay] = []
var annotations : [MKPointAnnotation] = []
for airport in airports {
overlays.append(buildAirportOverlay(airport, .Outer))
overlays.append(buildAirportOverlay(airport, .Inner))
let annotation = MKPointAnnotation()
annotation.setCoordinate(CLLocationCoordinate2D(latitude:airport.latitude, longitude:airport.longitude))
annotation.title = airport.name
annotations.append(annotation)
}
mapView.addOverlays(overlays)
mapView.addAnnotations(annotations)
overlaysDefined = true
}
func updateLocation(latitude: Double, _ longitude:Double) {
if manualDragging {
return
}
let location = CLLocationCoordinate2D(latitude: latitude, longitude:longitude)
mapView.setCenterCoordinate(location, animated: true)
}
@IBAction func doApplyLocationOverride() {
manualDragging = false
mapView.removeAnnotation(centerLocationAnnotation)
overrideLocation = locationPicker.selectedRowInComponent(0)
let newDebugLocation = debugLocations[overrideLocation]
if overrideLocation > 0 {
log("manual override of location to \(newDebugLocation.description)")
masterController.airportsWatcher.emitFakeUpdateLocation(newDebugLocation.latitude, newDebugLocation.longitude)
fakeLocationAnnotation.setCoordinate(CLLocationCoordinate2D(latitude:newDebugLocation.latitude, longitude:newDebugLocation.longitude))
mapView.addAnnotation(fakeLocationAnnotation)
} else {
log("stopped overriding location")
mapView.removeAnnotation(fakeLocationAnnotation)
}
}
}
// MARK: MKMapViewDelegate
extension MapController : MKMapViewDelegate{
// http://stackoverflow.com/a/26002176/84283
func mapViewRegionDidChangeFromUserInteraction() -> Bool {
let view = (mapView.subviews[0] as? UIView)
let recognizers = view!.gestureRecognizers! as [AnyObject]
for recognizer in recognizers {
if recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Ended {
return true;
}
}
return false
}
func mapView(mapView: MKMapView!, regionWillChangeAnimated animated: Bool) {
if mapViewRegionDidChangeFromUserInteraction() {
manualDragging = true
mapView.addAnnotation(centerLocationAnnotation)
log("started manual dragging")
}
}
func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) {
var center = mapView.centerCoordinate
centerLocationAnnotation.setCoordinate(center)
let fmt = ".4"
centerLabel.text = "\(center.latitude.format(fmt)), \(center.longitude.format(fmt))"
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if let airportOverlay = overlay as? AirportOverlay {
var circleRenderer = MKCircleRenderer(overlay: airportOverlay)
airportOverlay.setupRenderer(circleRenderer)
return circleRenderer
}
return nil
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is MKUserLocation {
return nil // map view should draw "blue dot" for user location
}
if annotation is FakeLocationAnnotation {
let reuseId = "fake-location"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "Crosshairs")
annotationView.centerOffset = CGPointMake(0, 0)
annotationView.calloutOffset = CGPointMake(0, 0)
}
annotationView.annotation = annotation
return annotationView
}
if annotation is CenterLocationAnnotation {
let reuseId = "center-location"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
annotationView.canShowCallout = false
annotationView.image = UIImage(named: "MagentaDot")
annotationView.centerOffset = CGPointMake(0, 0)
annotationView.calloutOffset = CGPointMake(0, 0)
}
annotationView.annotation = annotation
return annotationView
}
let reuseId = "airport"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "DotCircle")
annotationView.centerOffset = CGPointMake(0, 0)
annotationView.calloutOffset = CGPointMake(0, 0)
}
annotationView.annotation = annotation
return annotationView
}
}
extension MapController : UIPickerViewDataSource {
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return debugLocations.count
}
}
extension MapController : UIPickerViewDelegate {
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return debugLocations[row].description
}
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let text = debugLocations[row].description
var attrString = NSMutableAttributedString(string: text)
var range = NSMakeRange(0, attrString.length)
attrString.beginEditing()
attrString.addAttribute(NSForegroundColorAttributeName, value:UIColor.blueColor(), range:range)
attrString.endEditing()
return attrString
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
doApplyLocationOverride()
}
}
| mit |
banDedo/BDModules | NavigationDrawerViewController/NavigationDrawerViewController.swift | 1 | 17526 | //
// NavigationDrawerViewController.swift
// Harness
//
// Created by Patrick Hogan on 3/17/15.
// Copyright (c) 2015 bandedo. All rights reserved.
//
import Snap
import UIKit
private let kNavigationDrawerDefaultRevealOffset = CGFloat(50.0)
public class NavigationDrawerViewController: LifecycleViewController, UIGestureRecognizerDelegate {
// MARK:- Enumerated Types
public enum Orientation {
case Default
case PartialRevealLeft
case RevealLeft
}
private enum ViewControllerIndex: Int {
case Left = 0
case Center = 1
static var count: Int {
var max: Int = 0
while let _ = self(rawValue: ++max) {}
return max
}
}
// MARK:- Properties
public var leftDrawerPartialRevealHorizontalOffset = CGFloat(kNavigationDrawerDefaultRevealOffset) {
didSet {
if !isDragging {
switch orientation {
case .PartialRevealLeft:
updateViewConstraints()
break
case .Default, .RevealLeft:
break
}
}
}
}
private(set) public var centerViewController: UIViewController?
private(set) public var leftDrawerViewController: UIViewController?
private(set) public lazy var statusBarBlockerView: UIView = {
let statusBarBlockerView = UIView(frame: CGRectZero)
statusBarBlockerView.backgroundColor = UIColor.blackColor()
return statusBarBlockerView
}()
public var animationDuration = NSTimeInterval(0.25)
public var shortAnimationDuration = NSTimeInterval(0.15)
public var minimumLeftContainerOffset = CGFloat(-kNavigationDrawerDefaultRevealOffset)
private(set) public var orientation = Orientation.Default
// MARK:- View lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
for containerView in containerViews {
view.addSubview(containerView)
}
view.addSubview(statusBarBlockerView)
leftContainerView.snp_makeConstraints() { make in
make.top.and.bottom.equalTo(UIEdgeInsetsZero);
make.width.equalTo(self.view);
}
centerContainerView.snp_makeConstraints() { make in
make.top.and.bottom.equalTo(UIEdgeInsetsZero);
make.width.equalTo(self.view);
}
blockingView.snp_makeConstraints() { make in
make.edges.equalTo(UIEdgeInsetsZero)
}
statusBarBlockerView.snp_makeConstraints() { make in
make.top.equalTo(self.view)
make.left.equalTo(self.view)
make.right.equalTo(self.view)
make.height.equalTo(UIApplication.sharedApplication().statusBarFrame.size.height)
}
}
// MARK:- Layout
public override func updateViewConstraints() {
centerContainerViewHorizontalOffsetConstraint?.uninstall()
leftContainerViewHorizontalOffsetConstraint?.uninstall()
centerContainerView.snp_makeConstraints() { make in
self.centerContainerViewHorizontalOffsetConstraint = {
if self.isDragging {
var currentHorizontalOffset = self.currentHorizontalOffset
if fabs(self.currentPanDelta!.x) > fabs(self.currentPanDelta!.y) {
currentHorizontalOffset -= self.currentPanDelta!.x
currentHorizontalOffset = max(0.0, currentHorizontalOffset)
currentHorizontalOffset = min(self.view.frame.size.width, currentHorizontalOffset)
}
return make.centerX.equalTo(self.view.snp_centerX).with.offset(currentHorizontalOffset)
} else {
switch self.orientation {
case .Default:
return make.left.equalTo(0.0)
case .PartialRevealLeft:
return make.left.equalTo(self.view.snp_right).with.offset(-self.leftDrawerPartialRevealHorizontalOffset)
case .RevealLeft:
return make.left.equalTo(self.view.snp_right)
}
}
}()
}
leftContainerView.snp_makeConstraints() { make in
self.leftContainerViewHorizontalOffsetConstraint = {
if self.isDragging {
var currentLeftContainerOffset = (1.0 - self.normalizedCenterViewOffset) * self.minimumLeftContainerOffset
currentLeftContainerOffset = max(currentLeftContainerOffset, self.minimumLeftContainerOffset)
currentLeftContainerOffset = min(currentLeftContainerOffset, 0.0)
return make.left.equalTo(self.view.snp_left).with.offset(currentLeftContainerOffset)
} else {
switch self.orientation {
case .Default:
return make.left.equalTo(self.minimumLeftContainerOffset)
case .PartialRevealLeft, .RevealLeft:
return make.left.equalTo(0.0)
}
}
}()
}
super.updateViewConstraints()
}
public class func requiresConstraintBasedLayout() -> Bool {
return true
}
// MARK: Status Bar
func updateStatusBarBlockerView() {
statusBarBlockerView.alpha = min(normalizedCenterViewOffset, 1.0)
setNeedsStatusBarAppearanceUpdate()
}
// MARK: Blocking View
func updateBlockingView() {
switch orientation {
case .Default:
blockingView.hidden = true
break
case .PartialRevealLeft, .RevealLeft:
blockingView.hidden = false
break
}
}
// MARK:- Child View Controllers
public func replaceCenterViewController(viewController: UIViewController) {
replaceCenterViewController({ return viewController })
}
public func replaceCenterViewController(
handler: Void -> UIViewController,
animated: Bool = false,
completion: Bool -> Void = { $0 }) {
view.userInteractionEnabled = false
let child = centerViewController
var completionHandler: (Bool -> Void) = { $0 }
let replacementHandler: Void -> Void = { [weak self] in
if let strongSelf = self {
var viewController = handler()
child?.willMoveToParentViewController(nil)
strongSelf.addChildViewController(viewController)
strongSelf.centerContainerView.insertSubview(
viewController.view,
belowSubview:child?.view ?? strongSelf.blockingView
)
viewController.view.snp_makeConstraints() { make in
make.edges.equalTo(strongSelf.centerContainerView)
}
strongSelf.centerContainerView.layoutIfNeeded()
completionHandler = { [weak self] finished in
if let strongSelf = self {
strongSelf.view.userInteractionEnabled = true
strongSelf.blockingView.hidden = true
child?.removeFromParentViewController()
viewController.didMoveToParentViewController(strongSelf)
strongSelf.centerViewController = viewController
completion(finished)
}
}
}
}
if !animated {
replacementHandler()
child?.view.removeFromSuperview()
completionHandler(true)
updateViewConstraints()
view.layoutIfNeeded()
updateStatusBarBlockerView()
} else {
view.layoutIfNeeded()
UIView.animate(
true,
duration: shortAnimationDuration,
animations: {
self.orientation = .RevealLeft
self.updateViewConstraints()
self.view.layoutIfNeeded()
}) { [weak self] finished in
if let strongSelf = self {
let minimumDelay = dispatch_time(DISPATCH_TIME_NOW, Int64(strongSelf.shortAnimationDuration * Double(NSEC_PER_SEC)))
replacementHandler()
child?.view.removeFromSuperview()
dispatch_after(minimumDelay, dispatch_get_main_queue()) { [weak self] in
if let strongSelf = self {
UIView.animate(
true,
duration: strongSelf.animationDuration,
animations: { [weak self] in
strongSelf.orientation = .Default
strongSelf.updateViewConstraints()
strongSelf.view.layoutIfNeeded()
strongSelf.updateStatusBarBlockerView()
},
completion: completionHandler
)
}
}
}
}
}
}
public func replaceLeftViewController(viewController: UIViewController) {
view.userInteractionEnabled = false
let child = leftDrawerViewController
child?.willMoveToParentViewController(nil)
child?.view.removeFromSuperview()
addChildViewController(viewController)
leftContainerView.addSubview(viewController.view)
viewController.view.snp_makeConstraints() { make in
make.edges.equalTo(UIEdgeInsetsZero)
}
child?.removeFromParentViewController()
viewController.didMoveToParentViewController(self)
leftDrawerViewController = viewController
updateViewConstraints()
view.layoutIfNeeded()
updateStatusBarBlockerView()
}
// MARK:- Anchor Drawer
public func anchorDrawer(
orientation: Orientation,
animated: Bool,
completion: Bool -> Void = { finished in }) {
let animations: Void -> Void = {
self.orientation = orientation
self.updateViewConstraints()
self.view.layoutIfNeeded()
self.updateStatusBarBlockerView()
}
let completionHandler: Bool -> Void = { [weak self] finished in
if let strongSelf = self {
strongSelf.updateBlockingView()
completion(finished)
}
}
UIView.animate(
animated,
duration: animationDuration,
animations: animations,
completion: completionHandler
)
}
// MARK:- Action Handlers
public func handlePan(sender: UIPanGestureRecognizer) {
let location = sender.locationInView(view)
switch sender.state {
case UIGestureRecognizerState.Began:
currentPanDelta = CGPointZero
currentTouchPoint = location
isDragging = true
break
case UIGestureRecognizerState.Changed:
currentPanDelta = CGPointMake(
currentTouchPoint!.x - location.x,
currentTouchPoint!.y - location.y
)
currentTouchPoint = location
updateViewConstraints()
view.layoutIfNeeded()
break
case UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled:
isDragging = false
let thresholdSpeed = CGFloat(100.0)
let currentVelocity = sender.velocityInView(view)
let orientation: Orientation
if fabs(currentVelocity.x) > thresholdSpeed {
if currentVelocity.x > 0.0 {
orientation = .PartialRevealLeft
} else {
orientation = .Default
}
} else {
if currentHorizontalOffset > leftDrawerPartialRevealHorizontalOffset {
orientation = .PartialRevealLeft
} else {
orientation = .Default
}
}
anchorDrawer(orientation, animated: true)
break
case UIGestureRecognizerState.Failed, UIGestureRecognizerState.Possible:
break
}
updateStatusBarBlockerView()
}
public func handleTap(sender: UITapGestureRecognizer) {
anchorDrawer(.Default, animated: true)
}
// MARK:- Private Properties
private lazy var panGestureRecognizer: UIPanGestureRecognizer = {
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
panGestureRecognizer.delegate = self
return panGestureRecognizer
}()
private lazy var blockingView: UIView = {
let blockingView = UIView(frame: CGRectZero)
blockingView.backgroundColor = UIColor.clearColor()
blockingView.hidden = true
blockingView.addGestureRecognizer({
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTap:")
tapGestureRecognizer.numberOfTapsRequired = 1
tapGestureRecognizer.numberOfTouchesRequired = 1
tapGestureRecognizer.delegate = self
tapGestureRecognizer.requireGestureRecognizerToFail(self.panGestureRecognizer)
return tapGestureRecognizer
}())
return blockingView
}()
private lazy var containerViews: [ UIView ] = {
var containerViews = [ UIView ]()
for i in 0..<ViewControllerIndex.count {
let view = UIView(frame: CGRectZero)
view.backgroundColor = UIColor.blackColor()
view.opaque = true
let viewControllerIndex = ViewControllerIndex(rawValue: i)!
switch viewControllerIndex {
case .Left:
break
case .Center:
view.addGestureRecognizer(self.panGestureRecognizer)
view.addSubview(self.blockingView)
break
}
containerViews.append(view)
}
return containerViews
}()
private lazy var leftContainerView: UIView = {
return self.containerViews[ViewControllerIndex.Left.rawValue]
}()
private var centerContainerView: UIView {
return self.containerViews[ViewControllerIndex.Center.rawValue]
}
public func gestureRecognizer(
gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer.self) {
// Disable if vertical scrolling is desired.
let velocity = (otherGestureRecognizer as! UIPanGestureRecognizer).velocityInView(view)
if (fabs(velocity.y) > fabs(velocity.x)) {
return false
}
}
// If view is a horizontal scroller, don't allow panning unless at the far left of the scroll view.
if let view = otherGestureRecognizer.view where view.isKindOfClass(UIScrollView.self) {
let scrollView = otherGestureRecognizer.view as! UIScrollView
if (scrollView.contentOffset.x >= 1) {
return false
}
}
return true
}
// MARK:- Panning Properties
private var isDragging = false
private var currentTouchPoint: CGPoint?
private var currentPanDelta: CGPoint?
private var centerContainerViewHorizontalOffsetConstraint: Constraint?
private var leftContainerViewHorizontalOffsetConstraint: Constraint?
private var currentHorizontalOffset: CGFloat {
return CGRectGetMinX(centerContainerView.frame)
}
private var normalizedCenterViewOffset: CGFloat {
var normalizedCenterViewOffset = self.currentHorizontalOffset
normalizedCenterViewOffset /= (view.frame.size.width - self.leftDrawerPartialRevealHorizontalOffset)
return normalizedCenterViewOffset
}
}
| apache-2.0 |
qwang216/ChatApp | ChatApp/GlobalMethods.swift | 1 | 431 | //
// GlobalMethods.swift
// ChatApp
//
// Created by Jason Wang on 8/14/16.
// Copyright © 2016 Jason Wang. All rights reserved.
//
import UIKit
func errorAlertTitle(title: String, message: String) -> UIAlertController {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let ok = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
alert.addAction(ok)
return alert
} | mit |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Core/Data/EditProfileData.swift | 1 | 1982 | //
// EditProfileData.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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
@objc
open class EditProfileData: NSObject {
open var username: String?
open var displayName: String?
open var name: String?
open var email: String?
open var birthYear: Int? // >1900
open var birthMonth: Int?
open var ageDisplayType: String? //Change to enum
open var gender: String? //Change to enum
open var uiLocale: String? //Change to enum
open var preApproveComments: Bool?
open var whatDoYouTeach: String?
open var interests: String?
open var countryCode: String?
open var receiveNotifications: Bool?
open var receiveNewswletter: Bool?
open var avatarCreationIdentifier: String?
open var interestsList: Array<String>?
open var personalizedAvatarSourceUrl: String?
}
| mit |
ben-ng/swift | validation-test/compiler_crashers_fixed/01092-getselftypeforcontainer.swift | 1 | 436 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
extension
l()
protocol l : f { func f
| apache-2.0 |
IndisputableLabs/Swifthereum | Examples/MacOS/MacEtherScan/MacEtherScan/AppDelegate.swift | 1 | 516 | //
// AppDelegate.swift
// MacEtherScan
//
// Created by Ronald Mannak on 10/18/17.
// Copyright © 2017 Indisputable Labs. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| mit |
mrdepth/Neocom | Legacy/Neocom/Neocom/NCLoyaltyStoreOffersViewController.swift | 2 | 6329 | //
// NCLoyaltyStoreOffersViewController.swift
// Neocom
//
// Created by Artem Shimanski on 12.10.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import EVEAPI
import CoreData
import Futures
class NCLoyaltyStoreCategoryRow: TreeRow {
let categoryID: Int
lazy var category: NCDBInvCategory? = {
return NCDatabase.sharedDatabase?.invCategories[categoryID]
}()
init(categoryID: Int, route: Route) {
self.categoryID = categoryID
super.init(prototype: Prototype.NCDefaultTableViewCell.compact, route: route)
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCDefaultTableViewCell else {return}
cell.titleLabel?.text = category?.categoryName
cell.iconView?.image = category?.icon?.image?.image ?? NCDBEveIcon.defaultCategory.image?.image
cell.accessoryType = .disclosureIndicator
}
}
class NCLoyaltyStoreGroupRow: TreeRow {
let groupID: Int
lazy var group: NCDBInvGroup? = {
return NCDatabase.sharedDatabase?.invGroups[groupID]
}()
init(groupID: Int, route: Route) {
self.groupID = groupID
super.init(prototype: Prototype.NCDefaultTableViewCell.compact, route: route)
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCDefaultTableViewCell else {return}
cell.titleLabel?.text = group?.groupName
cell.iconView?.image = group?.icon?.image?.image ?? NCDBEveIcon.defaultGroup.image?.image
cell.accessoryType = .disclosureIndicator
}
}
class NCLoyaltyStoreOfferRow: TreeRow {
let offer: ESI.Loyalty.Offer
lazy var subtitle: String = {
var components = [String]()
if offer.lpCost > 0 {
components.append(NCUnitFormatter.localizedString(from: offer.lpCost, unit: .custom(NSLocalizedString("LP", comment: ""), false), style: .full))
}
if offer.iskCost > 0 {
components.append(NCUnitFormatter.localizedString(from: offer.lpCost, unit: .isk, style: .full))
}
if !offer.requiredItems.isEmpty {
// offer.requiredItems.flat
components.append(String(format: NSLocalizedString("%d items", comment: ""), offer.requiredItems.count))
}
return components.joined(separator: ", ")
}()
lazy var type: NCDBInvType? = {
return NCDatabase.sharedDatabase?.invTypes[self.offer.typeID]
}()
init(offer: ESI.Loyalty.Offer) {
self.offer = offer
super.init(prototype: Prototype.NCDefaultTableViewCell.default, route: Router.Database.TypeInfo(offer.typeID))
}
override func configure(cell: UITableViewCell) {
super.configure(cell: cell)
guard let cell = cell as? NCDefaultTableViewCell else {return}
cell.titleLabel?.text = type?.typeName
cell.iconView?.image = type?.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image
cell.subtitleLabel?.text = subtitle
cell.accessoryType = .disclosureIndicator
}
}
class NCLoyaltyStoreOffersViewController: NCTreeViewController {
var loyaltyPoints: ESI.Loyalty.Point?
enum Filter {
case category(Int)
case group(Int)
}
var filter: Filter?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register([Prototype.NCDefaultTableViewCell.default,
Prototype.NCDefaultTableViewCell.compact,
Prototype.NCHeaderTableViewCell.default])
let label = NCNavigationItemTitleLabel(frame: CGRect(origin: .zero, size: .zero))
let title: String = {
switch filter {
case let .category(categoryID)?:
return NCDatabase.sharedDatabase?.invCategories[categoryID]?.categoryName
case let .group(groupID)?:
return NCDatabase.sharedDatabase?.invGroups[groupID]?.groupName
default:
return nil
}
}() ?? NSLocalizedString("Offers", comment: "")
label.set(title: title, subtitle: NCUnitFormatter.localizedString(from: loyaltyPoints?.loyaltyPoints ?? 0, unit: .custom("LP", false), style: .full))
navigationItem.titleView = label
}
override func load(cachePolicy: URLRequest.CachePolicy) -> Future<[NCCacheRecord]> {
guard let loyaltyPoints = loyaltyPoints, filter == nil && offers == nil else {
return .init([])
}
return dataManager.loyaltyStoreOffers(corporationID: Int64(loyaltyPoints.corporationID)).then(on: .main) { result -> [NCCacheRecord] in
self.offers = result
return [result.cacheRecord(in: NCCache.sharedCache!.viewContext)]
}
}
override func content() -> Future<TreeNode?> {
let loyaltyPoints = self.loyaltyPoints
let offers = self.offers
return DispatchQueue.global(qos: .utility).async { () -> TreeNode? in
guard let loyaltyPoints = loyaltyPoints, let offers = offers, let value = offers.value else {throw NCTreeViewControllerError.noResult}
return try NCDatabase.sharedDatabase!.performTaskAndWait { (managedObjectContext) in
let invTypes = NCDBInvType.invTypes(managedObjectContext: managedObjectContext)
// var map: [Int: [NCLoyaltyStoreOfferRow]] = [:]
let sections: [TreeNode]
switch self.filter {
case let .category(categoryID)?:
let categoryID = Int32(categoryID)
let groups = Set(value.compactMap {invTypes[$0.typeID]?.group}).filter {$0.category?.categoryID == categoryID}
sections = groups.sorted {($0.groupName ?? "") < ($1.groupName ?? "")}.map {NCLoyaltyStoreGroupRow(groupID: Int($0.groupID), route: Router.Character.LoyaltyStoreOffers(loyaltyPoints: loyaltyPoints, filter: .group(Int($0.groupID)), offers: offers))}
case let .group(groupID)?:
let groupID = Int32(groupID)
let types = value.compactMap { i -> (NCDBInvType, ESI.Loyalty.Offer)? in
guard let type = invTypes[i.typeID], type.group?.groupID == groupID else {return nil}
return (type, i)
}
sections = types.sorted {($0.0.typeName ?? "") < ($1.0.typeName ?? "")}.map {NCLoyaltyStoreOfferRow(offer: $0.1)}
default:
let categories = Set(value.compactMap {invTypes[$0.typeID]?.group?.category})
sections = categories.sorted {($0.categoryName ?? "") < ($1.categoryName ?? "")}.map {NCLoyaltyStoreCategoryRow(categoryID: Int($0.categoryID), route: Router.Character.LoyaltyStoreOffers(loyaltyPoints: loyaltyPoints, filter: .category(Int($0.categoryID)), offers: offers))}
}
guard !sections.isEmpty else {throw NCTreeViewControllerError.noResult}
return RootNode(sections)
}
}
}
//MARK: - NCRefreshable
var offers: CachedValue<[ESI.Loyalty.Offer]>?
}
| lgpl-2.1 |
frootloops/swift | test/Sema/diag_get_vs_set_subscripts.swift | 4 | 660 | // RUN: %target-typecheck-verify-swift
enum Key: Int {
case aKey
case anotherKey // expected-note {{did you mean 'anotherKey'?}}
}
class sr6175 {
var dict: [Key: String] = [:]
func what() -> Void {
dict[.notAKey] = "something" // expected-error {{type 'Key' has no member 'notAKey'}}
}
subscript(i: Int) -> Int {
return i*i
}
subscript(j: Double) -> Double {
get { return j*j }
set {}
}
}
let s = sr6175()
let one: Int = 1
// Should choose the settable subscript to find a problem with, not the get-only subscript
s[one] = 2.5 // expected-error {{cannot convert value of type 'Int' to expected argument type 'Double'}}
| apache-2.0 |
adrfer/swift | test/1_stdlib/Dispatch.swift | 4 | 2107 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Dispatch
import Foundation
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
defer { runAllTests() }
var DispatchAPI = TestSuite("DispatchAPI")
DispatchAPI.test("constants") {
expectEqual(2147483648, DISPATCH_PROC_EXIT)
expectEqual("<>", dispatch_data_empty.description)
// This is a lousy test, but really we just care that
// DISPATCH_QUEUE_CONCURRENT comes through at all.
_ = DISPATCH_QUEUE_CONCURRENT as AnyObject
_ = DISPATCH_QUEUE_CONCURRENT.description
}
DispatchAPI.test("OS_OBJECT support") {
let mainQueue = dispatch_get_main_queue() as AnyObject
expectTrue(mainQueue is dispatch_queue_t)
// This should not be optimized out, and should succeed.
expectNotEmpty(mainQueue as? dispatch_queue_t)
}
DispatchAPI.test("dispatch_block_t conversions") {
var counter = 0
let closure = { () -> Void in
counter += 1
}
let block = closure as dispatch_block_t
block()
expectEqual(1, counter)
let closureAgain = block as () -> Void
closureAgain()
expectEqual(2, counter)
}
if #available(OSX 10.10, iOS 8.0, *) {
DispatchAPI.test("dispatch_block_t identity") {
let block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) {
_ = 1
}
dispatch_async(dispatch_get_main_queue(), block)
// This will trap if the block's pointer identity is not preserved.
dispatch_block_cancel(block)
}
DispatchAPI.test("dispatch_block_t conversions with dispatch_block_create") {
var counter = 0
let block = dispatch_block_create(dispatch_block_flags_t(0)) {
counter += 1
}
block()
expectEqual(1, counter)
let closure = block as () -> Void
closure()
expectEqual(2, counter)
let blockAgain = closure as dispatch_block_t
blockAgain()
expectEqual(3, counter)
}
}
| apache-2.0 |
GYLibrary/GPRS | OznerGPRS/View/WaterPurifiCell.swift | 1 | 1429 | //
// WaterPurifiCell.swift
// OznerGPRS
//
// Created by ZGY on 2017/9/22.
// Copyright © 2017年 macpro. All rights reserved.
//
// Author: Airfight
// My GitHub: https://github.com/airfight
// My Blog: http://airfight.github.io/
// My Jane book: http://www.jianshu.com/users/17d6a01e3361
// Current Time: 2017/9/22 下午1:24
// GiantForJade: Efforts to do my best
// Real developers ship.
import UIKit
class WaterPurifiCell: UITableViewCell {
@IBOutlet weak var powerBtn: UIButton!
@IBOutlet weak var hotBnt: UIButton!
@IBOutlet weak var coldBtn: UIButton!
@IBAction func btnAction(_ sender: UIButton) {
appDelegate.window?.noticeOnlyText("此机型暂无此功能")
switch sender.tag {
//开关机
case 666:
break
//hot
case 777:
break
//cold
case 888:
break
default:
break
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
cplaverty/KeitaiWaniKani | AlliCrab/ViewControllers/WebViewController.swift | 1 | 20275 | //
// WebViewController.swift
// AlliCrab
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
import OnePasswordExtension
import os
import UIKit
import WaniKaniKit
import WebKit
protocol WebViewControllerDelegate: class {
func webViewControllerDidFinish(_ controller: WebViewController)
}
class WebViewController: UIViewController {
class func wrapped(url: URL, configBlock: ((WebViewController) -> Void)? = nil) -> UINavigationController {
let webViewController = self.init(url: url)
configBlock?(webViewController)
let nc = UINavigationController(rootViewController: webViewController)
nc.hidesBarsOnSwipe = true
nc.hidesBarsWhenVerticallyCompact = true
return nc
}
// MARK: - Properties
weak var delegate: WebViewControllerDelegate?
private(set) var webView: WKWebView!
private var url: URL?
private var webViewConfiguration: WKWebViewConfiguration?
private var shouldIncludeDoneButton = false
private var keyValueObservers: [NSKeyValueObservation]?
private lazy var backButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "ArrowLeft"), style: .plain, target: self, action: #selector(backButtonTouched(_:forEvent:)))
private lazy var forwardButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "ArrowRight"), style: .plain, target: self, action: #selector(forwardButtonTouched(_:forEvent:)))
private lazy var shareButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(share(_:)))
private lazy var openInSafariButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "OpenInSafari"), style: .plain, target: self, action: #selector(openInSafari(_:)))
private lazy var doneButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(done(_:)))
private lazy var statusBarView: UIView = {
let view = UIBottomBorderedView(frame: UIApplication.shared.statusBarFrame, color: .lightGray, width: 0.5)
view.autoresizingMask = .flexibleWidth
view.backgroundColor = .globalBarTintColor
return view
}()
private lazy var defaultWebViewConfiguration: WKWebViewConfiguration = {
let config = WKWebViewConfiguration()
registerMessageHandlers(config.userContentController)
config.applicationNameForUserAgent = "Mobile AlliCrab"
let delegate = UIApplication.shared.delegate as! AppDelegate
config.ignoresViewportScaleLimits = true
config.mediaTypesRequiringUserActionForPlayback = [.video]
config.processPool = delegate.webKitProcessPool
return config
}()
// MARK: - Initialisers
required init(url: URL) {
super.init(nibName: nil, bundle: nil)
self.url = url
}
required init(configuration: WKWebViewConfiguration) {
super.init(nibName: nil, bundle: nil)
self.webViewConfiguration = configuration
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
// We nil these references out to unregister KVO on WKWebView
self.navigationItem.titleView = nil
keyValueObservers = nil
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
// MARK: - Actions
@objc func backButtonTouched(_ sender: UIBarButtonItem, forEvent event: UIEvent) {
guard let touch = event.allTouches?.first else { return }
switch touch.tapCount {
case 0: // Long press
self.showBackForwardList(webView.backForwardList.backList, sender: sender)
case 1: // Tap
self.webView.goBack()
default: break
}
}
@objc func forwardButtonTouched(_ sender: UIBarButtonItem, forEvent event: UIEvent) {
guard let touch = event.allTouches?.first else { return }
switch touch.tapCount {
case 0: // Long press
self.showBackForwardList(webView.backForwardList.forwardList, sender: sender)
case 1: // Tap
self.webView.goForward()
default: break
}
}
@objc func share(_ sender: UIBarButtonItem) {
guard let absoluteURL = webView.url?.absoluteURL else {
return
}
var activityItems: [AnyObject] = [absoluteURL as NSURL]
activityItems.reserveCapacity(2)
let onePasswordExtension = OnePasswordExtension.shared()
if onePasswordExtension.isAppExtensionAvailable() {
onePasswordExtension.createExtensionItem(forWebView: webView!) { extensionItem, error -> Void in
if let error = error {
os_log("Failed to create 1Password extension item: %@", type: .error, error as NSError)
} else if let extensionItem = extensionItem {
activityItems.append(extensionItem)
}
self.presentActivityViewController(activityItems, title: self.webView.title, sender: sender) {
activityType, completed, returnedItems, activityError in
if let error = activityError {
os_log("Activity failed: %@", type: .error, error as NSError)
DispatchQueue.main.async {
self.showAlert(title: "Activity failed", message: error.localizedDescription)
}
return
}
guard completed else {
return
}
if onePasswordExtension.isOnePasswordExtensionActivityType(activityType?.rawValue) {
onePasswordExtension.fillReturnedItems(returnedItems, intoWebView: self.webView!) { success, error in
if !success {
let errorDescription = error?.localizedDescription ?? "(No error details)"
os_log("Failed to fill password from password manager: %@", type: .error, errorDescription)
DispatchQueue.main.async {
self.showAlert(title: "Password fill failed", message: errorDescription)
}
}
}
}
}
}
} else {
presentActivityViewController(activityItems, title: webView.title, sender: sender)
}
}
@objc func openInSafari(_ sender: UIBarButtonItem) {
guard let URL = webView.url else {
return
}
UIApplication.shared.open(URL)
}
@objc func done(_ sender: UIBarButtonItem) {
finish()
}
func showBackForwardList(_ backForwardList: [WKBackForwardListItem], sender: UIBarButtonItem) {
let vc = WebViewBackForwardListTableViewController()
vc.backForwardList = backForwardList
vc.delegate = self
vc.modalPresentationStyle = .popover
if let popover = vc.popoverPresentationController {
popover.delegate = vc
popover.permittedArrowDirections = [.up, .down]
popover.barButtonItem = sender
}
present(vc, animated: true, completion: nil)
}
func presentActivityViewController(_ activityItems: [AnyObject], title: String?, sender: UIBarButtonItem, completionHandler: UIActivityViewController.CompletionWithItemsHandler? = nil) {
let avc = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
avc.popoverPresentationController?.barButtonItem = sender;
avc.completionWithItemsHandler = completionHandler
if let title = title {
avc.setValue(title, forKey: "subject")
}
navigationController?.present(avc, animated: true, completion: nil)
}
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
webView = makeWebView()
keyValueObservers = registerObservers(webView)
self.view.addSubview(webView)
self.view.addSubview(statusBarView)
NSLayoutConstraint.activate([
webView.topAnchor.constraint(equalTo: view.topAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
statusBarView.topAnchor.constraint(equalTo: view.topAnchor),
statusBarView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
statusBarView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
if let nc = self.navigationController {
shouldIncludeDoneButton = nc.viewControllers[0] == self
let addressBarView = WebAddressBarView(frame: nc.navigationBar.bounds, forWebView: webView)
self.navigationItem.titleView = addressBarView
}
configureToolbars(for: self.traitCollection)
if let url = self.url {
let request = URLRequest(url: url)
self.webView.load(request)
}
}
private func makeWebView() -> WKWebView {
let webView = WKWebView(frame: .zero, configuration: webViewConfiguration ?? defaultWebViewConfiguration)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.navigationDelegate = self
webView.uiDelegate = self
webView.allowsBackForwardNavigationGestures = true
webView.allowsLinkPreview = true
webView.keyboardDisplayDoesNotRequireUserAction()
return webView
}
private func registerObservers(_ webView: WKWebView) -> [NSKeyValueObservation] {
let keyValueObservers = [
webView.observe(\.canGoBack, options: [.initial]) { [weak self] webView, _ in
self?.backButton.isEnabled = webView.canGoBack
},
webView.observe(\.canGoForward, options: [.initial]) { [weak self] webView, _ in
self?.forwardButton.isEnabled = webView.canGoForward
},
webView.observe(\.isLoading, options: [.initial]) { [weak self] webView, _ in
UIApplication.shared.isNetworkActivityIndicatorVisible = webView.isLoading
self?.shareButton.isEnabled = !webView.isLoading && webView.url != nil
},
webView.observe(\.url, options: [.initial]) { [weak self] webView, _ in
let hasURL = webView.url != nil
self?.shareButton.isEnabled = !webView.isLoading && hasURL
self?.openInSafariButton.isEnabled = hasURL
}
]
return keyValueObservers
}
// MARK: - Size class transitions
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
if newCollection.horizontalSizeClass != traitCollection.horizontalSizeClass || newCollection.verticalSizeClass != traitCollection.verticalSizeClass {
configureToolbars(for: newCollection)
}
}
/// Sets the navigation bar and toolbar items based on the given UITraitCollection
func configureToolbars(for traitCollection: UITraitCollection) {
statusBarView.isHidden = traitCollection.verticalSizeClass == .compact
if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
addToolbarItemsForCompactWidthRegularHeight()
} else {
addToolbarItemsForAllOtherTraitCollections()
}
}
/// For phone in portrait
func addToolbarItemsForCompactWidthRegularHeight() {
self.navigationController?.setToolbarHidden(false, animated: true)
navigationItem.leftItemsSupplementBackButton = !shouldIncludeDoneButton
navigationItem.leftBarButtonItems = customLeftBarButtonItems
navigationItem.rightBarButtonItems = customRightBarButtonItems
let flexibleSpace = { UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) }
setToolbarItems([backButton, flexibleSpace(), forwardButton, flexibleSpace(), shareButton, flexibleSpace(), openInSafariButton], animated: true)
}
/// For phone in landscape and pad in any orientation
func addToolbarItemsForAllOtherTraitCollections() {
self.navigationController?.setToolbarHidden(true, animated: true)
setToolbarItems(nil, animated: true)
navigationItem.leftItemsSupplementBackButton = !shouldIncludeDoneButton
navigationItem.leftBarButtonItems = customLeftBarButtonItems + [backButton, forwardButton]
navigationItem.rightBarButtonItems = customRightBarButtonItems + [openInSafariButton, shareButton]
}
var customLeftBarButtonItems: [UIBarButtonItem] {
var buttons: [UIBarButtonItem] = []
buttons.reserveCapacity(1)
if shouldIncludeDoneButton {
buttons.append(doneButton)
}
return buttons
}
var customRightBarButtonItems: [UIBarButtonItem] {
var buttons: [UIBarButtonItem] = []
buttons.reserveCapacity(1)
return buttons
}
// MARK: - Implementation
func showBrowserInterface(_ shouldShowBrowserInterface: Bool, animated: Bool) {
guard let nc = self.navigationController else { return }
nc.setNavigationBarHidden(!shouldShowBrowserInterface, animated: animated)
if self.toolbarItems?.isEmpty == false {
nc.setToolbarHidden(!shouldShowBrowserInterface, animated: animated)
}
}
func finish() {
unregisterMessageHandlers(webView.configuration.userContentController)
delegate?.webViewControllerDidFinish(self)
dismiss(animated: true, completion: nil)
}
func registerMessageHandlers(_ userContentController: WKUserContentController) {
}
func unregisterMessageHandlers(_ userContentController: WKUserContentController) {
}
}
// MARK: - WebViewBackForwardListTableViewControllerDelegate
extension WebViewController: WebViewBackForwardListTableViewControllerDelegate {
func webViewBackForwardListTableViewController(_ controller: WebViewBackForwardListTableViewController, didSelectBackForwardListItem item: WKBackForwardListItem) {
controller.dismiss(animated: true, completion: nil)
self.webView.go(to: item)
}
}
// MARK: - WKNavigationDelegate
extension WebViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
self.navigationController?.setNavigationBarHidden(false, animated: true)
if self.toolbarItems?.isEmpty == false {
self.navigationController?.setToolbarHidden(false, animated: true)
}
injectUserScripts(to: webView)
}
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
injectUserScripts(to: webView)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
os_log("Navigation failed: %@", type: .error, error as NSError)
showErrorDialog(error)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
os_log("Navigation failed: %@", type: .error, error as NSError)
showErrorDialog(error)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let url = webView.url else { return }
switch url {
case WaniKaniURL.lessonSession, WaniKaniURL.reviewSession:
showBrowserInterface(false, animated: true)
default: break
}
}
private func injectUserScripts(to webView: WKWebView) {
webView.configuration.userContentController.removeAllUserScripts()
if let url = webView.url {
_ = injectUserScripts(for: url)
}
}
private func showErrorDialog(_ error: Error) {
switch error {
case let urlError as URLError where urlError.code == .cancelled:
break
case let nsError as NSError where nsError.domain == "WebKitErrorDomain" && nsError.code == 102:
break
default:
showAlert(title: "Failed to load page", message: error.localizedDescription)
}
}
}
// MARK: - WKScriptMessageHandler
extension WebViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
}
}
// MARK: - WKUIDelegate
extension WebViewController: WKUIDelegate {
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
let newVC = type(of: self).init(configuration: configuration)
newVC.url = navigationAction.request.url
self.navigationController?.pushViewController(newVC, animated: true)
return newVC.webView
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
DispatchQueue.main.async {
let host = frame.request.url?.host ?? "web page"
let title = "From \(host):"
os_log("Displaying alert with title %@ and message %@", type: .debug, title, message)
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler() })
self.present(alert, animated: true, completion: nil)
}
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
DispatchQueue.main.async {
let host = frame.request.url?.host ?? "web page"
let title = "From \(host):"
os_log("Displaying alert with title %@ and message %@", type: .debug, title, message)
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler(true) })
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in completionHandler(false) })
self.present(alert, animated: true, completion: nil)
}
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
DispatchQueue.main.async {
let host = frame.request.url?.host ?? "web page"
let title = "From \(host):"
os_log("Displaying input panel with title %@ and message %@", type: .debug, title, prompt)
let alert = UIAlertController(title: title, message: prompt, preferredStyle: .alert)
alert.addTextField { $0.text = defaultText }
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler(alert.textFields?.first?.text) })
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in completionHandler(nil) })
self.present(alert, animated: true, completion: nil)
}
}
}
// MARK: - WebViewUserScriptSupport
extension WebViewController: WebViewUserScriptSupport {
}
| mit |
iosphere/ISHLogDNA | SampleAppSwift/ViewController.swift | 1 | 210 | //
// ViewController.swift
// SampleAppSwift
//
// Created by Felix Lamouroux on 14.06.17.
// Copyright © 2017 iosphere. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
}
| mit |
qinting513/SwiftNote | PullToRefreshKit-master 自定义刷新控件/PullToRefreshKit/CurveMaskTableViewController.swift | 1 | 823 | //
// CurveMaskTableViewController.swift
// PullToRefreshKit
//
// Created by huangwenchen on 16/8/4.
// Copyright © 2016年 Leo. All rights reserved.
//
import Foundation
import UIKit
class CurveMaskTableViewController:BaseTableViewController{
override func viewDidLoad() {
super.viewDidLoad()
//Setup
let curveHeader = CurveRefreshHeader(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 0))
_ = self.tableView.setUpHeaderRefresh(curveHeader) { [weak self] in
delay(1.5, closure: {
self?.models = (self?.models.map({_ in random100()}))!
self?.tableView.reloadData()
self?.tableView.endHeaderRefreshing(delay: 0.5)
})
}
// self.tableView.beginHeaderRefreshing()
}
}
| apache-2.0 |
hughhopkins/PW-OSX | Pods/CryptoSwift/Sources/CryptoSwift/PKCS7.swift | 4 | 1498 | //
// PKCS7.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 28/02/15.
// Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved.
//
// PKCS is a group of public-key cryptography standards devised
// and published by RSA Security Inc, starting in the early 1990s.
//
public struct PKCS7: Padding {
public enum Error: ErrorType {
case InvalidPaddingValue
}
public init() {
}
public func add(bytes: [UInt8] , blockSize:Int) -> [UInt8] {
let padding = UInt8(blockSize - (bytes.count % blockSize))
var withPadding = bytes
if (padding == 0) {
// If the original data is a multiple of N bytes, then an extra block of bytes with value N is added.
for _ in 0..<blockSize {
withPadding.appendContentsOf([UInt8(blockSize)])
}
} else {
// The value of each added byte is the number of bytes that are added
for _ in 0..<padding {
withPadding.appendContentsOf([UInt8(padding)])
}
}
return withPadding
}
public func remove(bytes: [UInt8], blockSize:Int?) -> [UInt8] {
let lastByte = bytes.last!
let padding = Int(lastByte) // last byte
let finalLength = bytes.count - padding
if finalLength < 0 {
return bytes
}
if padding >= 1 {
return Array(bytes[0..<finalLength])
}
return bytes
}
} | mit |
khizkhiz/swift | validation-test/compiler_crashers_fixed/27780-swift-conformancelookuptable-lookupconformances.swift | 4 | 260 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
{struct h
}
enum b{
enum e:A
class A<T:T.a
| apache-2.0 |
inkyfox/SwiftySQL | Sources/SQLFunc.swift | 3 | 2010 | //
// SQLFunc.swift
// SwiftySQL
//
// Created by Yongha Yoo (inkyfox) on 2016. 10. 22..
// Copyright © 2016년 Gen X Hippies Company. All rights reserved.
//
import Foundation
public struct SQLFunc: SQLValueType, SQLConditionType, SQLOrderType, SQLAliasable {
let name: String
let args: [SQLExprType]
public init(_ name: String, args: [SQLValueType] = []) {
self.name = name
self.args = args
}
public init(_ name: String, args: SQLAsteriskMark) {
self.name = name
self.args = [args]
}
public init(_ name: String, args: SQLValueType...) {
self.name = name
self.args = args
}
}
extension SQL {
public static func count(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("COUNT", args: [arg])
}
public static func count(_ args: SQLAsteriskMark) -> SQLFunc {
return SQLFunc("COUNT", args: args)
}
}
extension SQL {
public static func avg(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("AVG", args: [arg])
}
public static func max(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("MAX", args: [arg])
}
public static func min(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("MIN", args: [arg])
}
public static func sum(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("SUM", args: [arg])
}
public static func total(_ args: SQLValueType) -> SQLFunc {
return SQLFunc("TOTAL", args: [args])
}
public static func abs(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("ABS", args: [arg])
}
public static func length(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("LENGTH", args: [arg])
}
public static func lower(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("LOWER", args: [arg])
}
public static func upper(_ arg: SQLValueType) -> SQLFunc {
return SQLFunc("UPPER", args: [arg])
}
}
| mit |
zhangmufeng/ZMFDY | ZMFDouYu/ZMFDouYu/Classes/Main/MainTabBarController.swift | 1 | 1260 | //
// MainTabBarController.swift
// ZMFDouYu
//
// Created by Mufeng on 2016/12/1.
// Copyright © 2016年 ZMF. All rights reserved.
//
import UIKit
class MainTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
addChildVC(storyName: "Home")
addChildVC(storyName: "Live")
addChildVC(storyName: "Follow")
addChildVC(storyName: "Profile")
}
private func addChildVC(storyName: String) {
// 1.通过SB获取控制器
let childVC = UIStoryboard(name: storyName, bundle: nil).instantiateInitialViewController()!
// 2.将childVC添加作为根控制器
addChildViewController(childVC)
}
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.
}
*/
}
| mit |
TylerKuster/MeetAnotherTeam | MeetAnotherTeam/MeetAnotherTeamTests/MeetAnotherTeamTests.swift | 1 | 1003 | //
// MeetAnotherTeamTests.swift
// MeetAnotherTeamTests
//
// Created by Tyler Kuster on 10/5/17.
// Copyright © 2017 12 Triangles. All rights reserved.
//
import XCTest
@testable import MeetAnotherTeam
class MeetAnotherTeamTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
jkolb/Shkadov | Shkadov/renderer/GPUBuffer.swift | 1 | 1845 | /*
The MIT License (MIT)
Copyright (c) 2016 Justin Kolb
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 Lilliput
public protocol GPUBufferOwner : class {
func createBuffer(count: Int, storageMode: StorageMode) -> GPUBufferHandle
func createBuffer(bytes: UnsafeRawPointer, count: Int, storageMode: StorageMode) -> GPUBufferHandle
func createBuffer(bytesNoCopy: UnsafeMutableRawPointer, count: Int, storageMode: StorageMode) -> GPUBufferHandle
func borrowBuffer(handle: GPUBufferHandle) -> GPUBuffer
func destroyBuffer(handle: GPUBufferHandle)
}
public struct GPUBufferHandle : Handle {
public let key: UInt16
public init() { self.init(key: 0) }
public init(key: UInt16) {
self.key = key
}
}
public protocol GPUBuffer : UnsafeBuffer {
func wasCPUModified(range: Range<Int>)
}
| mit |
Incipia/Conduction | Example/Pods/Bindable/Bindable/Classes/KeyValue/KVCompliance.swift | 2 | 1212 | //
// IncKVCompliance.swift
// GigSalad
//
// Created by Leif Meyer on 2/24/17.
// Copyright © 2017 Incipia. All rights reserved.
//
import Foundation
public protocol IncKVKeyType: Hashable {
var rawValue: String { get }
init?(rawValue: String)
func kvTypeError(value: Any?) -> IncKVError
static var all: [Self] { get }
}
public extension IncKVKeyType {
static var all: [Self] {
var all: [Self] = []
for element in IncIterateEnum(Self.self) {
all.append(element)
}
return all
}
func kvTypeError(value: Any?) -> IncKVError {
let valueString: String = {
guard let value = value else { return "nil" }
return "\(type(of: value))"
}()
return IncKVError.valueType(key: "\(type(of: self)).\(self.rawValue)", value: valueString)
}
}
public enum IncKVError: Error {
case valueType(key: String, value: String)
}
public protocol IncKVCompliance: KVStringCompliance {
associatedtype Key: IncKVKeyType
func value(for key: Key) -> Any?
mutating func set(value: Any?, for key: Key) throws
}
public protocol IncKVComplianceClass: class, IncKVCompliance {
func set(value: Any?, for key: Key) throws
}
| mit |
czerwinskilukasz1/QuickSwiftStructures | QuickSwiftStructures/QuickNode.swift | 1 | 366 | //
// QNode.swift
// QuickSwiftStructures
//
// Created by Lukasz Czerwinski on 11/5/15.
// Copyright © 2015 Lukasz Czerwinski <[email protected]>. All rights reserved.
// Distributed under MIT License
import Foundation
class QuickNode<T> {
var key: T
var next: QuickNode? = nil
init(key: T) {
self.key = key
}
}
| mit |
TheBudgeteers/CartTrackr | CartTrackr/Carthage/Checkouts/SwiftyCam/Source/PreviewView.swift | 1 | 1914 | /*Copyright (c) 2016, Andrew Walz.
Redistribution and use in source and binary forms, with or without modification,are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import UIKit
import AVFoundation
class PreviewView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.black
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var videoPreviewLayer: AVCaptureVideoPreviewLayer {
return layer as! AVCaptureVideoPreviewLayer
}
var session: AVCaptureSession? {
get {
return videoPreviewLayer.session
}
set {
videoPreviewLayer.session = newValue
}
}
// MARK: UIView
override class var layerClass : AnyClass {
return AVCaptureVideoPreviewLayer.self
}
}
| mit |
hstdt/GodEye | Carthage/Checkouts/LeakEye/Example/LeakEye/SecondViewController.swift | 1 | 1155 | //
// SecondViewController.swift
// LeakEye
//
// Created by zixun on 16/12/26.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
class LeakTest: NSObject {
var block: (() -> ())!
init(block: @escaping () -> () ) {
super.init()
self.block = block
}
}
class SecondViewController: UIViewController {
private var test : LeakTest!
private var str: String = ""
override func viewDidLoad() {
super.viewDidLoad()
let btn = UIButton(frame: CGRect(x: 200, y: 100, width: 100, height: 100))
btn.setTitle("Pop", for: UIControlState.normal)
btn.setTitleColor(UIColor.red, for: UIControlState.normal)
btn.addTarget(self, action: #selector(SecondViewController.pop), for: UIControlEvents.touchUpInside)
self.view.addSubview(btn)
self.test = LeakTest {
self.str.append("leak")
}
}
func pop() {
_ = self.navigationController?.popViewController(animated: true)
}
deinit {
print("deinit")
}
}
| mit |
lvogelzang/Blocky | Blocky/Levels/Level17.swift | 1 | 877 | //
// Level17.swift
// Blocky
//
// Created by Lodewijck Vogelzang on 07-12-18
// Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved.
//
import UIKit
final class Level17: Level {
let levelNumber = 17
var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]]
let cameraFollowsBlock = false
let blocky: Blocky
let enemies: [Enemy]
let foods: [Food]
init() {
blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1))
let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0)
let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1)
enemies = [enemy0, enemy1]
foods = []
}
}
| mit |
inket/stts | sttsTests/StringExtensionsTests.swift | 1 | 589 | //
// StringExtensionsTests.swift
// sttsTests
//
import XCTest
@testable import stts
class StringExtensionsTests: XCTestCase {
func testInnerJSONStringWithNewLine() throws {
XCTAssertEqual("jsonCallback(✅);\n".innerJSONString, "✅")
XCTAssertEqual("jsonCallback(✅); \n\n\n ".innerJSONString, "✅")
}
func testInnerJSONStringWithoutNewLine() throws {
XCTAssertEqual("jsonCallback(✅);".innerJSONString, "✅")
}
func testInnerJSONStringOther() throws {
XCTAssertEqual("out of scope".innerJSONString, "out of scope")
}
}
| mit |
funnyordie/TimeAgoInWords | Demo/Demo/AppDelegate.swift | 1 | 2134 | //
// AppDelegate.swift
// Demo
//
// Created by Ryan Boyajian on 4/3/15.
// Copyright (c) 2015 Ello. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
Roommate-App/roomy | roomy/Pods/IBAnimatable/Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationBallZigZag.swift | 2 | 2533 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallZigZag: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 0.7
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize: CGFloat = size.width / 5
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.timingFunctionType = .linear
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 = .infinity
animation.isRemovedOnCompletion = false
let circle1 = makeCircleLayer(frame: frame, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
layer.addSublayer(circle1)
// 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))]
let circle2 = makeCircleLayer(frame: frame, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
layer.addSublayer(circle2)
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallZigZag {
func makeCircleLayer(frame: CGRect, size: CGSize, color: UIColor, animation: CAAnimation) -> CALayer {
let circle = ActivityIndicatorShape.circle.makeLayer(size: size, color: color)
circle.frame = frame
circle.add(animation, forKey: "animation")
return circle
}
}
| mit |
mbuchetics/DataSource | DataSourceTests/DataSourceTests.swift | 1 | 1006 | //
// DataSourceTests.swift
// DataSourceTests
//
// Created by Matthias Buchetics on 22/02/2017.
// Copyright © 2017 aaa - all about apps GmbH. All rights reserved.
//
import XCTest
@testable import DataSource
class DataSourceTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
kickstarter/ios-oss | KsApi/extensions/ApolloClient+RAC.swift | 1 | 2167 | import Apollo
import Foundation
import ReactiveSwift
extension ApolloClient: ApolloClientType {
/**
Performs a GraphQL fetch request with a given query.
- parameter query: The `Query` to fetch.
- returns: A `SignalProducer` generic over `Query.Data` and `ErrorEnvelope`.
*/
public func fetch<Query: GraphQLQuery>(query: Query) -> SignalProducer<Query.Data, ErrorEnvelope> {
SignalProducer { observer, _ in
self.fetch(query: query, cachePolicy: .fetchIgnoringCacheCompletely) { result in
switch result {
case let .success(response):
if let error = response.errors?.first?.errorDescription {
return observer.send(error: .graphError(error))
}
guard let data = response.data else {
return observer.send(error: .couldNotParseJSON)
}
observer.send(value: data)
observer.sendCompleted()
case let .failure(error):
print("🔴 [KsApi] ApolloClient query failure - error : \((error as NSError).description)")
observer.send(error: .couldNotParseJSON)
}
}
}
}
/**
Performs a GraphQL mutation request with a given mutation.
- parameter mutation: The `Mutation` to perform.
- returns: A `SignalProducer` generic over `Mutation.Data` and `ErrorEnvelope`.
*/
public func perform<Mutation: GraphQLMutation>(
mutation: Mutation
) -> SignalProducer<Mutation.Data, ErrorEnvelope> {
SignalProducer { observer, _ in
self.perform(mutation: mutation) { result in
switch result {
case let .success(response):
if let error = response.errors?.first?.errorDescription {
return observer.send(error: .graphError(error))
}
guard let data = response.data else {
return observer.send(error: .couldNotParseJSON)
}
observer.send(value: data)
observer.sendCompleted()
case let .failure(error):
print("🔴 [KsApi] ApolloClient mutation failure - error : \((error as NSError).description)")
observer.send(error: .couldNotParseJSON)
}
}
}
}
}
| apache-2.0 |
propellerlabs/PropellerNetwork | Source/WebService.swift | 1 | 5559 | //
// WebService.swift
// PropellerNetwork
//
// Created by Roy McKenzie on 2/2/17.
// Copyright © 2017 Propeller. All rights reserved.
//
import Foundation
private let acceptableStatusCodes = Array(200..<300)
/// WebService error
public enum WebServiceError: Error {
case creatingRequestFailed
case parsingResponseFailed
case noParserProvided
case unacceptableStatusCode(code: Int, data: Data?)
case unknown
}
extension WebServiceError: LocalizedError {
public var errorDescription: String? {
switch self {
case .creatingRequestFailed:
return NSLocalizedString("Could not create URLRequest", comment: "")
case .noParserProvided:
return NSLocalizedString("No parser was provided for Resource", comment: "")
case .parsingResponseFailed:
return NSLocalizedString("Could not parse response", comment: "")
case .unacceptableStatusCode(let statusCode):
return NSLocalizedString("Returned bad status code: \(statusCode)", comment: "")
case .unknown:
return NSLocalizedString("An unkwon error occured", comment: "")
}
}
}
/// Makes requests
public struct WebService {
/// Requests a resource with completion via `URLSession` `dataTask`
///
/// - Parameters:
/// - configuration: a configuration conforming to `ResourceRequestConfiguring`
/// - completion: `(A?, Error?) -> Void`
public static func request<A>(_ resource: Resource<A>, completion: @escaping (A?, Error?) -> Void) {
// Build `URLRequest` with this resource
let request: URLRequest
do {
request = try urlRequestWith(resource)
} catch {
completion(nil, error)
return
}
// Perform `dataTask` with `shared` `URLSession` and resource request
URLSession.shared.dataTask(with: request) { data, response, error in
// Error case
if let error = error {
NSLog("Failed performing `URLSession` `dataTask` for resource: \(resource.description)")
completion(nil, error)
return
}
// Check response code
if let response = response as? HTTPURLResponse {
if !acceptableStatusCodes.contains(response.statusCode) {
let error = WebServiceError.unacceptableStatusCode(code: response.statusCode, data: data)
completion(nil, error)
return
}
}
// For void types we will not be handling data
if A.self is Void.Type {
completion(() as? A, nil)
return
}
// Data response case
if let data = data {
let jsonObject: Any
do {
jsonObject = try JSONDecoder.decode(data)
} catch {
completion(nil, error)
return
}
guard let parser = resource.parsing else {
let error = WebServiceError.noParserProvided
completion(nil, error)
return
}
// Parse object
do {
let object = try parser(jsonObject)
completion(object, nil)
} catch {
completion(nil, error)
}
return
}
// Nil data and error case
completion(nil, nil)
}
.resume()
}
/// Configures and credentials a `URLRequest` for a `Resource<A>`
///
/// - Returns: A `URLRequest` for this resource
internal static func urlRequestWith<A>(_ resource: Resource<A>) throws -> URLRequest {
let configuration = resource.configuration
let resourceUrl: URL
// Set URL
if let basePath = configuration.basePath, !basePath.isEmpty {
guard let url = URL(string: basePath)?.appendingPathComponent(resource.urlPath) else {
throw WebServiceConfigurationError.couldNotBuildUrl
}
resourceUrl = url
} else {
guard let url = URL(string: resource.urlPath) else {
throw WebServiceConfigurationError.couldNotBuildUrl
}
resourceUrl = url
}
// Create request and set method
var request = URLRequest(url: resourceUrl)
request.httpMethod = resource.method.rawValue.uppercased()
// Add headers
resource.headers?.forEach { request.addValue($0.value, forHTTPHeaderField: $0.key) }
// Add parameters
if let parameters = resource.parameters {
do {
request = try resource.encoding.encode(request, parameters: parameters)
} catch {
throw error
}
}
// Add additional headers
configuration.additionalHeaders?.forEach { request.addValue($0.value, forHTTPHeaderField: $0.key) }
// Add Auth header
if let credential = configuration.credential {
request = credential.applyTo(request)
}
return request
}
}
| mit |
omochi/numsw | Playgrounds/RenderTableViewController.swift | 1 | 3874 | //
// RenderTableViewController.swift
// sandbox
//
// Created by color_box on 2017/03/04.
// Copyright © 2017年 sonson. All rights reserved.
//
// Second Implementation with UITableView
import UIKit
private class RenderTableViewCell: UITableViewCell {
var renderer: Renderer? {
willSet {
self.renderImageView.image = nil
self.renderedImageSize = .zero
}
}
private let renderImageView = UIImageView(frame: .zero)
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
print("RenderTableViewCell init")
self.separatorInset = .zero
self.selectionStyle = .none
renderImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
renderImageView.contentMode = .scaleAspectFit
self.contentView.addSubview(renderImageView)
renderImageView.frame = self.contentView.bounds
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
print("RenderTableViewCell deinit")
}
private var renderedImageSize = CGSize.zero
func updateImageViewIfNeeded() {
print("rendering bounds: \(self.contentView.bounds)")
if renderedImageSize == self.contentView.bounds.size &&
self.renderImageView.image != nil {
// already rendered
return
}
updateImageView()
}
private func updateImageView() {
guard let renderer = self.renderer else { return }
let image = renderer.renderToImage(size: self.contentView.bounds.size)
self.renderImageView.image = image
renderedImageSize = self.contentView.bounds.size
}
}
public class RenderTableViewController: UITableViewController {
private let CellIdentifier = "Cell"
var renderers: [Renderer] = [] {
didSet {
tableView.reloadData()
}
}
public init() {
super.init(style: .plain)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset = .zero
tableView.separatorStyle = .none
tableView.register(RenderTableViewCell.self, forCellReuseIdentifier: CellIdentifier)
}
public func append(renderer: Renderer) {
self.renderers.append(renderer)
self.tableView.reloadData()
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// will ??
//self.tableView.reloadData()
}
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
for view in tableView.visibleCells {
(view as! RenderTableViewCell).updateImageViewIfNeeded()
}
}
public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return renderers.count
}
public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier, for: indexPath) as! RenderTableViewCell
cell.renderer = renderers[indexPath.row]
return cell
}
public override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.view.bounds.height * 0.5
}
public override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let cell = cell as! RenderTableViewCell
cell.updateImageViewIfNeeded()
}
}
| mit |
CodeAndWeb/TexturePacker-SpriteKit-Swift | TexturePacker-SpriteKit-Swift/AppDelegate.swift | 1 | 2199 | //
// AppDelegate.swift
// TexturePacker-SpriteKit-Swift
//
// Created by Joachim Grill on 17.12.14.
// Copyright (c) 2014 CodeAndWeb GmbH. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
apple/swift-package-manager | Sources/PackageGraph/Version+Extensions.swift | 2 | 656 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2019-2020 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 struct TSCUtility.Version
extension Version {
func nextPatch() -> Version {
return Version(major, minor, patch + 1)
}
}
| apache-2.0 |
rajeejones/SavingPennies | Pods/IBAnimatable/IBAnimatable/PresentFlipSegue.swift | 4 | 417 | //
// Created by Tom Baranes on 05/05/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
open class PresentFlipSegue: UIStoryboardSegue {
open override func perform() {
destination.transitioningDelegate = TransitionPresenterManager.sharedManager().retrievePresenter(transitionAnimationType: .flip(from: .left))
source.present(destination, animated: true, completion: nil)
}
}
| gpl-3.0 |
googlesamples/identity-appflip-ios | AppFlip-Sample-iOS/AppDelegate.swift | 1 | 2480 | /*
* Copyright 2019 Google
*
* 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
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity,
restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
print("Handling Universal Link");
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
let incomingURL = userActivity.webpageURL,
let components = NSURLComponents(url: incomingURL, resolvingAgainstBaseURL: true),
let path = components.path,
let params = components.queryItems else {
return false
}
print("path = \(path)")
// Start AppFlipViewController
let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initViewController : AppFlipViewController = mainStoryboard.instantiateViewController(
withIdentifier: "consentPanel") as! AppFlipViewController
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = initViewController
if let clientID = params.first(where: { $0.name == "client_id" } )?.value,
let scope = params.first(where: { $0.name == "scope" } )?.value,
let state = params.first(where: { $0.name == "state" } )?.value,
let redirectUri = params.first(where: { $0.name == "redirect_uri" } )?.value {
initViewController.flipData["clientID"] = clientID
initViewController.flipData["scope"] = scope
initViewController.flipData["state"] = state
initViewController.flipData["redirectUri"] = redirectUri
self.window?.makeKeyAndVisible()
return true
} else {
print("Parameters are missing")
return false
}
}
}
| apache-2.0 |
TonnyTao/HowSwift | how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/AnyObserver.swift | 8 | 2199 | //
// AnyObserver.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// A type-erased `ObserverType`.
///
/// Forwards operations to an arbitrary underlying observer with the same `Element` type, hiding the specifics of the underlying observer type.
public struct AnyObserver<Element> : ObserverType {
/// Anonymous event handler type.
public typealias EventHandler = (Event<Element>) -> Void
private let observer: EventHandler
/// Construct an instance whose `on(event)` calls `eventHandler(event)`
///
/// - parameter eventHandler: Event handler that observes sequences events.
public init(eventHandler: @escaping EventHandler) {
self.observer = eventHandler
}
/// Construct an instance whose `on(event)` calls `observer.on(event)`
///
/// - parameter observer: Observer that receives sequence events.
public init<Observer: ObserverType>(_ observer: Observer) where Observer.Element == Element {
self.observer = observer.on
}
/// Send `event` to this observer.
///
/// - parameter event: Event instance.
public func on(_ event: Event<Element>) {
self.observer(event)
}
/// Erases type of observer and returns canonical observer.
///
/// - returns: type erased observer.
public func asObserver() -> AnyObserver<Element> {
self
}
}
extension AnyObserver {
/// Collection of `AnyObserver`s
typealias s = Bag<(Event<Element>) -> Void>
}
extension ObserverType {
/// Erases type of observer and returns canonical observer.
///
/// - returns: type erased observer.
public func asObserver() -> AnyObserver<Element> {
AnyObserver(self)
}
/// Transforms observer of type R to type E using custom transform method.
/// Each event sent to result observer is transformed and sent to `self`.
///
/// - returns: observer that transforms events.
public func mapObserver<Result>(_ transform: @escaping (Result) throws -> Element) -> AnyObserver<Result> {
AnyObserver { e in
self.on(e.map(transform))
}
}
}
| mit |
AboutObjectsTraining/swift-comp-reston-2017-02 | demos/ReadingList/ReadingList/AppDelegate.swift | 1 | 252 | //
// AppDelegate.swift
// ReadingList
//
// Created by Student on 3/1/17.
// Copyright © 2017 Student. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| mit |
zhiquan911/CHKLineChart | CHKLineChart/Example/Example/Demo/views/SectionHeaderView.swift | 1 | 1733 | //
// SectionHeaderView.swift
// CHKLineChart
//
// Created by Chance on 2017/7/14.
// Copyright © 2017年 atall.io. All rights reserved.
//
import UIKit
import SnapKit
import CHKLineChartKit
class SectionHeaderView: UIView {
@IBOutlet var labelTitle: UILabel!
@IBOutlet var buttonSet: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setupUI() {
self.buttonSet = UIButton(type: .custom)
self.buttonSet.setTitle("设置", for: .normal)
self.buttonSet.titleLabel?.font = UIFont.systemFont(ofSize: 10)
self.buttonSet.setTitleColor(UIColor.white, for: .normal)
self.buttonSet.backgroundColor = UIColor.darkGray
self.buttonSet.layer.cornerRadius = 2
self.addSubview(self.buttonSet)
self.buttonSet.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(2)
make.top.bottom.equalToSuperview().offset(2)
make.width.equalTo(30)
}
// self.buttonSet.frame = CGRect(x: 0, y: 1, width: 30, height: 20)
self.labelTitle = UILabel()
self.labelTitle.textColor = UIColor.white
self.labelTitle.font = UIFont.systemFont(ofSize: 10)
self.labelTitle.backgroundColor = UIColor.clear
self.addSubview(self.labelTitle)
self.labelTitle.snp.makeConstraints { (make) in
make.left.equalTo(self.buttonSet.snp.right).offset(8)
make.top.bottom.equalToSuperview().offset(2)
make.right.equalToSuperview()
}
}
}
| mit |
tohab/HanBot | Hanbot/AppDelegate.swift | 2 | 2174 | //
// AppDelegate.swift
// HanBot
//
// Created by Rohan Prasad on 03/02/2017.
// Copyright (c) 2017 Rohan Prasad. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
mohamede1945/quran-ios | Quran/QuranShareData.swift | 2 | 893 | //
// QuranShareData.swift
// Quran
//
// Created by Mohamed Afifi on 4/4/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UIKit
struct QuranShareData {
let location: CGPoint
let gestures: [UIGestureRecognizer]
let cell: QuranBasePageCollectionViewCell
let page: QuranPage
let ayah: AyahNumber
}
| gpl-3.0 |
arvedviehweger/swift | test/ClangImporter/objc_bridging_generics.swift | 1 | 15238 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -verify -swift-version 4 %s
// REQUIRES: objc_interop
import Foundation
import objc_generics
func testNSArrayBridging(_ hive: Hive) {
_ = hive.bees as [Bee]
}
func testNSDictionaryBridging(_ hive: Hive) {
_ = hive.beesByName as [String : Bee] // expected-error{{'[String : Bee]?' is not convertible to '[String : Bee]'; did you mean to use 'as!' to force downcast?}}
var dict1 = hive.anythingToBees
let dict2: [AnyHashable : Bee] = dict1
dict1 = dict2
}
func testNSSetBridging(_ hive: Hive) {
_ = hive.allBees as Set<Bee>
}
public func expectType<T>(_: T.Type, _ x: inout T) {}
func testNSMutableDictionarySubscript(
_ dict: NSMutableDictionary, key: NSCopying, value: Any) {
var oldValue = dict[key]
expectType(Optional<Any>.self, &oldValue)
dict[key] = value
}
class C {}
struct S {}
func f(_ x: GenericClass<NSString>) -> NSString? { return x.thing() }
func f1(_ x: GenericClass<NSString>) -> NSString? { return x.otherThing() }
func f2(_ x: GenericClass<NSString>) -> Int32 { return x.count() }
func f3(_ x: GenericClass<NSString>) -> NSString? { return x.propertyThing }
func f4(_ x: GenericClass<NSString>) -> [NSString] { return x.arrayOfThings() }
func f5(_ x: GenericClass<C>) -> [C] { return x.arrayOfThings() }
func f6(_ x: GenericSubclass<NSString>) -> NSString? { return x.thing() }
func f6(_ x: GenericSubclass<C>) -> C? { return x.thing() }
func g() -> NSString? { return GenericClass<NSString>.classThing() }
func g1() -> NSString? { return GenericClass<NSString>.otherClassThing() }
func h(_ s: NSString?) -> GenericClass<NSString> {
return GenericClass(thing: s)
}
func j(_ x: GenericClass<NSString>?) {
takeGenericClass(x)
}
class Desk {}
class Rock: NSObject, Pettable {
required init(fur: Any) {}
func other() -> Self { return self }
class func adopt() -> Self { fatalError("") }
func pet() {}
func pet(with other: Pettable) {}
class var needingMostPets: Pettable {
get { fatalError("") }
set { }
}
}
class Porcupine: Animal {
}
class Cat: Animal, Pettable {
required init(fur: Any) {}
func other() -> Self { return self }
class func adopt() -> Self { fatalError("") }
func pet() {}
func pet(with other: Pettable) {}
class var needingMostPets: Pettable {
get { fatalError("") }
set { }
}
}
func testImportedTypeParamRequirements() {
let _ = PettableContainer<Desk>() // expected-error{{type 'Desk' does not conform to protocol 'Pettable'}}
let _ = PettableContainer<Rock>()
let _ = PettableContainer<Porcupine>() // expected-error{{type 'Porcupine' does not conform to protocol 'Pettable'}}
let _ = PettableContainer<Cat>()
let _ = AnimalContainer<Desk>() // expected-error{{'AnimalContainer' requires that 'Desk' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Desk]}}
let _ = AnimalContainer<Rock>() // expected-error{{'AnimalContainer' requires that 'Rock' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Rock]}}
let _ = AnimalContainer<Porcupine>()
let _ = AnimalContainer<Cat>()
let _ = PettableAnimalContainer<Desk>() // expected-error{{'PettableAnimalContainer' requires that 'Desk' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Desk]}}
let _ = PettableAnimalContainer<Rock>() // expected-error{{'PettableAnimalContainer' requires that 'Rock' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Rock]}}
let _ = PettableAnimalContainer<Porcupine>() // expected-error{{type 'Porcupine' does not conform to protocol 'Pettable'}}
let _ = PettableAnimalContainer<Cat>()
}
extension GenericClass {
@objc func doesntUseGenericParam() {}
@objc func doesntUseGenericParam2() -> Self {}
// Doesn't use 'T', since ObjC class type params are type-erased
@objc func doesntUseGenericParam3() -> GenericClass<T> {}
// Doesn't use 'T', since its metadata isn't necessary to pass around instance
@objc func doesntUseGenericParam4(_ x: T, _ y: T.Type) -> T {
_ = x
_ = y
return x
}
// Doesn't use 'T', since its metadata isn't necessary to erase to AnyObject
// or to existential metatype
@objc func doesntUseGenericParam5(_ x: T, _ y: T.Type) -> T {
_ = y as AnyObject.Type
_ = y as Any.Type
_ = y as AnyObject
_ = x as AnyObject
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamC(_ x: [(T, T)]?) {} // expected-note{{used here}}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamD(_ x: Int) {
_ = T.self // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamE(_ x: Int) {
_ = x as? T // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamF(_ x: Int) {
_ = x is T // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamG(_ x: T) {
_ = T.self // expected-note{{used here}}
}
@objc func doesntUseGenericParamH(_ x: T) {
_ = x as Any
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamI(_ y: T.Type) {
_ = y as Any // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamJ() -> [(T, T)]? {} // expected-note{{used here}}
@objc static func doesntUseGenericParam() {}
@objc static func doesntUseGenericParam2() -> Self {}
// Doesn't technically use 'T', since it's type-erased at runtime
@objc static func doesntUseGenericParam3() -> GenericClass<T> {}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
static func usesGenericParamC(_ x: [(T, T)]?) {} // expected-note{{used here}}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc static func usesGenericParamD(_ x: Int) {
_ = T.self // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc static func usesGenericParamE(_ x: Int) {
_ = x as? T // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc static func usesGenericParamF(_ x: Int) {
_ = x is T // expected-note{{used here}}
}
@objc func checkThatMethodsAreObjC() {
_ = #selector(GenericClass.doesntUseGenericParam)
_ = #selector(GenericClass.doesntUseGenericParam2)
_ = #selector(GenericClass.doesntUseGenericParam3)
_ = #selector(GenericClass.doesntUseGenericParam4)
_ = #selector(GenericClass.doesntUseGenericParam5)
}
}
func swiftFunction<T: Animal>(x: T) {}
extension AnimalContainer {
@objc func doesntUseGenericParam1(_ x: T, _ y: T.Type) {
_ = #selector(x.another)
_ = #selector(y.create)
}
@objc func doesntUseGenericParam2(_ x: T, _ y: T.Type) {
let a = x.another()
_ = a.another()
_ = x.another().another()
_ = type(of: x).create().another()
_ = type(of: x).init(noise: x).another()
_ = y.create().another()
_ = y.init(noise: x).another()
_ = y.init(noise: x.another()).another()
x.eat(a)
}
@objc func doesntUseGenericParam3(_ x: T, _ y: T.Type) {
let sup: Animal = x
sup.eat(x)
_ = x.buddy
_ = x[0]
x[0] = x
}
@objc func doesntUseGenericParam4(_ x: T, _ y: T.Type) {
_ = type(of: x).apexPredator.another()
type(of: x).apexPredator = x
_ = y.apexPredator.another()
y.apexPredator = x
}
@objc func doesntUseGenericParam5(y: T) {
var x = y
x = y
_ = x
}
@objc func doesntUseGenericParam6(y: T?) {
var x = y
x = y
_ = x
}
// Doesn't use 'T', since dynamic casting to an ObjC generic class doesn't
// check its generic parameters
@objc func doesntUseGenericParam7() {
_ = (self as AnyObject) as! GenericClass<T>
_ = (self as AnyObject) as? GenericClass<T>
_ = (self as AnyObject) as! AnimalContainer<T>
_ = (self as AnyObject) as? AnimalContainer<T>
_ = (self as AnyObject) is AnimalContainer<T>
_ = (self as AnyObject) is AnimalContainer<T>
}
// Dynamic casting to the generic parameter would require its generic params,
// though
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamZ1() {
_ = (self as AnyObject) as! T //expected-note{{here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamZ2() {
_ = (self as AnyObject) as? T //expected-note{{here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamZ3() {
_ = (self as AnyObject) is T //expected-note{{here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamA(_ x: T) {
_ = T(noise: x) // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamB() {
_ = T.create() // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamC() {
_ = T.apexPredator // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamD(_ x: T) {
T.apexPredator = x // expected-note{{used here}}
}
// rdar://problem/27796375 -- allocating init entry points for ObjC
// initializers are generated as true Swift generics, so reify type
// parameters.
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
func usesGenericParamE(_ x: T) {
_ = GenericClass(thing: x) // expected-note{{used here}}
}
@objc func checkThatMethodsAreObjC() {
_ = #selector(AnimalContainer.doesntUseGenericParam1)
_ = #selector(AnimalContainer.doesntUseGenericParam2)
_ = #selector(AnimalContainer.doesntUseGenericParam3)
_ = #selector(AnimalContainer.doesntUseGenericParam4)
}
// rdar://problem/26283886
@objc func funcWithWrongArgType(x: NSObject) {}
@objc func crashWithInvalidSubscript(x: NSArray) {
_ = funcWithWrongArgType(x: x[12])
// expected-error@-1{{cannot convert value of type 'Any' to expected argument type 'NSObject'}}
}
}
extension PettableContainer {
@objc func doesntUseGenericParam(_ x: T, _ y: T.Type) {
// TODO: rdar://problem/27796375--allocating entry points are emitted as
// true generics.
// _ = type(of: x).init(fur: x).other()
_ = type(of: x).adopt().other()
// _ = y.init(fur: x).other()
_ = y.adopt().other()
x.pet()
x.pet(with: x)
}
// TODO: rdar://problem/27796375--allocating entry points are emitted as
// true generics.
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamZ1(_ x: T, _ y: T.Type) {
_ = type(of: x).init(fur: x).other() // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamZ2(_ x: T, _ y: T.Type) {
_ = y.init(fur: x).other() // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamA(_ x: T) {
_ = T(fur: x) // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamB(_ x: T) {
_ = T.adopt() // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamC(_ x: T) {
_ = T.needingMostPets // expected-note{{used here}}
}
// expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}}
@objc func usesGenericParamD(_ x: T) {
T.needingMostPets = x // expected-note{{used here}}
}
@objc func checkThatMethodsAreObjC() {
_ = #selector(PettableContainer.doesntUseGenericParam)
}
}
// expected-error@+1{{inheritance from a generic Objective-C class 'GenericClass' must bind type parameters of 'GenericClass' to specific concrete types}}
class SwiftGenericSubclassA<X: AnyObject>: GenericClass<X> {}
// expected-error@+1{{inheritance from a generic Objective-C class 'GenericClass' must bind type parameters of 'GenericClass' to specific concrete types}}
class SwiftGenericSubclassB<X: AnyObject>: GenericClass<GenericClass<X>> {}
// expected-error@+1{{inheritance from a generic Objective-C class 'GenericClass' must bind type parameters of 'GenericClass' to specific concrete types}}
class SwiftGenericSubclassC<X: NSCopying>: GenericClass<X> {}
class SwiftConcreteSubclassA: GenericClass<AnyObject> {
override init(thing: AnyObject) { }
override func thing() -> AnyObject? { }
override func count() -> Int32 { }
override class func classThing() -> AnyObject? { }
override func arrayOfThings() -> [AnyObject] {}
}
class SwiftConcreteSubclassB: GenericClass<NSString> {
override init(thing: NSString) { }
override func thing() -> NSString? { }
override func count() -> Int32 { }
override class func classThing() -> NSString? { }
override func arrayOfThings() -> [NSString] {}
}
class SwiftConcreteSubclassC<T>: GenericClass<NSString> {
override init(thing: NSString) { }
override func thing() -> NSString? { }
override func count() -> Int32 { }
override class func classThing() -> NSString? { }
override func arrayOfThings() -> [NSString] {}
}
// FIXME: Some generic ObjC APIs rely on covariance. We don't handle this well
// in Swift yet, but ensure we don't emit spurious warnings when
// `as!` is used to force types to line up.
func foo(x: GenericClass<NSMutableString>) {
let x2 = x as! GenericClass<NSString>
takeGenericClass(x2)
takeGenericClass(unsafeBitCast(x, to: GenericClass<NSString>.self))
}
// Test type-erased bounds
func getContainerForPanda() -> AnimalContainer<Animal> {
return Panda.getContainer()
}
func getContainerForFungiblePanda() -> FungibleAnimalContainer<Animal & Fungible> {
return Panda.getFungibleContainer()
}
| apache-2.0 |
OneBusAway/onebusaway-iphone | Carthage/Checkouts/IGListKit/Examples/Examples-tvOS/IGListKitExamples/Views/CarouselCell.swift | 2 | 1150 | /**
Copyright (c) Facebook, Inc. and its affiliates.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
final class CarouselCell: UICollectionViewCell {
@IBOutlet weak var titleLabel: UILabel!
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
let normalColor = UIColor(red: 174 / 255.0, green: 198 / 255.0, blue: 207 / 255.0, alpha: 1)
let focusColor = UIColor(red: 117 / 255.0, green: 155 / 255.0, blue: 169 / 255.0, alpha: 1)
backgroundColor = isFocused ? focusColor : normalColor
}
}
| apache-2.0 |
HabitRPG/habitrpg-ios | HabitRPG/Views/HabiticaAlertController.swift | 1 | 16880 | //
// BaseAlertController.swift
// Habitica
//
// Created by Phillip on 23.10.17.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import UIKit
import PopupDialog
@objc
class HabiticaAlertController: UIViewController, Themeable {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var titleLabelTopMargin: NSLayoutConstraint!
@IBOutlet weak var titleLabelBottomMargin: NSLayoutConstraint!
@IBOutlet weak var titleLabelBackground: UIView!
@IBOutlet weak var buttonStackView: UIStackView!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var alertStackView: UIStackView!
@IBOutlet weak var bottomOffsetConstraint: NSLayoutConstraint!
@IBOutlet var centerConstraint: NSLayoutConstraint!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var scrollviewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var alertBackgroundView: UIView!
@IBOutlet weak var buttonContainerView: UIView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var containerViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var buttonUpperSpacing: NSLayoutConstraint!
@IBOutlet weak var buttonLowerSpacing: NSLayoutConstraint!
private var buttonHandlers = [Int: ((UIButton) -> Swift.Void)]()
private var buttons = [UIButton]()
private var shouldCloseOnButtonTap = [Int: Bool]()
var dismissOnBackgroundTap = true
var contentView: UIView? {
didSet {
configureContentView()
}
}
override var title: String? {
didSet {
configureTitleView()
}
}
var message: String? {
didSet {
if message == nil || self.view == nil {
return
}
attributedMessage = nil
configureMessageView()
}
}
var attributedMessage: NSAttributedString? {
didSet {
if attributedMessage == nil || self.view == nil {
return
}
message = nil
configureMessageView()
}
}
var messageFont = CustomFontMetrics.scaledSystemFont(ofSize: 17)
var messageColor: UIColor?
var messageView: UILabel?
var arrangeMessageLast = false
var closeAction: (() -> Void)? {
didSet {
configureCloseButton()
}
}
var contentViewInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 30) {
didSet {
if containerView != nil {
containerView.layoutMargins = contentViewInsets
}
}
}
var containerViewSpacing: CGFloat = 8
var closeTitle: String?
convenience init(title newTitle: String?, message newMessage: String? = nil) {
self.init()
title = newTitle
message = newMessage
}
convenience init(title newTitle: String?, attributedMessage newMessage: NSAttributedString) {
self.init()
title = newTitle
attributedMessage = newMessage
}
init() {
super.init(nibName: "HabiticaAlertController", bundle: Bundle.main)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
ThemeService.shared.addThemeable(themable: self, applyImmediately: true)
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(backgroundTapped)))
alertBackgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(alertTapped)))
}
func applyTheme(theme: Theme) {
view.backgroundColor = theme.dimmBackgroundColor.withAlphaComponent(0.7)
buttonContainerView.backgroundColor = theme.contentBackgroundColor
alertBackgroundView.backgroundColor = theme.contentBackgroundColor
closeButton.backgroundColor = theme.contentBackgroundColor
titleLabel.textColor = theme.primaryTextColor
titleLabelBackground.backgroundColor = theme.contentBackgroundColor
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
configureTitleView()
configureContentView()
configureMessageView()
configureCloseButton()
configureButtons()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
super.viewWillDisappear(animated)
}
override func viewWillLayoutSubviews() {
var maximumSize = view.frame.size
if #available(iOS 11.0, *) {
let guide = view.safeAreaLayoutGuide
maximumSize = guide.layoutFrame.size
}
maximumSize.width = min(300, maximumSize.width - 24)
maximumSize.width -= contentViewInsets.left + contentViewInsets.right
maximumSize.height -= contentViewInsets.top + contentViewInsets.bottom
let maximumHeight = maximumSize.height - (32 + 140) - buttonUpperSpacing.constant - buttonLowerSpacing.constant
var contentHeight = contentView?.systemLayoutSizeFitting(maximumSize).height ?? 0
if contentHeight == 0 {
contentHeight = contentView?.intrinsicContentSize.height ?? 0
}
var height = contentHeight + contentViewInsets.top + contentViewInsets.bottom
if let messageView = messageView {
if height > 0 {
height += containerViewSpacing
}
height += messageView.sizeThatFits(maximumSize).height
}
scrollviewHeightConstraint.constant = min(height, maximumHeight)
if arrangeMessageLast {
if let contentView = contentView {
contentView.pin.top(contentViewInsets.top).left(contentViewInsets.left).width(maximumSize.width).height(contentHeight)
messageView?.pin.top(contentHeight + containerViewSpacing).left(contentViewInsets.left).width(maximumSize.width).sizeToFit(.width)
} else {
messageView?.pin.top(contentViewInsets.top).left(contentViewInsets.left).width(maximumSize.width).height(height)
}
} else {
if let messageView = messageView {
messageView.pin.top(contentViewInsets.top).left(contentViewInsets.left).width(maximumSize.width).sizeToFit(.width)
contentView?.pin.below(of: messageView).marginTop(containerViewSpacing).left(contentViewInsets.left).width(maximumSize.width).height(contentHeight)
} else {
contentView?.pin.top(contentViewInsets.top).left(contentViewInsets.left).width(maximumSize.width).height(contentHeight)
}
}
containerViewHeightConstraint.constant = height
contentView?.updateConstraints()
super.viewWillLayoutSubviews()
}
@objc
func keyboardWillShow(notification: NSNotification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.bottomOffsetConstraint.constant = keyboardHeight + 8
if centerConstraint.isActive {
centerConstraint.isActive = false
}
}
}
@objc
func keyboardWillHide(notification: NSNotification) {
self.bottomOffsetConstraint.constant = 16
if !centerConstraint.isActive {
centerConstraint.isActive = true
}
}
@objc
@discardableResult
func addAction(title: String, style: UIAlertAction.Style = .default, isMainAction: Bool = false, closeOnTap: Bool = true, identifier: String? = nil, handler: ((UIButton) -> Swift.Void)? = nil) -> UIButton {
let button = UIButton()
if let identifier = identifier {
button.accessibilityIdentifier = identifier
}
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.setTitle(title, for: .normal)
button.contentEdgeInsets = UIEdgeInsets(top: 8, left: 24, bottom: 8, right: 24)
var color = isMainAction ? ThemeService.shared.theme.fixedTintColor : ThemeService.shared.theme.tintColor
if style == .destructive {
color = ThemeService.shared.theme.errorColor
}
if isMainAction {
button.setTitleColor(UIColor.white, for: .normal)
button.titleLabel?.font = CustomFontMetrics.scaledSystemFont(ofSize: 17, ofWeight: .semibold)
button.backgroundColor = color
button.cornerRadius = 8
button.layer.shadowColor = ThemeService.shared.theme.buttonShadowColor.cgColor
button.layer.shadowRadius = 2
button.layer.shadowOffset = CGSize(width: 1, height: 1)
button.layer.shadowOpacity = 0.5
button.layer.masksToBounds = false
} else {
button.setTitleColor(color, for: .normal)
button.titleLabel?.font = CustomFontMetrics.scaledSystemFont(ofSize: 17)
}
button.addWidthConstraint(width: 150, relatedBy: NSLayoutConstraint.Relation.greaterThanOrEqual)
button.addHeightConstraint(height: 38)
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
button.tag = buttons.count
if let action = handler {
buttonHandlers[button.tag] = action
}
shouldCloseOnButtonTap[button.tag] = closeOnTap
buttons.append(button)
if buttonStackView != nil {
buttonStackView.addArrangedSubview(button)
if buttonStackView.arrangedSubviews.count > 2 {
buttonStackView.axis = .vertical
}
}
return button
}
@objc
func setCloseAction(title: String, handler: @escaping (() -> Void)) {
closeAction = handler
closeTitle = title
}
private func configureTitleView() {
if titleLabel != nil {
titleLabel.text = title
}
if title == nil && titleLabelTopMargin != nil && titleLabelBottomMargin != nil {
titleLabelTopMargin.constant = 0
titleLabelBottomMargin.constant = 0
} else if titleLabelTopMargin != nil && titleLabelBottomMargin != nil {
titleLabelTopMargin.constant = 12
titleLabelBottomMargin.constant = 12
}
}
private func configureMessageView() {
if (message == nil && attributedMessage == nil) || containerView == nil {
return
}
let label = UILabel()
label.textColor = messageColor ?? ThemeService.shared.theme.secondaryTextColor
label.font = messageFont
if message != nil {
label.text = message
} else {
label.attributedText = attributedMessage
}
label.numberOfLines = 0
label.textAlignment = .center
containerView.addSubview(label)
messageView = label
}
private func configureContentView() {
if containerView == nil {
return
}
containerView.layoutMargins = contentViewInsets
if contentView == nil && message == nil {
containerView.superview?.isHidden = true
alertStackView.spacing = 0
} else {
containerView.superview?.isHidden = false
alertStackView.spacing = containerViewSpacing
}
if let view = contentView {
if let oldView = containerView.subviews.first {
oldView.removeFromSuperview()
}
containerView.addSubview(view)
}
}
private func configureCloseButton() {
if closeButton != nil {
closeButton.isHidden = closeAction == nil
closeButton.setTitle(closeTitle, for: .normal)
closeButton.tintColor = ThemeService.shared.theme.fixedTintColor
}
}
private func configureButtons() {
buttonStackView.arrangedSubviews.forEach { (view) in
view.removeFromSuperview()
}
for button in buttons {
buttonStackView.addArrangedSubview(button)
}
if buttons.count > 1 {
buttonStackView.axis = .vertical
} else {
buttonStackView.axis = .horizontal
}
}
@objc
func show() {
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
modalTransitionStyle = .crossDissolve
modalPresentationStyle = .overCurrentContext
topController.present(self, animated: true) {
}
}
}
@objc
func enqueue() {
HabiticaAlertController.addToQueue(alert: self)
}
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
super.dismiss(animated: flag, completion: completion)
HabiticaAlertController.showNextInQueue(currentAlert: self)
}
@objc
func buttonTapped(_ button: UIButton) {
if shouldCloseOnButtonTap[button.tag] != false {
dismiss(animated: true, completion: {[weak self] in
self?.buttonHandlers[button.tag]?(button)
})
} else {
buttonHandlers[button.tag]?(button)
}
}
@IBAction func closeTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
if let action = closeAction {
action()
}
}
@objc
func backgroundTapped() {
if dismissOnBackgroundTap {
dismiss(animated: true, completion: nil)
}
}
@objc
func alertTapped() {
// if the alert is tapped, it should not be dismissed
}
private static var alertQueue = [HabiticaAlertController]()
private static func showNextInQueue(currentAlert: HabiticaAlertController) {
if alertQueue.first == currentAlert {
alertQueue.removeFirst()
}
if !alertQueue.isEmpty {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
alertQueue[0].show()
}
}
}
private static func addToQueue(alert: HabiticaAlertController) {
if alertQueue.isEmpty {
alert.show()
}
alertQueue.append(alert)
}
}
extension HabiticaAlertController {
@objc
public static func alert(title: String? = nil,
message: String? = nil) -> HabiticaAlertController {
let alertController = HabiticaAlertController(
title: title,
message: message
)
return alertController
}
@objc
public static func alert(title: String? = nil,
attributedMessage: NSAttributedString) -> HabiticaAlertController {
let alertController = HabiticaAlertController(
title: title,
attributedMessage: attributedMessage
)
return alertController
}
@objc
public static func genericError(message: String?, title: String = L10n.Errors.error) -> HabiticaAlertController {
let alertController = HabiticaAlertController(
title: title,
message: message
)
alertController.addOkAction()
return alertController
}
@objc
func addCancelAction(handler: ((UIButton) -> Void)? = nil) {
addAction(title: L10n.cancel, identifier: "Cancel", handler: handler)
}
@objc
func addCloseAction(handler: ((UIButton) -> Void)? = nil) {
addAction(title: L10n.close, identifier: "Close", handler: handler)
}
@objc
func addShareAction(handler: ((UIButton) -> Void)? = nil) {
addAction(title: L10n.share, closeOnTap: false, handler: handler)
}
@objc
func addOkAction(handler: ((UIButton) -> Void)? = nil) {
addAction(title: L10n.ok, handler: handler)
}
}
| gpl-3.0 |
twobitlabs/Nimble | Tests/NimbleTests/Matchers/MatchErrorTest.swift | 11 | 3159 | import Foundation
import XCTest
import Nimble
final class MatchErrorTest: XCTestCase, XCTestCaseProvider {
func testMatchErrorPositive() {
expect(NimbleError.laugh).to(matchError(NimbleError.laugh))
expect(NimbleError.laugh).to(matchError(NimbleError.self))
expect(EquatableError.parameterized(x: 1)).to(matchError(EquatableError.parameterized(x: 1)))
expect(NimbleError.laugh as Error).to(matchError(NimbleError.laugh))
}
func testMatchErrorNegative() {
expect(NimbleError.laugh).toNot(matchError(NimbleError.cry))
expect(NimbleError.laugh as Error).toNot(matchError(NimbleError.cry))
expect(NimbleError.laugh).toNot(matchError(EquatableError.self))
expect(EquatableError.parameterized(x: 1)).toNot(matchError(EquatableError.parameterized(x: 2)))
}
func testMatchNSErrorPositive() {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let error1 = NSError(domain: "err", code: 0, userInfo: nil)
let error2 = NSError(domain: "err", code: 0, userInfo: nil)
expect(error1).to(matchError(error2))
#endif
}
func testMatchNSErrorNegative() {
let error1 = NSError(domain: "err", code: 0, userInfo: nil)
let error2 = NSError(domain: "err", code: 1, userInfo: nil)
expect(error1).toNot(matchError(error2))
}
func testMatchPositiveMessage() {
failsWithErrorMessage("expected to match error <parameterized(x: 2)>, got <parameterized(x: 1)>") {
expect(EquatableError.parameterized(x: 1)).to(matchError(EquatableError.parameterized(x: 2)))
}
failsWithErrorMessage("expected to match error <cry>, got <laugh>") {
expect(NimbleError.laugh).to(matchError(NimbleError.cry))
}
failsWithErrorMessage("expected to match error <code=1>, got <code=0>") {
expect(CustomDebugStringConvertibleError.a).to(matchError(CustomDebugStringConvertibleError.b))
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
failsWithErrorMessage("expected to match error <Error Domain=err Code=1 \"(null)\">, got <Error Domain=err Code=0 \"(null)\">") {
let error1 = NSError(domain: "err", code: 0, userInfo: nil)
let error2 = NSError(domain: "err", code: 1, userInfo: nil)
expect(error1).to(matchError(error2))
}
#endif
}
func testMatchNegativeMessage() {
failsWithErrorMessage("expected to not match error <laugh>, got <laugh>") {
expect(NimbleError.laugh).toNot(matchError(NimbleError.laugh))
}
failsWithErrorMessage("expected to match error from type <EquatableError>, got <laugh>") {
expect(NimbleError.laugh).to(matchError(EquatableError.self))
}
}
func testDoesNotMatchNils() {
failsWithErrorMessageForNil("expected to match error <laugh>, got no error") {
expect(nil as Error?).to(matchError(NimbleError.laugh))
}
failsWithErrorMessageForNil("expected to not match error <laugh>, got no error") {
expect(nil as Error?).toNot(matchError(NimbleError.laugh))
}
}
}
| apache-2.0 |
onevcat/Kingfisher | Sources/General/ImageSource/AVAssetImageDataProvider.swift | 2 | 5185 | //
// AVAssetImageDataProvider.swift
// Kingfisher
//
// Created by onevcat on 2020/08/09.
//
// Copyright (c) 2020 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if !os(watchOS)
import Foundation
import AVKit
#if canImport(MobileCoreServices)
import MobileCoreServices
#else
import CoreServices
#endif
/// A data provider to provide thumbnail data from a given AVKit asset.
public struct AVAssetImageDataProvider: ImageDataProvider {
/// The possible error might be caused by the `AVAssetImageDataProvider`.
/// - userCancelled: The data provider process is cancelled.
/// - invalidImage: The retrieved image is invalid.
public enum AVAssetImageDataProviderError: Error {
case userCancelled
case invalidImage(_ image: CGImage?)
}
/// The asset image generator bound to `self`.
public let assetImageGenerator: AVAssetImageGenerator
/// The time at which the image should be generate in the asset.
public let time: CMTime
private var internalKey: String {
return (assetImageGenerator.asset as? AVURLAsset)?.url.absoluteString ?? UUID().uuidString
}
/// The cache key used by `self`.
public var cacheKey: String {
return "\(internalKey)_\(time.seconds)"
}
/// Creates an asset image data provider.
/// - Parameters:
/// - assetImageGenerator: The asset image generator controls data providing behaviors.
/// - time: At which time in the asset the image should be generated.
public init(assetImageGenerator: AVAssetImageGenerator, time: CMTime) {
self.assetImageGenerator = assetImageGenerator
self.time = time
}
/// Creates an asset image data provider.
/// - Parameters:
/// - assetURL: The URL of asset for providing image data.
/// - time: At which time in the asset the image should be generated.
///
/// This method uses `assetURL` to create an `AVAssetImageGenerator` object and calls
/// the `init(assetImageGenerator:time:)` initializer.
///
public init(assetURL: URL, time: CMTime) {
let asset = AVAsset(url: assetURL)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
self.init(assetImageGenerator: generator, time: time)
}
/// Creates an asset image data provider.
///
/// - Parameters:
/// - assetURL: The URL of asset for providing image data.
/// - seconds: At which time in seconds in the asset the image should be generated.
///
/// This method uses `assetURL` to create an `AVAssetImageGenerator` object, uses `seconds` to create a `CMTime`,
/// and calls the `init(assetImageGenerator:time:)` initializer.
///
public init(assetURL: URL, seconds: TimeInterval) {
let time = CMTime(seconds: seconds, preferredTimescale: 600)
self.init(assetURL: assetURL, time: time)
}
public func data(handler: @escaping (Result<Data, Error>) -> Void) {
assetImageGenerator.generateCGImagesAsynchronously(forTimes: [NSValue(time: time)]) {
(requestedTime, image, imageTime, result, error) in
if let error = error {
handler(.failure(error))
return
}
if result == .cancelled {
handler(.failure(AVAssetImageDataProviderError.userCancelled))
return
}
guard let cgImage = image, let data = cgImage.jpegData else {
handler(.failure(AVAssetImageDataProviderError.invalidImage(image)))
return
}
handler(.success(data))
}
}
}
extension CGImage {
var jpegData: Data? {
guard let mutableData = CFDataCreateMutable(nil, 0),
let destination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, nil)
else {
return nil
}
CGImageDestinationAddImage(destination, self, nil)
guard CGImageDestinationFinalize(destination) else { return nil }
return mutableData as Data
}
}
#endif
| mit |
roecrew/AudioKit | AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Noise Operations.xcplaygroundpage/Contents.swift | 2 | 503 | //: ## Noise Operations
//:
import XCPlayground
import AudioKit
let generator = AKOperationGenerator() { _ in
let white = AKOperation.whiteNoise()
let pink = AKOperation.pinkNoise()
let lfo = AKOperation.sineWave(frequency: 0.3)
let balance = lfo.scale(minimum: 0, maximum: 1)
let noise = mixer(white, pink, balance: balance)
return noise.pan(lfo)
}
AudioKit.output = generator
AudioKit.start()
generator.start()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
| mit |
acn001/SwiftJSONModel | SwiftJSONModel/SwiftJSONModelIgnored.swift | 1 | 1278 | //
// SwiftJSONModel.swift
// SWiftJSONModel
//
// @version 0.1.1
// @author Zhu Yue([email protected])
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Zhu Yue
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
class SwiftJSONModelIgnored: NSObject {
} | mit |
nathawes/swift | test/ClangImporter/clang_builtins.swift | 5 | 1637 | // RUN: not %target-swift-frontend -typecheck %s 2>&1 | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-%target-runtime %s
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import MSVCRT
#else
#error("Unsupported platform")
#endif
func test() {
let _: Int = strxfrm
// CHECK: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int'
let _: Int = strcspn
// CHECK: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int'
let _: Int = strspn
// CHECK: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int'
let _: Int = strlen
// CHECK: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int'
}
#if canImport(Darwin)
// These functions aren't consistently available across platforms, so only
// test for them on Apple platforms.
func testApple() {
let _: Int = strlcpy
// CHECK-objc: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int'
let _: Int = strlcat
// CHECK-objc: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int'
// wcslen is different: it wasn't a builtin until Swift 4, and so its return
// type has always been 'Int'.
let _: Int = wcslen
// CHECK-objc: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int'
}
#endif
| apache-2.0 |
TrustWallet/trust-wallet-ios | Trust/Settings/Types/SettingsError.swift | 1 | 405 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
enum SettingsError: LocalizedError {
case failedToSendEmail
var errorDescription: String? {
switch self {
case .failedToSendEmail:
return NSLocalizedString("settings.error.failedToSendEmail", value: "Failed to send email. Make sure you have Mail app installed.", comment: "")
}
}
}
| gpl-3.0 |
apple/swift-format | Tests/SwiftFormatRulesTests/OneVariableDeclarationPerLineTests.swift | 1 | 5945 | import SwiftFormatRules
final class OneVariableDeclarationPerLineTests: LintOrFormatRuleTestCase {
func testMultipleVariableBindings() {
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
var a = 0, b = 2, (c, d) = (0, "h")
let e = 0, f = 2, (g, h) = (0, "h")
var x: Int { return 3 }
let a, b, c: Int
var j: Int, k: String, l: Float
""",
expected:
"""
var a = 0
var b = 2
var (c, d) = (0, "h")
let e = 0
let f = 2
let (g, h) = (0, "h")
var x: Int { return 3 }
let a: Int
let b: Int
let c: Int
var j: Int
var k: String
var l: Float
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 1, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 2, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 4, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 5, column: 1)
}
func testNestedVariableBindings() {
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
var x: Int = {
let y = 5, z = 10
return z
}()
func foo() {
let x = 4, y = 10
}
var x: Int {
let y = 5, z = 10
return z
}
var a: String = "foo" {
didSet {
let b, c: Bool
}
}
let
a: Int = {
let p = 10, q = 20
return p * q
}(),
b: Int = {
var s: Int, t: Double
return 20
}()
""",
expected:
"""
var x: Int = {
let y = 5
let z = 10
return z
}()
func foo() {
let x = 4
let y = 10
}
var x: Int {
let y = 5
let z = 10
return z
}
var a: String = "foo" {
didSet {
let b: Bool
let c: Bool
}
}
let
a: Int = {
let p = 10
let q = 20
return p * q
}()
let
b: Int = {
var s: Int
var t: Double
return 20
}()
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 2, column: 3)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 7, column: 3)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 11, column: 3)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 17, column: 5)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 21, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 23, column: 5)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 27, column: 5)
}
func testMixedInitializedAndTypedBindings() {
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
var a = 5, b: String
let c: Int, d = "d", e = "e", f: Double
""",
expected:
"""
var a = 5
var b: String
let c: Int
let d = "d"
let e = "e"
let f: Double
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 1, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 2, column: 1)
}
func testCommentPrecedingDeclIsNotRepeated() {
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
// Comment
let a, b, c: Int
""",
expected:
"""
// Comment
let a: Int
let b: Int
let c: Int
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 2, column: 1)
}
func testCommentsPrecedingBindingsAreKept() {
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
let /* a */ a, /* b */ b, /* c */ c: Int
""",
expected:
"""
let /* a */ a: Int
let /* b */ b: Int
let /* c */ c: Int
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 1, column: 1)
}
func testInvalidBindingsAreNotDestroyed() {
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
let a, b, c = 5
let d, e
let f, g, h: Int = 5
let a: Int, b, c = 5, d, e: Int
""",
expected:
"""
let a, b, c = 5
let d, e
let f, g, h: Int = 5
let a: Int
let b, c = 5
let d: Int
let e: Int
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 1, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 2, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 3, column: 1)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 4, column: 1)
}
func testMultipleBindingsWithAccessorsAreCorrected() {
// Swift parses multiple bindings with accessors but forbids them at a later
// stage. That means that if the individual bindings would be correct in
// isolation then we can correct them, which is kind of nice.
XCTAssertFormatting(
OneVariableDeclarationPerLine.self,
input:
"""
var x: Int { return 10 }, y = "foo" { didSet { print("changed") } }
""",
expected:
"""
var x: Int { return 10 }
var y = "foo" { didSet { print("changed") } }
""",
checkForUnassertedDiagnostics: true
)
XCTAssertDiagnosed(.onlyOneVariableDeclaration, line: 1, column: 1)
}
}
| apache-2.0 |
huang1988519/WechatArticles | WechatArticles/WechatArticles/Library/Timepiece/NSTimeInterval+Timepiece.swift | 6 | 1614 | //
// NSTimeInterval+Timepiece.swift
// Timepiece
//
// Created by Mattijs on 10/05/15.
// Copyright (c) 2015 Naoto Kaneko. All rights reserved.
//
import Foundation
/**
This extension is deprecated in 0.4.1 and will be obsoleted in 0.5.0.
The conversion of Duration into NSTimeInterval is performed under incorrect assumption that 1 month is always equal to 30 days.
Therefore, The comparison between Duration and NSTimeInterval is also incorrect.
*/
public func < (lhs: NSTimeInterval, rhs: Duration) -> Bool {
return lhs < rhs.interval
}
public func < (lhs: Duration, rhs: NSTimeInterval) -> Bool {
return lhs.interval < rhs
}
public func > (lhs: NSTimeInterval, rhs: Duration) -> Bool {
return lhs > rhs.interval
}
public func > (lhs: Duration, rhs: NSTimeInterval) -> Bool {
return lhs.interval > rhs
}
public func == (lhs: NSTimeInterval, rhs: Duration) -> Bool {
return lhs == rhs.interval
}
public func == (lhs: Duration, rhs: NSTimeInterval) -> Bool {
return lhs.interval == rhs
}
public func >= (lhs: NSTimeInterval, rhs: Duration) -> Bool {
return lhs >= rhs.interval
}
public func >= (lhs: Duration, rhs: NSTimeInterval) -> Bool {
return lhs.interval >= rhs
}
public func <= (lhs: NSTimeInterval, rhs: Duration) -> Bool {
return lhs <= rhs.interval
}
public func <= (lhs: Duration, rhs: NSTimeInterval) -> Bool {
return lhs.interval <= rhs
}
public func != (lhs: NSTimeInterval, rhs: Duration) -> Bool {
return lhs != rhs.interval
}
public func != (lhs: Duration, rhs: NSTimeInterval) -> Bool {
return lhs.interval != rhs
} | apache-2.0 |
songzhw/2iOS | iOS_Swift/iOS_Swift/biz/basiclesson/BillCaculatorViewController.swift | 1 | 1323 | import UIKit
class BillCaculatorViewController: UIViewController {
@IBOutlet weak var tfTotal: UITextField!
@IBOutlet weak var lblSplit: UILabel!
weak var btnPrevSelected : UIButton? //让上一个selected的变为不可选. 是动态的. 所以不用IBOutlet
var percentage : Float = 0
var headcount : Int = 2
@IBAction func tipPressed(_ sender: UIButton) {
guard btnPrevSelected !== sender else {return}
btnPrevSelected?.isSelected = false
sender.isSelected = true
btnPrevSelected = sender
percentage = Float(sender.currentTitle!.dropLast())!/100 //去除"%"后再参与运算
}
@IBAction func splitPressed(_ sender: UIStepper) {
headcount = Int(sender.value)
lblSplit.text = String(headcount)
}
@IBAction func calculatePressed(_ sender: UIButton) {
self.performSegue(withIdentifier: "BillResult", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "BillResult" {
guard tfTotal.text != nil else {return}
let vc2 = segue.destination as! BillResultViewController
vc2.total = Float(tfTotal.text!)!
vc2.headcount = headcount
vc2.tipPercentage = percentage
print("totoal = \(vc2.total), head = \(headcount)")
}
}
}
| apache-2.0 |
lukaskollmer/RuntimeKit | RuntimeKit/Sources/Classes.swift | 1 | 1684 | //
// Classes.swift
// RuntimeKit
//
// Created by Lukas Kollmer on 31.03.17.
// Copyright © 2017 Lukas Kollmer. All rights reserved.
//
import Foundation
public extension Runtime {
/// Register a new class with the Objective-C runtime
///
/// - Parameters:
/// - name: The name of the new class
/// - superclass: The superclass. Defaults to `NSObject`
/// - protocols: All protocols the class should adopt
/// - Returns: The new class
/// - Throws: `RuntimeKitError.classnameAlreadyTaken` if the classname isn't available anymore, `RuntimeKitError.unableToCreateClass` if there was an error registering the new class
public static func createClass(_ name: String, superclass: AnyClass = NSObject.self, protocols: [Protocol] = []) throws -> NSObject.Type {
guard !Runtime.classExists(name) else {
throw RuntimeKitError.classnameAlreadyTaken
}
guard let newClass = objc_allocateClassPair(superclass, name.cString(using: .utf8)!, 0) else {
throw RuntimeKitError.unableToCreateClass
}
objc_registerClassPair(newClass)
protocols.forEach {
class_addProtocol(newClass, $0)
}
guard let castedClass = newClass as? NSObject.Type else {
fatalError("wtf")
}
return castedClass
}
/// Destroys a class and its associated metaclass.
///
/// - Parameter cls: The class to be destroyed. This class must have been created using RuntimeKit.createClass(_:)
public static func destroy(class cls: NSObject.Type) {
objc_disposeClassPair(cls)
}
}
| mit |
vamsirajendra/firefox-ios | Client/Frontend/Home/BookmarksPanel.swift | 2 | 14566 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Storage
import Shared
import XCGLogger
private let log = Logger.browserLogger
let BookmarkStatusChangedNotification = "BookmarkStatusChangedNotification"
struct BookmarksPanelUX {
private static let BookmarkFolderHeaderViewChevronInset: CGFloat = 10
private static let BookmarkFolderChevronSize: CGFloat = 20
private static let BookmarkFolderChevronLineWidth: CGFloat = 4.0
private static let BookmarkFolderTextColor = UIColor(red: 92/255, green: 92/255, blue: 92/255, alpha: 1.0)
private static let BookmarkFolderTextFont = UIFont.systemFontOfSize(UIConstants.DefaultMediumFontSize, weight: UIFontWeightMedium)
}
class BookmarksPanel: SiteTableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate? = nil
var source: BookmarksModel?
var parentFolders = [BookmarkFolder]()
var bookmarkFolder = BookmarkRoots.MobileFolderGUID
private let BookmarkFolderCellIdentifier = "BookmarkFolderIdentifier"
private let BookmarkFolderHeaderViewIdentifier = "BookmarkFolderHeaderIdentifier"
private lazy var defaultIcon: UIImage = {
return UIImage(named: "defaultFavicon")!
}()
init() {
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil)
self.tableView.registerClass(BookmarkFolderTableViewCell.self, forCellReuseIdentifier: BookmarkFolderCellIdentifier)
self.tableView.registerClass(BookmarkFolderTableViewHeader.self, forHeaderFooterViewReuseIdentifier: BookmarkFolderHeaderViewIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// if we've not already set a source for this panel fetch a new model
// otherwise just use the existing source to select a folder
guard let source = self.source else {
// Get all the bookmarks split by folders
profile.bookmarks.modelForFolder(bookmarkFolder).upon(onModelFetched)
return
}
source.selectFolder(bookmarkFolder).upon(onModelFetched)
}
func notificationReceived(notification: NSNotification) {
switch notification.name {
case NotificationFirefoxAccountChanged:
self.reloadData()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
private func onModelFetched(result: Maybe<BookmarksModel>) {
guard let model = result.successValue else {
self.onModelFailure(result.failureValue)
return
}
self.onNewModel(model)
}
private func onNewModel(model: BookmarksModel) {
self.source = model
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
private func onModelFailure(e: Any) {
log.error("Error: failed to get data: \(e)")
}
override func reloadData() {
self.source?.reloadData().upon(onModelFetched)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return source?.current.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let source = source, bookmark = source.current[indexPath.row] else { return super.tableView(tableView, cellForRowAtIndexPath: indexPath) }
let cell: UITableViewCell
if let _ = bookmark as? BookmarkFolder {
cell = tableView.dequeueReusableCellWithIdentifier(BookmarkFolderCellIdentifier, forIndexPath: indexPath)
} else {
cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
if let url = bookmark.favicon?.url.asURL where url.scheme == "asset" {
cell.imageView?.image = UIImage(named: url.host!)
} else {
cell.imageView?.setIcon(bookmark.favicon, withPlaceholder: self.defaultIcon)
}
}
switch (bookmark) {
case let item as BookmarkItem:
if item.title.isEmpty {
cell.textLabel?.text = item.url
} else {
cell.textLabel?.text = item.title
}
default:
// Bookmark folders don't have a good fallback if there's no title. :(
cell.textLabel?.text = bookmark.title
}
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? BookmarkFolderTableViewCell {
cell.textLabel?.font = BookmarksPanelUX.BookmarkFolderTextFont
}
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// Don't show a header for the root
if source == nil || parentFolders.isEmpty {
return nil
}
guard let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(BookmarkFolderHeaderViewIdentifier) as? BookmarkFolderTableViewHeader else { return nil }
// register as delegate to ensure we get notified when the user interacts with this header
if header.delegate == nil {
header.delegate = self
}
if parentFolders.count == 1 {
header.textLabel?.text = NSLocalizedString("Bookmarks", comment: "Panel accessibility label")
} else if let parentFolder = parentFolders.last {
header.textLabel?.text = parentFolder.title
}
return header
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// Don't show a header for the root. If there's no root (i.e. source == nil), we'll also show no header.
if source == nil || parentFolders.isEmpty {
return 0
}
return SiteTableViewControllerUX.RowHeight
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? BookmarkFolderTableViewHeader {
// for some reason specifying the font in header view init is being ignored, so setting it here
header.textLabel?.font = BookmarksPanelUX.BookmarkFolderTextFont
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if let source = source {
let bookmark = source.current[indexPath.row]
switch (bookmark) {
case let item as BookmarkItem:
homePanelDelegate?.homePanel(self, didSelectURL: NSURL(string: item.url)!, visitType: VisitType.Bookmark)
break
case let folder as BookmarkFolder:
let nextController = BookmarksPanel()
nextController.parentFolders = parentFolders + [source.current]
nextController.bookmarkFolder = folder.guid
nextController.source = source
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
self.navigationController?.pushViewController(nextController, animated: true)
break
default:
// Weird.
break // Just here until there's another executable statement (compiler requires one).
}
}
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// Intentionally blank. Required to use UITableViewRowActions
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if source == nil {
return .None
}
if source!.current.itemIsEditableAtIndex(indexPath.row) ?? false {
return .Delete
}
return .None
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
if source == nil {
return [AnyObject]()
}
let title = NSLocalizedString("Delete", tableName: "BookmarkPanel", comment: "Action button for deleting bookmarks in the bookmarks panel.")
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: title, handler: { (action, indexPath) in
if let bookmark = self.source?.current[indexPath.row] {
// Why the dispatches? Because we call success and failure on the DB
// queue, and so calling anything else that calls through to the DB will
// deadlock. This problem will go away when the bookmarks API switches to
// Deferred instead of using callbacks.
// TODO: it's now time for this.
self.profile.bookmarks.remove(bookmark).uponQueue(dispatch_get_main_queue()) { res in
if let err = res.failureValue {
self.onModelFailure(err)
return
}
dispatch_async(dispatch_get_main_queue()) {
self.source?.reloadData().upon {
guard let model = $0.successValue else {
self.onModelFailure($0.failureValue)
return
}
dispatch_async(dispatch_get_main_queue()) {
tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
self.source = model
tableView.endUpdates()
NSNotificationCenter.defaultCenter().postNotificationName(BookmarkStatusChangedNotification, object: bookmark, userInfo:["added":false])
}
}
}
}
}
})
return [delete]
}
}
private protocol BookmarkFolderTableViewHeaderDelegate {
func didSelectHeader()
}
extension BookmarksPanel: BookmarkFolderTableViewHeaderDelegate {
private func didSelectHeader() {
self.navigationController?.popViewControllerAnimated(true)
}
}
class BookmarkFolderTableViewCell: TwoLineTableViewCell {
private let ImageMargin: CGFloat = 12
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = SiteTableViewControllerUX.HeaderBackgroundColor
textLabel?.backgroundColor = UIColor.clearColor()
textLabel?.tintColor = BookmarksPanelUX.BookmarkFolderTextColor
textLabel?.font = BookmarksPanelUX.BookmarkFolderTextFont
imageView?.image = UIImage(named: "bookmarkFolder")
let chevron = ChevronView(direction: .Right)
chevron.tintColor = BookmarksPanelUX.BookmarkFolderTextColor
chevron.frame = CGRectMake(0, 0, BookmarksPanelUX.BookmarkFolderChevronSize, BookmarksPanelUX.BookmarkFolderChevronSize)
chevron.lineWidth = BookmarksPanelUX.BookmarkFolderChevronLineWidth
accessoryView = chevron
separatorInset = UIEdgeInsetsZero
}
override func layoutSubviews() {
super.layoutSubviews()
// doing this here as TwoLineTableViewCell changes the imageView frame in it's layoutSubviews and we have to make sure it is right
if let imageSize = imageView?.image?.size {
imageView?.frame = CGRectMake(ImageMargin, (frame.height - imageSize.width) / 2, imageSize.width, imageSize.height)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private class BookmarkFolderTableViewHeader : UITableViewHeaderFooterView {
var delegate: BookmarkFolderTableViewHeaderDelegate?
lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = UIConstants.HighlightBlue
return label
}()
lazy var chevron: ChevronView = {
let chevron = ChevronView(direction: .Left)
chevron.tintColor = UIConstants.HighlightBlue
chevron.lineWidth = BookmarksPanelUX.BookmarkFolderChevronLineWidth
return chevron
}()
override var textLabel: UILabel? {
return titleLabel
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
userInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "viewWasTapped:")
tapGestureRecognizer.numberOfTapsRequired = 1
addGestureRecognizer(tapGestureRecognizer)
contentView.addSubview(chevron)
contentView.addSubview(titleLabel)
chevron.snp_makeConstraints { make in
make.left.equalTo(contentView).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.centerY.equalTo(contentView)
make.size.equalTo(BookmarksPanelUX.BookmarkFolderChevronSize)
}
titleLabel.snp_makeConstraints { make in
make.left.equalTo(chevron.snp_right).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.right.equalTo(contentView).offset(-BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.centerY.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func viewWasTapped(gestureRecognizer: UITapGestureRecognizer) {
delegate?.didSelectHeader()
}
}
| mpl-2.0 |
ObjectAlchemist/OOUIKit | Sources/_UIKitDelegate/UITableViewDelegate/ConfiguringRowsForTheTableView/UITableViewDelegateConfigurationPrinting.swift | 1 | 2423 | //
// UITableViewDelegateConfigurationPrinting.swift
// OOUIKit
//
// Created by Karsten Litsche on 04.11.17.
//
import UIKit
public final class UITableViewDelegateConfigurationPrinting: NSObject, UITableViewDelegate {
// MARK: - init
convenience override init() {
fatalError("Not supported!")
}
public init(_ decorated: UITableViewDelegate, filterKey: String = "") {
self.decorated = decorated
// add space if exist to separate following log
self.filterKey = filterKey.count == 0 ? "" : "\(filterKey) "
}
// MARK: - protocol: UITableViewDelegate
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
printUI("\(filterKey)table heightForRowAt (\(indexPath.section)-\(indexPath.row)) called")
return decorated.tableView?(tableView, heightForRowAt: indexPath) ?? UITableView.automaticDimension
}
public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
printUI("\(filterKey)table estimatedHeightForRowAt (\(indexPath.section)-\(indexPath.row)) called")
return decorated.tableView?(tableView, estimatedHeightForRowAt: indexPath) ?? UITableView.automaticDimension
}
public func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
printUI("\(filterKey)table indentationLevelForRowAt (\(indexPath.section)-\(indexPath.row)) called")
return decorated.tableView?(tableView, indentationLevelForRowAt: indexPath) ?? 1
}
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
printUI("\(filterKey)table willDisplayCellForRowAt (\(indexPath.section)-\(indexPath.row)) called")
decorated.tableView?(tableView, willDisplay: cell, forRowAt: indexPath)
}
public func tableView(_ tableView: UITableView, shouldSpringLoadRowAt indexPath: IndexPath, with context: UISpringLoadedInteractionContext) -> Bool {
printUI("\(filterKey)table shouldSpringLoadRowAt (\(indexPath.section)-\(indexPath.row)) called")
return decorated.tableView?(tableView, shouldSpringLoadRowAt: indexPath, with: context) ?? true
}
// MARK: - private
private let decorated: UITableViewDelegate
private let filterKey: String
}
| mit |
eofster/Telephone | Telephone/ApplicationDataLocations.swift | 1 | 785 | //
// ApplicationDataLocations.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Foundation
protocol ApplicationDataLocations {
func root() -> URL
func logs() -> URL
func callHistories() -> URL
}
| gpl-3.0 |
PeeJWeeJ/SwiftyDevice | SwiftyDevice/AppDelegate.swift | 1 | 2081 | //
// AppDelegate.swift
// SwiftyDevice
//
// Created by Paul Fechner on 9/14/16.
// Copyright © 2016 PeeJWeeJ. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
martinomamic/CarBooking | CarBooking/Services/Booking/BookingService.swift | 1 | 1951 | //
// BookingService.swift
// CarBooking
//
// Created by Martino Mamic on 29/07/2017.
// Copyright © 2017 Martino Mamic. All rights reserved.
//
import UIKit
import Foundation
class BookingService: BookingsStoreProtocol {
private let service = WebService()
func createBooking(newBooking: Booking, completionHandler: @escaping (() throws -> Booking?) -> Void) {
var json = RequestDictionary()
json["carId"] = "\(newBooking.car.id)"
json["startDate"] = newBooking.startDate.fullDateFormat()
json["endDate"] = newBooking.endDate.fullDateFormat()
json["isExpired"] = "\(false)"
json["duration"] = "\(newBooking.duration)"
service.create(params: json, resource: BookingResources.newBooking) { (createdBooking, error, response) in
if let booking = createdBooking {
completionHandler { return booking }
} else {
print(error ?? "no error")
print(response ?? "no response")
}
}
}
func fetchBookings(completionHandler: @escaping (() throws -> [Booking]) -> Void) {
service.get(resource: BookingResources.allBookings) { (bookingsArray, error, response) in
if let bookings = bookingsArray {
print(bookings)
for b in bookings {
print(b)
}
completionHandler { return bookings }
}
}
}
func fetchBooking(id: String, completionHandler: @escaping (() throws -> Booking?) -> Void) {
service.get(resource: BookingResources.fetchBooking(id)) { (fetchedBooking, error, response) in
if let booking = fetchedBooking {
print(booking)
completionHandler { return booking }
} else {
print(error ?? "no error")
print(response ?? "no response")
}
}
}
}
| mit |
Tj3n/TVNExtensions | UIKit/UITableView.swift | 1 | 1821 | //
// UITableViewExtension.swift
// MerchantDashboard
//
// Created by Tien Nhat Vu on 3/17/16.
// Copyright © 2016 Tien Nhat Vu. All rights reserved.
//
import Foundation
import UIKit
extension UITableView {
/// Auto dequeue cell with custom cell class, the identifier must have the same name as the cell class
///
/// - Parameter type: Custom cell class
/// - Returns: Custom cell
public func dequeueReusableCell<T: UITableViewCell>(_ type: T.Type) -> T {
guard let cell = self.dequeueReusableCell(withIdentifier: String(describing: type)) as? T else {
fatalError("\(String(describing: type)) cell could not be instantiated because it was not found on the tableView")
}
return cell
}
/// Auto dequeue cell with custom cell class, the identifier must have the same name as the cell class
///
/// - Parameter type: Custom cell class
/// - Returns: Custom cell
public func dequeueReusableCell<T: UITableViewCell>(_ type: T.Type, for indexPath: IndexPath) -> T {
guard let cell = self.dequeueReusableCell(withIdentifier: String(describing: type), for: indexPath) as? T else {
fatalError("\(String(describing: type)) cell could not be instantiated because it was not found on the tableView")
}
return cell
}
/// Check if tableView is empty
public var isEmpty: Bool {
get {
return self.visibleCells.isEmpty
}
}
/// Get indexPath from cell's subview
///
/// - Parameter subview: cell's subview
/// - Returns: cell's indexPath
public func indexPathForRowSubview(_ subview: UIView) -> IndexPath? {
let point = subview.convert(subview.frame, to: self)
return self.indexPathForRow(at: point.origin)
}
}
| mit |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/InsertLinkViewController.swift | 3 | 3701 | import UIKit
protocol InsertLinkViewControllerDelegate: AnyObject {
func insertLinkViewController(_ insertLinkViewController: InsertLinkViewController, didTapCloseButton button: UIBarButtonItem)
func insertLinkViewController(_ insertLinkViewController: InsertLinkViewController, didInsertLinkFor page: String, withLabel label: String?)
}
class InsertLinkViewController: UIViewController {
weak var delegate: InsertLinkViewControllerDelegate?
private var theme = Theme.standard
private let dataStore: MWKDataStore
typealias Link = SectionEditorWebViewMessagingController.Link
private let link: Link
private let siteURL: URL?
init(link: Link, siteURL: URL?, dataStore: MWKDataStore) {
self.link = link
self.siteURL = siteURL
self.dataStore = dataStore
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var closeButton: UIBarButtonItem = {
let closeButton = UIBarButtonItem.wmf_buttonType(.X, target: self, action: #selector(delegateCloseButtonTap(_:)))
closeButton.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
return closeButton
}()
private lazy var searchViewController: SearchViewController = {
let searchViewController = SearchViewController()
searchViewController.dataStore = dataStore
searchViewController.siteURL = siteURL
searchViewController.searchTerm = link.page
searchViewController.areRecentSearchesEnabled = false
searchViewController.shouldBecomeFirstResponder = true
searchViewController.dataStore = SessionSingleton.sharedInstance()?.dataStore
searchViewController.shouldShowCancelButton = false
searchViewController.delegate = self
searchViewController.delegatesSelection = true
searchViewController.showLanguageBar = false
searchViewController.search()
return searchViewController
}()
override func viewDidLoad() {
super.viewDidLoad()
title = CommonStrings.insertLinkTitle
navigationItem.leftBarButtonItem = closeButton
let navigationController = WMFThemeableNavigationController(rootViewController: searchViewController)
navigationController.isNavigationBarHidden = true
wmf_add(childController: navigationController, andConstrainToEdgesOfContainerView: view)
apply(theme: theme)
}
@objc private func delegateCloseButtonTap(_ sender: UIBarButtonItem) {
delegate?.insertLinkViewController(self, didTapCloseButton: sender)
}
override func accessibilityPerformEscape() -> Bool {
delegate?.insertLinkViewController(self, didTapCloseButton: closeButton)
return true
}
}
extension InsertLinkViewController: ArticleCollectionViewControllerDelegate {
func articleCollectionViewController(_ articleCollectionViewController: ArticleCollectionViewController, didSelectArticleWith articleURL: URL, at indexPath: IndexPath) {
guard let title = articleURL.wmf_title else {
return
}
delegate?.insertLinkViewController(self, didInsertLinkFor: title, withLabel: nil)
}
}
extension InsertLinkViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.inputAccessoryBackground
view.layer.shadowColor = theme.colors.shadow.cgColor
closeButton.tintColor = theme.colors.primaryText
searchViewController.apply(theme: theme)
}
}
| mit |
chrisjmendez/swift-exercises | Authentication/BasicDropBox/BasicDropBox/DropboxUtil.swift | 1 | 1637 | //
// DropboxUtil.swift
// BasicDropBox
//
// Created by Chris on 1/16/16.
// Copyright © 2016 Chris Mendez. All rights reserved.
//
// https://www.dropbox.com/developers/documentation/swift#tutorial
import UIKit
import SwiftyDropbox
protocol DropboxUtilDelegate {
func didAuthenticate(success:Bool)
}
class DropboxUtil {
let DROPBOX_FOLDER_PATH = "SwiftHero"
var client:DropboxClient?
var delegate:DropboxUtilDelegate? = nil
internal init(){
//super.init()
if let cli = Dropbox.authorizedClient {
client = cli
print("A")
delegate?.didAuthenticate(true)
print("B")
} else {
delegate?.didAuthenticate(false)
}
}
func getUserAccount(){
print("getUserAccount")
//A. Get the current user's account info
client?.users.getCurrentAccount().response({ (response, error) -> Void in
print("*** Get current account ***")
if error != nil {
print("Error:", error!)
}
if let account = response {
print("Hello \(account.name.givenName)!")
}
})
}
func listFolder(){
client?.files.listFolder(path: "./").response( { (response, error) -> Void in
print("*** List folder ***")
if let result = response {
print("Folder contents:")
for entry in result.entries {
print(entry.name)
}
} else {
print(error!)
}
})
}
} | mit |
TieShanWang/KKAutoScrollView | KKAutoScrollView/KKAutoScrollView/KKAutoCollectionViewCell.swift | 1 | 1556 | //
// KKAutoCollectionViewCell.swift
// KKAutoScrollController
//
// Created by KING on 2017/1/4.
// Copyright © 2017年 KING. All rights reserved.
//
import UIKit
import Security
let KKAutoCollectionViewCellReuseID = "KKAutoCollectionViewCellReuseID"
class KKAutoCollectionViewCell: UICollectionViewCell {
var imageView: UIImageView!
var titleLabel: UILabel!
var downloadURL: String?
var model: KKAutoScrollViewModel?
override init(frame: CGRect) {
super.init(frame: frame)
self.imageView = UIImageView()
self.titleLabel = UILabel.init()
self.contentView.addSubview(self.titleLabel)
self.contentView.addSubview(self.imageView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func reloadData() {
if let m = self.model {
self.showData(m)
}
}
func showData(_ data: KKAutoScrollViewModel) {
self.model = data
let url = data.url
self.downloadURL = url
data.downModel { [weak self] (img) in
DispatchQueue.main.async {
self?.imageView.image = img
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.imageView.frame = self.contentView.bounds
}
}
| mit |
davedufresne/SwiftParsec | Sources/SwiftParsec/TokenParser.swift | 1 | 42546 | //==============================================================================
// TokenParser.swift
// SwiftParsec
//
// Created by David Dufresne on 2015-10-05.
// Copyright © 2015 David Dufresne. All rights reserved.
//
// A helper module to parse lexical elements (tokens). See the initializer for
// the `TokenParser` structure for a description of how to use it.
// Operator implementations for the `Message` type.
//==============================================================================
import func Foundation.pow
//==============================================================================
/// Types implementing this protocol hold lexical parsers.
public protocol TokenParser {
/// The state supplied by the user.
associatedtype UserState
/// Language definition parameterizing the lexer.
var languageDefinition: LanguageDefinition<UserState> { get }
/// This lexeme parser parses a legal identifier. Returns the identifier
/// string. This parser will fail on identifiers that are reserved words.
/// Legal identifier (start) characters and reserved words are defined in
/// the `LanguageDefinition` that is passed to the initializer of this token
/// parser. An `identifier` is treated as a single token using
/// `GenericParser.attempt`.
var identifier: GenericParser<String, UserState, String> { get }
/// The lexeme parser `reservedName(name)` parses `symbol(name)`, but it
/// also checks that the `name` is not a prefix of a valid identifier. A
/// _reserved_ word is treated as a single token using
/// `GenericParser.attempt`.
///
/// - parameter name: The reserved name to parse.
/// - returns: A parser returning nothing.
func reservedName(_ name: String) -> GenericParser<String, UserState, ()>
/// This lexeme parser parses a legal operator and returns the name of the
/// operator. This parser will fail on any operators that are reserved
/// operators. Legal operator (start) characters and reserved operators are
/// defined in the `LanguageDefinition` that is passed to the initializer of
/// this token parser. An 'operator' is treated as a single token using
/// `GenericParser.attempt`.
var legalOperator: GenericParser<String, UserState, String> { get }
/// The lexeme parser `reservedOperator(name)` parses `symbol(name)`, but it
/// also checks that the `name` is not a prefix of a valid operator. A
/// 'reservedOperator' is treated as a single token using
/// `GenericParser.attempt`.
///
/// - parameter name: The operator name.
/// - returns: A parser returning nothing.
func reservedOperator(
_ name: String
) -> GenericParser<String, UserState, ()>
/// This lexeme parser parses a single literal character and returns the
/// literal character value. This parser deals correctly with escape
/// sequences.
var characterLiteral: GenericParser<String, UserState, Character> { get }
/// This lexeme parser parses a literal string and returns the literal
/// string value. This parser deals correctly with escape sequences and
/// gaps.
var stringLiteral: GenericParser<String, UserState, String> { get }
/// This lexeme parser parses a natural number (a positive whole number) and
/// returns the value of the number. The number can be specified in
/// 'decimal', 'hexadecimal' or 'octal'.
var natural: GenericParser<String, UserState, Int> { get }
/// This lexeme parser parses an integer (a whole number). This parser is
/// like `natural` except that it can be prefixed with sign (i.e. "-" or
/// "+"). It returns the value of the number. The number can be specified in
/// 'decimal', 'hexadecimal' or 'octal'.
var integer: GenericParser<String, UserState, Int> { get }
/// This lexeme parser parses an integer (a whole number). It is like
/// `integer` except that it can parse bigger numbers. Returns the value of
/// the number as a `Double`.
var integerAsFloat: GenericParser<String, UserState, Double> { get }
/// This lexeme parser parses a floating point value and returns the value
/// of the number.
var float: GenericParser<String, UserState, Double> { get }
/// This lexeme parser parses either `integer` or a `float` and returns the
/// value of the number. This parser deals with any overlap in the grammar
/// rules for integers and floats.
var number: GenericParser<String, UserState, Either<Int, Double>> { get }
/// Parses a positive whole number in the decimal system. Returns the value
/// of the number.
static var decimal: GenericParser<String, UserState, Int> { get }
/// Parses a positive whole number in the hexadecimal system. The number
/// should be prefixed with "x" or "X". Returns the value of the number.
static var hexadecimal: GenericParser<String, UserState, Int> { get }
/// Parses a positive whole number in the octal system. The number should be
/// prefixed with "o" or "O". Returns the value of the number.
static var octal: GenericParser<String, UserState, Int> { get }
/// Lexeme parser `symbol(str)` parses `str` and skips trailing white space.
///
/// - parameter name: The name of the symbol to parse.
/// - returns: `name`.
func symbol(_ name: String) -> GenericParser<String, UserState, String>
/// `lexeme(parser)` first applies `parser` and than the `whiteSpace`
/// parser, returning the value of `parser`. Every lexical token (lexeme) is
/// defined using `lexeme`, this way every parse starts at a point without
/// white space. Parsers that use `lexeme` are called _lexeme_ parsers in
/// this document.
///
/// The only point where the 'whiteSpace' parser should be called explicitly
/// is the start of the main parser in order to skip any leading white
/// space.
///
/// let mainParser = sum <^> whiteSpace *> lexeme(digit) <* eof
///
/// - parameter parser: The parser to transform in a 'lexeme'.
/// - returns: The value of `parser`.
func lexeme<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result>
/// Parses any white space. White space consists of _zero_ or more
/// occurrences of a 'space', a line comment or a block (multiline) comment.
/// Block comments may be nested. How comments are started and ended is
/// defined in the `LanguageDefinition` that is passed to the initializer of
/// this token parser.
var whiteSpace: GenericParser<String, UserState, ()> { get }
/// Lexeme parser `parentheses(parser)` parses `parser` enclosed in
/// parentheses, returning the value of `parser`.
///
/// - parameter parser: The parser applied between the parentheses.
/// - returns: The value of `parser`.
func parentheses<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result>
/// Lexeme parser `braces(parser)` parses `parser` enclosed in braces "{"
/// and "}", returning the value of `parser`.
///
/// - parameter parser: The parser applied between the braces.
/// - returns: The value of `parser`.
func braces<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result>
/// Lexeme parser `angles(parser)` parses `parser` enclosed in angle
/// brackets "<" and ">", returning the value of `parser`.
///
/// - parameter parser: The parser applied between the angles.
/// - returns: The value of `parser`.
func angles<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result>
/// Lexeme parser `brackets(parser)` parses `parser` enclosed in brackets
/// "[" and "]", returning the value of `parser`.
///
/// - parameter parser: The parser applied between the brackets.
/// - returns: The value of `parser`.
func brackets<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result>
/// Lexeme parser `semicolon` parses the character ";" and skips any
/// trailing white space. Returns the string ";".
var semicolon: GenericParser<String, UserState, String> { get }
/// Lexeme parser `comma` parses the character "," and skips any trailing
/// white space. Returns the string ",".
var comma: GenericParser<String, UserState, String> { get }
/// Lexeme parser `colon` parses the character ":" and skips any trailing
/// white space. Returns the string ":".
var colon: GenericParser<String, UserState, String> { get }
/// Lexeme parser `dot` parses the character "." and skips any trailing
/// white space. Returns the string ".".
var dot: GenericParser<String, UserState, String> { get }
/// Lexeme parser `semicolonSeperated(parser)` parses _zero_ or more
/// occurrences of `parser` separated by `semicolon`. Returns an array of
/// values returned by `parser`.
///
/// - parameter parser: The parser applied between semicolons.
/// - returns: An array of values returned by `parser`.
func semicolonSeparated<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]>
/// Lexeme parser `semicolonSeperated1(parser)` parses _one_ or more
/// occurrences of `parser` separated by `semicolon`. Returns an array of
/// values returned by `parser`.
///
/// - parameter parser: The parser applied between semicolons.
/// - returns: An array of values returned by `parser`.
func semicolonSeparated1<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]>
/// Lexeme parser `commaSeparated(parser)` parses _zero_ or more occurrences
/// of `parser` separated by `comma`. Returns an array of values returned by
/// `parser`.
///
/// - parameter parser: The parser applied between commas.
/// - returns: An array of values returned by `parser`.
func commaSeparated<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]>
/// Lexeme parser `commaSeparated1(parser)` parses _one_ or more occurrences
/// of `parser` separated by `comma`. Returns an array of values returned by
/// `parser`.
///
/// - parameter parser: The parser applied between commas.
/// - returns: An array of values returned by `parser`.
func commaSeparated1<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]>
}
// Default implementation of the methods of the `TokenParser` parser type.
extension TokenParser {
// Type aliases used internally to simplify the code.
typealias StrParser = GenericParser<String, UserState, String>
typealias CharacterParser = GenericParser<String, UserState, Character>
typealias IntParser = GenericParser<String, UserState, Int>
typealias DoubleParser = GenericParser<String, UserState, Double>
typealias IntDoubleParser =
GenericParser<String, UserState, Either<Int, Double>>
typealias VoidParser = GenericParser<String, UserState, ()>
//
// Identifiers & Reserved words
//
/// This lexeme parser parses a legal identifier. Returns the identifier
/// string. This parser will fail on identifiers that are reserved words.
/// Legal identifier (start) characters and reserved words are defined in
/// the `LanguageDefinition` that is passed to the initializer of this token
/// parser. An `identifier` is treated as a single token using
/// `GenericParser.attempt`.
public var identifier: GenericParser<String, UserState, String> {
let langDef = languageDefinition
let ident: StrParser = langDef.identifierStart >>- { char in
langDef.identifierLetter(char).many >>- { chars in
let cs = chars.prepending(char)
return GenericParser(result: String(cs))
}
} <?> LocalizedString("identifier")
let identCheck: StrParser = ident >>- { name in
let reservedNames: Set<String>
let n: String
if langDef.isCaseSensitive {
reservedNames = langDef.reservedNames
n = name
} else {
reservedNames = langDef.reservedNames.map { $0.lowercased() }
n = name.lowercased()
}
guard !reservedNames.contains(n) else {
let reservedWordMsg = LocalizedString("reserved word ")
return GenericParser.unexpected(reservedWordMsg + name)
}
return GenericParser(result: name)
}
return lexeme(identCheck.attempt)
}
/// The lexeme parser `reservedName(name)` parses `symbol(name)`, but it
/// also checks that the `name` is not a prefix of a valid identifier. A
/// _reserved_ word is treated as a single token using
/// `GenericParser.attempt`.
///
/// - parameter name: The reserved name to parse.
/// - returns: A parser returning nothing.
public func reservedName(
_ name: String
) -> GenericParser<String, UserState, ()> {
let lastChar = name.last!
let reserved = caseString(name) *>
languageDefinition.identifierLetter(lastChar).noOccurence <?>
LocalizedString("end of ") + name
return lexeme(reserved.attempt)
}
//
// Operators & reserved operators
//
/// This lexeme parser parses a legal operator and returns the name of the
/// operator. This parser will fail on any operators that are reserved
/// operators. Legal operator (start) characters and reserved operators are
/// defined in the `LanguageDefinition` that is passed to the initializer of
/// this token parser. An 'operator' is treated as a single token using
/// `GenericParser.attempt`.
public var legalOperator: GenericParser<String, UserState, String> {
let langDef = languageDefinition
let op: StrParser = langDef.operatorStart >>- { char in
langDef.operatorLetter.many >>- { chars in
let cs = chars.prepending(char)
return GenericParser(result: String(cs))
}
} <?> LocalizedString("operator")
let opCheck: StrParser = op >>- { name in
guard !langDef.reservedOperators.contains(name) else {
let reservedOperatorMsg = LocalizedString("reserved operator ")
return GenericParser.unexpected(reservedOperatorMsg + name)
}
return GenericParser(result: name)
}
return lexeme(opCheck.attempt)
}
/// The lexeme parser `reservedOperator(name)` parses `symbol(name)`, but it
/// also checks that the `name` is not a prefix of a valid operator. A
/// 'reservedOperator' is treated as a single token using
/// `GenericParser.attempt`.
///
/// - parameter name: The operator name.
/// - returns: A parser returning nothing.
public func reservedOperator(
_ name: String
) -> GenericParser<String, UserState, ()> {
let op = VoidParser.string(name) *>
languageDefinition.operatorLetter.noOccurence <?>
LocalizedString("end of ") + name
return lexeme(op.attempt)
}
//
// Characters & Strings
//
/// This lexeme parser parses a single literal character and returns the
/// literal character value. This parser deals correctly with escape
/// sequences.
public var characterLiteral: GenericParser<String, UserState, Character> {
let characterLetter = CharacterParser.satisfy { char in
char != "'" && char != "\\" && char != substituteCharacter
}
let defaultCharEscape = GenericParser.character("\\") *>
GenericTokenParser<UserState>.escapeCode
let characterEscape =
languageDefinition.characterEscape ?? defaultCharEscape
let character = characterLetter <|> characterEscape <?>
LocalizedString("literal character")
let quote = CharacterParser.character("'")
let endOfCharMsg = LocalizedString("end of character")
return lexeme(character.between(quote, quote <?> endOfCharMsg)) <?>
LocalizedString("character")
}
/// This lexeme parser parses a literal string and returns the literal
/// string value. This parser deals correctly with escape sequences and
/// gaps.
public var stringLiteral: GenericParser<String, UserState, String> {
let stringLetter = CharacterParser.satisfy { char in
char != "\"" && char != "\\" && char != substituteCharacter
}
let escapeGap: GenericParser<String, UserState, Character?> =
GenericParser.space.many1 *> GenericParser.character("\\") *>
GenericParser(result: nil) <?>
LocalizedString("end of string gap")
let escapeEmpty: GenericParser<String, UserState, Character?> =
GenericParser.character("&") *> GenericParser(result: nil)
let characterEscape: GenericParser<String, UserState, Character?> =
GenericParser.character("\\") *>
(escapeGap <|> escapeEmpty <|>
GenericTokenParser.escapeCode.map { $0 })
let stringEscape =
languageDefinition.characterEscape?.map { $0 } ?? characterEscape
let stringChar = stringLetter.map { $0 } <|> stringEscape
let doubleQuote = CharacterParser.character("\"")
let endOfStringMsg = LocalizedString("end of string")
let string = stringChar.many.between(
doubleQuote, doubleQuote <?> endOfStringMsg
)
let literalString = string.map({ str in
str.reduce("") { (acc, char) in
guard let c = char else { return acc }
return acc.appending(c)
}
}) <?> LocalizedString("literal string")
return lexeme(literalString)
}
//
// Numbers
//
/// This lexeme parser parses a natural number (a positive whole number) and
/// returns the value of the number. The number can be specified in
/// 'decimal', 'hexadecimal' or 'octal'.
public var natural: GenericParser<String, UserState, Int> {
return lexeme(GenericTokenParser.naturalNumber) <?>
LocalizedString("natural")
}
/// This lexeme parser parses an integer (a whole number). This parser is
/// like `natural` except that it can be prefixed with sign (i.e. "-" or
/// "+"). It returns the value of the number. The number can be specified in
/// 'decimal', 'hexadecimal' or 'octal'.
public var integer: GenericParser<String, UserState, Int> {
let int = lexeme(GenericTokenParser.sign()) >>- { f in
GenericTokenParser.naturalNumber >>- {
GenericParser(result: f($0))
}
}
return lexeme(int) <?> LocalizedString("integer")
}
/// This lexeme parser parses an integer (a whole number). It is like
/// `integer` except that it can parse bigger numbers. Returns the value of
/// the number as a `Double`.
public var integerAsFloat: GenericParser<String, UserState, Double> {
let hexaPrefix = CharacterParser.oneOf(hexadecimalPrefixes)
let hexa = hexaPrefix *> GenericTokenParser.doubleWithBase(
16,
parser: GenericParser.hexadecimalDigit
)
let octPrefix = CharacterParser.oneOf(octalPrefixes)
let oct = octPrefix *> GenericTokenParser.doubleWithBase(
8,
parser: GenericParser.octalDigit
)
let decDigit = CharacterParser.decimalDigit
let dec = GenericTokenParser.doubleWithBase(10, parser: decDigit)
let zeroNumber = (GenericParser.character("0") *>
(hexa <|> oct <|> dec <|> GenericParser(result: 0))) <?> ""
let nat = zeroNumber <|> dec
let double = lexeme(GenericTokenParser.sign()) >>- { sign in
nat >>- { GenericParser(result: sign($0)) }
}
return lexeme(double) <?> LocalizedString("integer")
}
/// This lexeme parser parses a floating point value and returns the value
/// of the number.
public var float: GenericParser<String, UserState, Double> {
let intPart = GenericTokenParser<UserState>.doubleIntegerPart
let expPart = GenericTokenParser<UserState>.fractionalExponent
let f = intPart >>- { expPart($0) }
let double = lexeme(GenericTokenParser.sign()) >>- { sign in
f >>- { GenericParser(result: sign($0)) }
}
return lexeme(double) <?> LocalizedString("float")
}
/// This lexeme parser parses either `integer` or a `float` and returns the
/// value of the number. This parser deals with any overlap in the grammar
/// rules for integers and floats.
public var number: GenericParser<String, UserState, Either<Int, Double>> {
let intDouble = float.map({ Either.right($0) }).attempt <|>
integer.map({ Either.left($0) })
return lexeme(intDouble) <?> LocalizedString("number")
}
/// Parses a positive whole number in the decimal system. Returns the value
/// of the number.
public static var decimal: GenericParser<String, UserState, Int> {
return numberWithBase(10, parser: GenericParser.decimalDigit)
}
/// Parses a positive whole number in the hexadecimal system. The number
/// should be prefixed with "x" or "X". Returns the value of the number.
public static var hexadecimal: GenericParser<String, UserState, Int> {
return GenericParser.oneOf(hexadecimalPrefixes) *>
numberWithBase(16, parser: GenericParser.hexadecimalDigit)
}
/// Parses a positive whole number in the octal system. The number should be
/// prefixed with "o" or "O". Returns the value of the number.
public static var octal: GenericParser<String, UserState, Int> {
return GenericParser.oneOf(octalPrefixes) *>
numberWithBase(8, parser: GenericParser.octalDigit)
}
//
// White space & symbols
//
/// Lexeme parser `symbol(str)` parses `str` and skips trailing white space.
///
/// - parameter name: The name of the symbol to parse.
/// - returns: `name`.
public func symbol(
_ name: String
) -> GenericParser<String, UserState, String> {
return lexeme(StrParser.string(name))
}
/// `lexeme(parser)` first applies `parser` and than the `whiteSpace`
/// parser, returning the value of `parser`. Every lexical token (lexeme) is
/// defined using `lexeme`, this way every parse starts at a point without
/// white space. Parsers that use `lexeme` are called _lexeme_ parsers in
/// this document.
///
/// The only point where the 'whiteSpace' parser should be called explicitly
/// is the start of the main parser in order to skip any leading white
/// space.
///
/// let mainParser = sum <^> whiteSpace *> lexeme(digit) <* eof
///
/// - parameter parser: The parser to transform in a 'lexeme'.
/// - returns: The value of `parser`.
public func lexeme<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result> {
return parser <* whiteSpace
}
/// Parses any white space. White space consists of _zero_ or more
/// occurrences of a 'space', a line comment or a block (multiline) comment.
/// Block comments may be nested. How comments are started and ended is
/// defined in the `LanguageDefinition` that is passed to the initializer of
/// this token parser.
public var whiteSpace: GenericParser<String, UserState, ()> {
let simpleSpace = CharacterParser.satisfy({ $0.isSpace }).skipMany1
let commentLineEmpty = languageDefinition.commentLine.isEmpty
let commentStartEmpty = languageDefinition.commentStart.isEmpty
if commentLineEmpty && commentStartEmpty {
return (simpleSpace <?> "").skipMany
}
if commentLineEmpty {
return (simpleSpace <|> multiLineComment <?> "").skipMany
}
if commentStartEmpty {
return (simpleSpace <|> oneLineComment <?> "").skipMany
}
return (
simpleSpace <|> oneLineComment <|> multiLineComment <?> ""
).skipMany
}
//
// Bracketing
//
/// Lexeme parser `parentheses(parser)` parses `parser` enclosed in
/// parentheses, returning the value of `parser`.
///
/// - parameter parser: The parser applied between the parentheses.
/// - returns: The value of `parser`.
public func parentheses<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result> {
return parser.between(symbol("("), symbol(")"))
}
/// Lexeme parser `braces(parser)` parses `parser` enclosed in braces "{"
/// and "}", returning the value of `parser`.
///
/// - parameter parser: The parser applied between the braces.
/// - returns: The value of `parser`.
public func braces<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result> {
return parser.between(symbol("{"), symbol("}"))
}
/// Lexeme parser `angles(parser)` parses `parser` enclosed in angle
/// brackets "<" and ">", returning the value of `parser`.
///
/// - parameter parser: The parser applied between the angles.
/// - returns: The value of `parser`.
public func angles<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result> {
return parser.between(symbol("<"), symbol(">"))
}
/// Lexeme parser `brackets(parser)` parses `parser` enclosed in brackets
/// "[" and "]", returning the value of `parser`.
///
/// - parameter parser: The parser applied between the brackets.
/// - returns: The value of `parser`.
public func brackets<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, Result> {
return parser.between(symbol("["), symbol("]"))
}
/// Lexeme parser `semicolon` parses the character ";" and skips any
/// trailing white space. Returns the string ";".
public var semicolon: GenericParser<String, UserState, String> {
return symbol(";")
}
/// Lexeme parser `comma` parses the character "," and skips any trailing
/// white space. Returns the string ",".
public var comma: GenericParser<String, UserState, String> {
return symbol(",")
}
/// Lexeme parser `colon` parses the character ":" and skips any trailing
/// white space. Returns the string ":".
public var colon: GenericParser<String, UserState, String> {
return symbol(":")
}
/// Lexeme parser `dot` parses the character "." and skips any trailing
/// white space. Returns the string ".".
public var dot: GenericParser<String, UserState, String> {
return symbol(".")
}
/// Lexeme parser `semicolonSeperated(parser)` parses _zero_ or more
/// occurrences of `parser` separated by `semicolon`. Returns an array of
/// values returned by `parser`.
///
/// - parameter parser: The parser applied between semicolons.
/// - returns: An array of values returned by `parser`.
public func semicolonSeparated<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]> {
return parser.separatedBy(semicolon)
}
/// Lexeme parser `semicolonSeperated1(parser)` parses _one_ or more
/// occurrences of `parser` separated by `semicolon`. Returns an array of
/// values returned by `parser`.
///
/// - parameter parser: The parser applied between semicolons.
/// - returns: An array of values returned by `parser`.
public func semicolonSeparated1<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]> {
return parser.separatedBy1(semicolon)
}
/// Lexeme parser `commaSeparated(parser)` parses _zero_ or more occurrences
/// of `parser` separated by `comma`. Returns an array of values returned by
/// `parser`.
///
/// - parameter parser: The parser applied between commas.
/// - returns: An array of values returned by `parser`.
public func commaSeparated<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]> {
return parser.separatedBy(comma)
}
/// Lexeme parser `commaSeparated1(parser)` parses _one_ or more occurrences
/// of `parser` separated by `comma`. Returns an array of values returned by
/// `parser`.
///
/// - parameter parser: The parser applied between commas.
/// - returns: An array of values returned by `parser`.
public func commaSeparated1<Result>(
_ parser: GenericParser<String, UserState, Result>
) -> GenericParser<String, UserState, [Result]> {
return parser.separatedBy1(comma)
}
//
// Private methods. They sould be in a separate private extension but it
// causes problems with the internal typealiases.
//
private var oneLineComment: VoidParser {
let commentStart = StrParser.string(languageDefinition.commentLine)
return commentStart.attempt *>
GenericParser.satisfy({ $0 != "\n"}).skipMany *>
GenericParser(result: ())
}
private var multiLineComment: VoidParser {
return GenericParser {
let commentStart =
StrParser.string(self.languageDefinition.commentStart)
return commentStart.attempt *> self.inComment
}
}
private var inComment: VoidParser {
return languageDefinition.allowNestedComments ?
inNestedComment : inNonNestedComment
}
private var inNestedComment: VoidParser {
return GenericParser {
let langDef = self.languageDefinition
let startEnd = (
langDef.commentStart + langDef.commentEnd
).removingDuplicates()
let commentEnd = StrParser.string(langDef.commentEnd)
return commentEnd.attempt *> GenericParser(result: ()) <|>
self.multiLineComment *> self.inNestedComment <|>
GenericParser.noneOf(String(startEnd)).skipMany1 *>
self.inNestedComment <|>
GenericParser.oneOf(String(startEnd)) *>
self.inNestedComment <?>
LocalizedString("end of comment")
}
}
private var inNonNestedComment: VoidParser {
return GenericParser {
let langDef = self.languageDefinition
let startEnd = (
langDef.commentStart + langDef.commentEnd
).removingDuplicates()
let commentEnd = StrParser.string(langDef.commentEnd)
return commentEnd.attempt *> GenericParser(result: ()) <|>
GenericParser.noneOf(String(startEnd)).skipMany1 *>
self.inNonNestedComment <|>
GenericParser.oneOf(String(startEnd)) *>
self.inNonNestedComment <?>
LocalizedString("end of comment")
}
}
private static var escapeCode: CharacterParser {
return charEscape <|> charNumber <|> charAscii <|> charControl <?>
LocalizedString("escape code")
}
private static var charEscape: CharacterParser {
let parsers = escapeMap.map { escCode in
CharacterParser.character(escCode.esc) *>
GenericParser(result: escCode.code)
}
return GenericParser.choice(parsers)
}
private static var charNumber: CharacterParser {
let octalDigit = CharacterParser.octalDigit
let hexaDigit = CharacterParser.hexadecimalDigit
let num = decimal <|>
GenericParser.character("o") *>
numberWithBase(8, parser: octalDigit) <|>
GenericParser.character("x") *>
numberWithBase(16, parser: hexaDigit)
return num >>- { characterFromInt($0) }
}
private static var charAscii: CharacterParser {
let parsers = asciiCodesMap.map { control in
StrParser.string(control.esc) *> GenericParser(result: control.code)
}
return GenericParser.choice(parsers)
}
private static var charControl: CharacterParser {
let upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let ctrlCodes: CharacterParser =
GenericParser.oneOf(upper).flatMap { char in
let charA: Character = "A"
let value = char.unicodeScalar.value -
charA.unicodeScalar.value + 1
let unicode = UnicodeScalar.fromUInt32(value)!
return GenericParser(result: Character(unicode))
}
return GenericParser.character("^") *> (ctrlCodes <|>
GenericParser.character("@") *> GenericParser(result: "\0") <|>
GenericParser.character("[") *>
GenericParser(result: "\u{001B}") <|>
GenericParser.character("]") *>
GenericParser(result: "\u{001C}") <|>
GenericParser.character("\\") *>
GenericParser(result: "\u{001D}") <|>
GenericParser.character("^") *>
GenericParser(result: "\u{001E}") <|>
GenericParser.character("_") *> GenericParser(result: "\u{001F}"))
}
static func characterFromInt(_ v: Int) -> CharacterParser {
guard let us = UnicodeScalar.fromInt(v) else {
let outsideMsg = LocalizedString(
"value outside of Unicode codespace"
)
return GenericParser.fail(outsideMsg)
}
return GenericParser(result: Character(us))
}
private static func numberWithBase(
_ base: Int,
parser: CharacterParser
) -> IntParser {
return parser.many1 >>- { digits in
return integerWithDigits(String(digits), base: base)
}
}
static func integerWithDigits(_ digits: String, base: Int) -> IntParser {
guard let integer = Int(digits, radix: base) else {
let overflowMsg = LocalizedString("Int overflow")
return GenericParser.fail(overflowMsg)
}
return GenericParser(result: integer)
}
private static func doubleWithBase(
_ base: Int,
parser: CharacterParser
) -> DoubleParser {
let baseDouble = Double(base)
return parser.many1 >>- { digits in
let double = digits.reduce(0.0) { acc, d in
baseDouble * acc + Double(Int(String(d), radix: base)!)
}
return GenericParser(result: double)
}
}
private static var doubleIntegerPart: DoubleParser {
return GenericParser.decimalDigit.many1 >>- { digits in
GenericParser(result: Double(String(digits))!)
}
}
private static var naturalNumber: IntParser {
let zeroNumber = GenericParser.character("0") *>
(hexadecimal <|> octal <|> decimal <|> GenericParser(result: 0))
<?> ""
return zeroNumber <|> decimal
}
private static func sign<Number: SignedNumeric>()
-> GenericParser<String, UserState, (Number) -> Number> {
return GenericParser.character("-") *> GenericParser(result: -) <|>
GenericParser.character("+") *> GenericParser(result: { $0 }) <|>
GenericParser(result: { $0 })
}
private static func fractionalExponent(_ number: Double) -> DoubleParser {
let fractionMsg = LocalizedString("fraction")
let fract = CharacterParser.character(".") *>
(GenericParser.decimalDigit.many1 <?> fractionMsg).map { digits in
digits.reduceRight(0) { frac, digit in
(frac + Double(String(digit))!) / 10
}
}
let exponentMsg = LocalizedString("exponent")
let expo = GenericParser.oneOf("eE") *> sign() >>- { sign in
(self.decimal <?> exponentMsg) >>- { exp in
GenericParser(result: power(sign(exp)))
}
}
let fraction = (fract <?> fractionMsg) >>- { frac in
(expo <?> exponentMsg).otherwise(1) >>- { exp in
return GenericParser(result: (number + frac) * exp)
}
}
let exponent = expo >>- { exp in
GenericParser(result: number * exp)
}
return fraction <|> exponent
}
private func caseString(_ name: String) -> StrParser {
if languageDefinition.isCaseSensitive {
return StrParser.string(name)
}
func walk(_ string: String) -> VoidParser {
let unit = VoidParser(result: ())
guard !string.isEmpty else { return unit }
var str = string
let c = str.remove(at: str.startIndex)
let charParser: VoidParser
if c.isAlpha {
charParser = (GenericParser.character(c.lowercase) <|>
GenericParser.character(c.uppercase)) *> unit
} else {
charParser = GenericParser.character(c) *> unit
}
return (charParser <?> name) >>- { _ in walk(str) }
}
return walk(name) *> GenericParser(result: name)
}
}
private let hexadecimalPrefixes = "xX"
private let octalPrefixes = "oO"
private let substituteCharacter: Character = "\u{001A}"
private let escapeMap: [(esc: Character, code: Character)] = [
("a", "\u{0007}"), ("b", "\u{0008}"), ("f", "\u{000C}"), ("n", "\n"),
("r", "\r"), ("t", "\t"), ("v", "\u{000B}"), ("\\", "\\"), ("\"", "\""),
("'", "'")
]
private let asciiCodesMap: [(esc: String, code:Character)] = [
("NUL", "\u{0000}"), ("SOH", "\u{0001}"), ("STX", "\u{0002}"),
("ETX", "\u{0003}"), ("EOT", "\u{0004}"), ("ENQ", "\u{0005}"),
("ACK", "\u{0006}"), ("BEL", "\u{0007}"), ("BS", "\u{0008}"),
("HT", "\u{0009}"), ("LF", "\u{000A}"), ("VT", "\u{000B}"),
("FF", "\u{000C}"), ("CR", "\u{000D}"), ("SO", "\u{000E}"),
("SI", "\u{000F}"), ("DLE", "\u{0010}"), ("DC1", "\u{0011}"),
("DC2", "\u{0012}"), ("DC3", "\u{0013}"), ("DC4", "\u{0014}"),
("NAK", "\u{0015}"), ("SYN", "\u{0016}"), ("ETB", "\u{0017}"),
("CAN", "\u{0018}"), ("EM", "\u{0019}"), ("SUB", "\u{001A}"),
("ESC", "\u{001B}"), ("FS", "\u{001C}"), ("GS", "\u{001D}"),
("RS", "\u{001E}"), ("US", "\u{001F}"), ("SP", "\u{0020}"),
("DEL", "\u{007F}")
]
private func power(_ exp: Int) -> Double {
if exp < 0 {
return 1.0 / power(-exp)
}
return pow(10.0, Double(exp))
}
| bsd-2-clause |
Brightify/Cuckoo | Source/CuckooFunctions.swift | 2 | 1683 | //
// CuckooFunctions.swift
// Cuckoo
//
// Created by Tadeas Kriz on 13/01/16.
// Copyright © 2016 Brightify. All rights reserved.
//
/// Starts the stubbing for the given mock. Can be used multiple times.
public func stub<M: Mock>(_ mock: M, block: (M.Stubbing) -> Void) {
block(mock.getStubbingProxy())
}
/// Used in stubbing. Currently only returns passed function but this may change in the future so it is not recommended to omit it.
// TODO: Uncomment the `: BaseStubFunctionTrait` before the next major release to improve API.
public func when<F/*: BaseStubFunctionTrait*/>(_ function: F) -> F {
return function
}
/// Creates object used for verification of calls.
public func verify<M: Mock>(_ mock: M, _ callMatcher: CallMatcher = times(1), file: StaticString = #file, line: UInt = #line) -> M.Verification {
return mock.getVerificationProxy(callMatcher, sourceLocation: (file, line))
}
/// Clears all invocations and stubs of mocks.
public func reset(_ mocks: HasMockManager...) {
mocks.forEach { mock in
mock.cuckoo_manager.reset()
}
}
/// Clears all stubs of mocks.
public func clearStubs<M: Mock>(_ mocks: M...) {
mocks.forEach { mock in
mock.cuckoo_manager.clearStubs()
}
}
/// Clears all invocations of mocks.
public func clearInvocations<M: Mock>(_ mocks: M...) {
mocks.forEach { mock in
mock.cuckoo_manager.clearInvocations()
}
}
/// Checks if there are no more uverified calls.
public func verifyNoMoreInteractions<M: Mock>(_ mocks: M..., file: StaticString = #file, line: UInt = #line) {
mocks.forEach { mock in
mock.cuckoo_manager.verifyNoMoreInteractions((file, line))
}
}
| mit |
silence0201/Swift-Study | Learn/18.错误处理/CocoaError/CocoaError/main.swift | 1 | 196 |
import Foundation
let filePath = "xxx"
var err: NSError?
let contents = NSString(contentsOfFile: filePath, encoding: String.Encoding.utf8, error: &err)
if err != nil {
// 错误处理
}
| mit |
luinily/hOme | hOme/UI/SequencesViewController.swift | 1 | 3269 | //
// SequencesViewController.swift
// hOme
//
// Created by Coldefy Yoann on 2016/02/07.
// Copyright © 2016年 YoannColdefy. All rights reserved.
//
import Foundation
import UIKit
class SequencesViewController: UITableViewController, ApplicationUser {
@IBOutlet weak var sequencesTable: UITableView!
private let _sectionSequences = 0
private let _sectionNewSequence = 1
override func viewDidLoad() {
sequencesTable.delegate = self
sequencesTable.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let cell = sender as? SequenceCell,
let sequenceVC = segue.destination as? SequenceViewController {
if let sequence = cell.sequence {
sequenceVC.setSequence(sequence)
}
} else if let viewController = segue.destination as? UINavigationController {
if let newSequenceVC = viewController.visibleViewController as? NewSequenceViewController {
newSequenceVC.setOnDone(reloadData)
}
}
}
override func viewWillAppear(_ animated: Bool) {
reloadData()
}
private func ShowSequence(_ sequence: Sequence) {
performSegue(withIdentifier: "ShowSequenceSegue", sender: self)
}
private func reloadData() {
sequencesTable.reloadData()
}
//MARK: Table Data Source
//MARK: Sections
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == _sectionSequences {
return "Sequences"
}
return ""
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == _sectionSequences {
if let application = application {
return application.getSequenceCount()
}
} else if section == _sectionNewSequence {
return 1
}
return 0
}
//MARK: Cells
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = nil
if (indexPath as NSIndexPath).section == _sectionSequences {
cell = tableView.dequeueReusableCell(withIdentifier: "SequenceCell")
if let cell = cell as? SequenceCell,
let application = application {
cell.setSequence(application.getSequences()[(indexPath as NSIndexPath).row])
}
} else if (indexPath as NSIndexPath).section == _sectionNewSequence {
cell = tableView.dequeueReusableCell(withIdentifier: "NewSequenceCell")
}
if let cell = cell {
return cell
} else {
return UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "Cell")
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return (indexPath as NSIndexPath).section == _sectionSequences
}
// MARK: Table Delegate
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .destructive, title: "Delete") {
action, indexPath in
if let cell = tableView.cellForRow(at: indexPath) as? SequenceCell,
let application = self.application {
if let sequence = cell.sequence {
application.deleteSequence(sequence)
tableView.reloadData()
}
}
}
return [delete]
}
}
| mit |
angmu/SwiftPlayCode | 02-TableView演练/02-TableView演练/ViewController.swift | 1 | 2821 | //
// ViewController.swift
// 02-TableView演练
//
// Created by 穆良 on 2017/6/21.
// Copyright © 2017年 穆良. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private lazy var tableView: UITableView = {
// 实例化 指定样式
let tb = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)
tb.dataSource = self
// 注册可重用cell [UITableViewCell class]
// 注册一个类
// tb.register(UITableViewCell.self , forCellReuseIdentifier: "CELL")
return tb
}()
// 纯代码创建视图层次结构 - 和 storyboard/xib 等价
override func loadView() {
// 在访问 view 时,如果view == nil, 会自动调用 loadView方法
// view没有创建 又来到这个方法 死循环
// print(view)
// view 就是tableView; tableViewController也是这么做的
view = tableView;
}
override func viewDidLoad() {
view.backgroundColor = UIColor.magenta
}
}
/// 将一组相关的代码放在一起, 便于阅读和维护
/// 遵守协议的写法 类似其他语言中 多继承
extension ViewController: UITableViewDataSource {
// 不实现直接报错
// UITableViewController 需要override已经遵守了协议,实现了方法
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 33;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 方式一: 必须注册可重用cell
// iOS6.0 出现indexPath 代替原始方法——>iOS7.0以后下面代码很少出现——>Swift中注册机制优势明显
// let cell = tableView.dequeueReusableCe÷ll(withIdentifier: "CELL", for: indexPath)
// cell.textLabel?.text = "hello \(indexPath.row)"
// return cell
// 方式二
// 最原始的方法,也可利用注册机制 不用判断了
// 不要求注册可重用的cell, 返回值有可能为空——可选的
var cell = tableView.dequeueReusableCell(withIdentifier: "CELL")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "CELL")
}
// cell? 可选更安全
cell?.textLabel?.text = "hello \(indexPath.row)"
return cell!
}
}
/*
### 思考问题
1. 创建tableView,frame参数怎么填?
- 注册cell怎么填写class类型?
- 怎样让view == tableView?
- 为什么会死循环
- 注册机制是怎样的
- 原始创建时,cell为什么要转来转去
- extension怎么用
- 为什么不用写override了?
- OC中没有多几继承, OC中用协议替代多线程
*/
| mit |
OatmealCode/Oatmeal | Example/Pods/Carlos/Carlos/GenericOperation.swift | 4 | 532 | import Foundation
/**
This class is a workaround for an issue with Swift where generic subclasses of NSOperation won't get the start() or main() func called.
*/
public class GenericOperation: ConcurrentOperation {
public override func start() {
genericStart()
}
/**
The method to override if you have a generic subclass of NSOperation (more specifically of ConcurrentOperation), so that your start() method will be called after adding the operation itself to a NSOperationQueue
*/
public func genericStart() {}
} | mit |
stripe/stripe-ios | Stripe/STPPaymentMethodParams+BasicUI.swift | 1 | 1584 | //
// STPPaymentMethodParams+BasicUI.swift
// StripeiOS
//
// Created by David Estes on 6/30/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripePaymentsUI
import UIKit
extension STPPaymentMethodParams: STPPaymentOption {
// MARK: - STPPaymentOption
@objc public var image: UIImage {
if type == .card && card != nil {
let brand = STPCardValidator.brand(forNumber: card?.number ?? "")
return STPImageLibrary.cardBrandImage(for: brand)
} else {
return STPImageLibrary.cardBrandImage(for: .unknown)
}
}
@objc public var templateImage: UIImage {
if type == .card && card != nil {
let brand = STPCardValidator.brand(forNumber: card?.number ?? "")
return STPImageLibrary.templatedBrandImage(for: brand)
} else if type == .FPX {
return STPImageLibrary.bankIcon()
} else {
return STPImageLibrary.templatedBrandImage(for: .unknown)
}
}
@objc public var isReusable: Bool {
switch type {
case .card, .link, .USBankAccount:
return true
case .alipay, .AUBECSDebit, .bacsDebit, .SEPADebit, .iDEAL, .FPX, .cardPresent, .giropay,
.grabPay, .EPS, .przelewy24, .bancontact, .netBanking, .OXXO, .payPal, .sofort, .UPI,
.afterpayClearpay, .blik, .weChatPay, .boleto, .klarna, .linkInstantDebit, .affirm,
.unknown:
return false
@unknown default:
return false
}
}
}
| mit |
cerberillo/ios-workflow | library/library.demo/AppDelegate.swift | 1 | 2149 | //
// AppDelegate.swift
// library.demo
//
// Created by David Martin on 6/28/16.
// Copyright © 2016 David Martin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
uias/Tabman | Sources/Tabman/Bar/BarItem/UIKit+TMBarItemable.swift | 1 | 647 | //
// UIKit+TMBarItem.swift
// Tabman
//
// Created by Merrick Sapsford on 19/10/2018.
// Copyright © 2022 UI At Six. All rights reserved.
//
import UIKit
/// :nodoc:
extension UINavigationItem: TMBarItemable {
// swiftlint:disable unused_setter_value
public var image: UIImage? {
get {
return nil
}
set {}
}
public var selectedImage: UIImage? {
get {
return nil
}
set {}
}
public var badgeValue: String? {
get {
return nil
}
set {}
}
}
/// :nodoc:
extension UITabBarItem: TMBarItemable {
}
| mit |
SweetzpotAS/TCXZpot-Swift | TCXZpot-SwiftTests/LapTest.swift | 1 | 3482 | //
// LapTest.swift
// TCXZpot
//
// Created by Tomás Ruiz López on 24/5/17.
// Copyright 2017 SweetZpot AS
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import TCXZpot
class LapTest: XCTestCase {
func testSerializesCorrectly() {
let lap = Lap(startTime: TCXDate(day: 1, month: 1, year: 2017, hour: 0, minute: 0, second: 0)!,
totalTime: 125,
distance: 67,
maximumSpeed: 23,
calories: 200,
averageHeartRate: HeartRate(bpm: 92),
maximumHeartRate: HeartRate(bpm: 120),
intensity: Intensity.active,
cadence: Cadence(value: 10),
triggerMethod: TriggerMethod.manual,
tracks: Track(with: []),
notes: Notes(text: "Some notes"))
let serializer = MockSerializer()
lap.serialize(to: serializer)
XCTAssertTrue(serializer.hasPrinted("<Lap StartTime=\"2017-01-01T00:00:00.000Z\">"))
XCTAssertTrue(serializer.hasPrinted("<TotalTimeSeconds>125.0</TotalTimeSeconds>"))
XCTAssertTrue(serializer.hasPrinted("<DistanceMeters>67.0</DistanceMeters>"))
XCTAssertTrue(serializer.hasPrinted("<MaximumSpeed>23.0</MaximumSpeed>"))
XCTAssertTrue(serializer.hasPrinted("<Calories>200</Calories>"))
XCTAssertTrue(serializer.hasPrinted("<AverageHeartRateBpm>"))
XCTAssertTrue(serializer.hasPrinted("<MaximumHeartRateBpm>"))
XCTAssertTrue(serializer.hasPrinted("<Intensity>Active</Intensity>"))
XCTAssertTrue(serializer.hasPrinted("<Cadence>10</Cadence>"))
XCTAssertTrue(serializer.hasPrinted("<TriggerMethod>Manual</TriggerMethod>"))
XCTAssertTrue(serializer.hasPrinted("<Track>"))
XCTAssertTrue(serializer.hasPrinted("<Notes>Some notes</Notes>"))
XCTAssertTrue(serializer.hasPrinted("</Lap>"))
}
func testSerializesShortVersionCorrectly() {
let lap = Lap(startTime: TCXDate(day: 1, month: 1, year: 2017, hour: 0, minute: 0, second: 0)!,
totalTime: 125,
distance: 67,
calories: 200,
intensity: Intensity.active,
triggerMethod: TriggerMethod.manual,
tracks: nil)
let serializer = MockSerializer()
lap.serialize(to: serializer)
XCTAssertTrue(serializer.hasPrinted("<Lap StartTime=\"2017-01-01T00:00:00.000Z\">"))
XCTAssertTrue(serializer.hasPrinted("<TotalTimeSeconds>125.0</TotalTimeSeconds>"))
XCTAssertTrue(serializer.hasPrinted("<DistanceMeters>67.0</DistanceMeters>"))
XCTAssertTrue(serializer.hasPrinted("<Calories>200</Calories>"))
XCTAssertTrue(serializer.hasPrinted("<Intensity>Active</Intensity>"))
XCTAssertTrue(serializer.hasPrinted("<TriggerMethod>Manual</TriggerMethod>"))
XCTAssertTrue(serializer.hasPrinted("</Lap>"))
}
}
| apache-2.0 |
L-Zephyr/Drafter | Tests/DrafterTests/CombinatorTest.swift | 1 | 6223 | //
// TestCombinator.swift
// DrafterTests
//
// Created by LZephyr on 2017/11/1.
//
import XCTest
class CombinatorTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// func run(_ input: String) {
//
// }
func testSeparator1() {
let tokens: [Token] = [Token(type: .name, text: "name1"),
Token(type: .comma, text: ","),
Token(type: .name, text: "name2"),
Token(type: .comma, text: ",")]
let comma = token(.comma)
let parser = token(.name).sepBy(comma)
if case .failure(_) = parser.parse(tokens) {
XCTAssert(true)
}
}
func testSeparator2() {
let tokens: [Token] = [Token(type: .name, text: "name1"),
Token(type: .comma, text: ","),
Token(type: .name, text: "name2")]
let comma = token(.comma)
let parser = token(.name).sepBy(comma)
guard case .success(let (result, rest)) = parser.parse(tokens) else {
XCTAssert(true)
return
}
XCTAssert(result.count == 2)
XCTAssert(rest.count == 0)
}
func testBetween() {
let tokens: [Token] = [Token(type: .leftBrace, text: "{"),
Token(type: .name, text: "name"),
Token(type: .rightBrace, text: "}")]
let parser = token(.name).between(token(.leftBrace), token(.rightBrace))
guard case .success(let (result, rest)) = parser.parse(tokens) else {
XCTAssert(false)
return
}
XCTAssert(result.type == .name)
XCTAssert(result.text == "name")
XCTAssert(rest.count == 0)
}
func testMany() {
let tokens: [Token] = [Token(type: .name, text: "name1"),
Token(type: .name, text: "name2")]
guard case .success(let (result, rest)) = token(.name).many.parse(tokens) else {
XCTAssert(false)
return
}
XCTAssert(result.count == 2)
XCTAssert(result[0].text == "name1")
XCTAssert(result[1].text == "name2")
XCTAssert(rest.count == 0)
}
func testAnyToken() {
let tokens = [Token(type: .name, text: "name"),
Token(type: .comma, text: ",")]
guard case .success(let (result, rest)) = anyToken.parse(tokens) else {
XCTAssert(false)
return
}
XCTAssert(result.type == .name)
XCTAssert(rest.count == 1)
}
// func testNotFollowedBy() {
// let tokens = [Token(type: .name, text: "name"),
// Token(type: .comma, text: ",")]
// guard case .success(let (result, rest)) = token(.name).notFollowedBy(token(.colon)).parse(tokens) else {
// XCTAssert(false)
// return
// }
//
// XCTAssert(result.type == .name)
// XCTAssert(rest.count == 1)
// }
// func testChioce() {
// let tokens = [Token(type: .name, text: "name"),
// Token(type: .comma, text: ",")]
// guard case .success(let (result, rest)) = choice([token(.comma), token(.name)]).parse(tokens) else {
// XCTAssert(false)
// return
// }
//
// XCTAssert(result.type == .name)
// XCTAssert(rest.count == 1)
// }
//
func testLookAhead() {
let tokens = [Token(type: .name, text: "name"),
Token(type: .comma, text: ",")]
guard case .success(let (result, rest)) = token(.name).lookahead.parse(tokens) else {
XCTAssert(false)
return
}
XCTAssert(result.type == .name)
XCTAssert(rest.count == 2)
}
// MARK: - AnyToken
func testAnyTokenUntil() {
let tokens = [Token(type: .name, text: "name"),
Token(type: .comma, text: ","),
Token(type: .colon, text: ":")]
guard case .success(let (result, rest)) = anyTokens(until: token(.colon)).parse(tokens) else {
XCTAssert(false)
return
}
XCTAssert(result.count == 2)
XCTAssert(rest.count == 1)
}
func testAnyTokenUntil2() {
let tokens = [Token(type: .name, text: "name"),
Token(type: .comma, text: ","),
Token(type: .colon, text: ":")]
guard case .success(let (result, rest)) = anyTokens(until: token(.colon)).parse(tokens) else {
XCTAssert(false)
return
}
XCTAssert(result.count == 2)
XCTAssert(rest.count == 1)
}
func testAnyTokenInside() {
let tokens = SourceLexer(input: "(name1 name2 (name3)())").allTokens
let l = token(.leftParen)
let r = token(.rightParen)
guard case .success(let (result, rest)) = anyTokens(inside: l, and: r).parse(tokens) else {
XCTAssert(false)
return
}
XCTAssert(result.count == 7)
XCTAssert(rest.count == 0)
}
// func testReduce() {
// let tokens = SourceLexer(input: "name1.name2.name3;").allTokens
//
// let single = token(.name) <* token(.dot)
// let parser =
// single.reduce([]) { (last, current) in
// return last + [current]
// }.flatMap { (results) -> Parser<[Token], Tokens> in
// return { results + [$0] } <^> token(.name)
// }
//
// guard case let .success((result, rest)) = parser.parse(tokens) else {
// XCTAssert(false)
// return
// }
// XCTAssert(result.count == 3)
// XCTAssert(rest.count == 1)
// }
}
| mit |
yisimeng/YSMFactory-swift | YSMFactory-swift/Vendor/CIFilter/CIMaskedVariableBlur.swift | 1 | 506 | //
// CIMaskedVariableBlur.swift
// YSMFactory-swift
//
// Created by 忆思梦 on 2016/12/30.
// Copyright © 2016年 忆思梦. All rights reserved.
//
import UIKit
class CIMaskedVariableBlur: YSMFilter {
/// default : 10.0
var inputRadius:CGFloat? {
didSet{
ciFilter.setValue(inputRadius, forKey: "inputRadius")
}
}
var inputMask:CIImage? {
didSet{
ciFilter.setValue(inputMask, forKey: "inputMask")
}
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/07087-swift-printingdiagnosticconsumer-handlediagnostic.swift | 11 | 355 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<H : T where A<d where g: A.g : d
func a(a<f = compose([1]
func a(a")
func a
var b {
let c : T -> T where S<S {
struct S {
}
}
struct d<d where B : String = nil
struct A : d
cla
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/11673-swift-parser-skipsingle.swift | 11 | 266 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
var d {
enum e {
{
}
var d = [ {
protocol P {
class
case ,
{
( ( ( ( ( ( (
[ {
( ( {
(
{
{
( [
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.