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 |
---|---|---|---|---|---|
4jchc/4jchc-BaiSiBuDeJie | 4jchc-MenuController/4jchc-MenuControllerUITests/_jchc_MenuControllerUITests.swift | 1 | 1275 | //
// _jchc_MenuControllerUITests.swift
// 4jchc-MenuControllerUITests
//
// Created by ่่ฟ on 16/3/2.
// Copyright ยฉ 2016ๅนด ่่ฟ. All rights reserved.
//
import XCTest
class _jchc_MenuControllerUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests itโs important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
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() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| apache-2.0 |
tejasranade/KinveyHealth | SportShop/SettingsController.swift | 1 | 1931 | //
// SettingsController.swift
// SportShop
//
// Created by Tejas on 1/31/17.
// Copyright ยฉ 2017 Kinvey. All rights reserved.
//
import Foundation
import UIKit
import Kinvey
import FBSDKLoginKit
class SettingsController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var email: UITextField!
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var phoneNumber: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
if let user = Kinvey.sharedClient.activeUser as? HealthUser {
email.text = user.email
firstName.text = user.firstname
lastName.text = user.lastname
phoneNumber.text = user.phone
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return textField.resignFirstResponder()
}
@IBAction func dismiss(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func save(_ sender: Any) {
if let user = Kinvey.sharedClient.activeUser as? HealthUser{
user.email = email.text
user.firstname = firstName.text
user.lastname = lastName.text
user.phone = phoneNumber.text
//user.save()
}
}
@IBAction func logout(_ sender: Any) {
Kinvey.sharedClient.activeUser?.logout()
self.dismiss(animated:true, completion: nil)
NotificationCenter.default.post(name: Notification.Name("kinveyUserChanged"), object: nil)
// User.login(username: "Guest", password: "kinvey") { user, error in
// if let _ = user {
// NotificationCenter.default.post(name: Notification.Name("kinveyUserChanged"), object: nil)
// self.dismiss(animated:true, completion: nil)
// }
// }
}
}
| apache-2.0 |
noppoMan/aws-sdk-swift | Sources/Soto/Services/ResourceGroupsTaggingAPI/ResourceGroupsTaggingAPI_Error.swift | 1 | 4134 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for ResourceGroupsTaggingAPI
public struct ResourceGroupsTaggingAPIErrorType: AWSErrorType {
enum Code: String {
case concurrentModificationException = "ConcurrentModificationException"
case constraintViolationException = "ConstraintViolationException"
case internalServiceException = "InternalServiceException"
case invalidParameterException = "InvalidParameterException"
case paginationTokenExpiredException = "PaginationTokenExpiredException"
case throttledException = "ThrottledException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize ResourceGroupsTaggingAPI
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The target of the operation is currently being modified by a different request. Try again later.
public static var concurrentModificationException: Self { .init(.concurrentModificationException) }
/// The request was denied because performing this operation violates a constraint. Some of the reasons in the following list might not apply to this specific operation. You must meet the prerequisites for using tag policies. For information, see Prerequisites and Permissions for Using Tag Policies in the AWS Organizations User Guide. You must enable the tag policies service principal (tagpolicies.tag.amazonaws.com) to integrate with AWS Organizations For information, see EnableAWSServiceAccess. You must have a tag policy attached to the organization root, an OU, or an account.
public static var constraintViolationException: Self { .init(.constraintViolationException) }
/// The request processing failed because of an unknown error, exception, or failure. You can retry the request.
public static var internalServiceException: Self { .init(.internalServiceException) }
/// This error indicates one of the following: A parameter is missing. A malformed string was supplied for the request parameter. An out-of-range value was supplied for the request parameter. The target ID is invalid, unsupported, or doesn't exist. You can't access the Amazon S3 bucket for report storage. For more information, see Additional Requirements for Organization-wide Tag Compliance Reports in the AWS Organizations User Guide.
public static var invalidParameterException: Self { .init(.invalidParameterException) }
/// A PaginationToken is valid for a maximum of 15 minutes. Your request was denied because the specified PaginationToken has expired.
public static var paginationTokenExpiredException: Self { .init(.paginationTokenExpiredException) }
/// The request was denied to limit the frequency of submitted requests.
public static var throttledException: Self { .init(.throttledException) }
}
extension ResourceGroupsTaggingAPIErrorType: Equatable {
public static func == (lhs: ResourceGroupsTaggingAPIErrorType, rhs: ResourceGroupsTaggingAPIErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension ResourceGroupsTaggingAPIErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 |
joshkennede/ToDo | Todo/AddTodoItemViewController.swift | 1 | 774 | //
// AddTodoItemViewController.swift
// ToDo
//
// Created by Joshua Kennedy on 10/26/16.
//
import UIKit
class AddTodoItemViewController: UIViewController {
var todoItem: TodoItem = TodoItem(itemName: "")
@IBOutlet var doneButton: UIBarButtonItem!
@IBOutlet var textField: UITextField!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
if (self.textField.text != "") {
self.todoItem = TodoItem(itemName: self.textField.text!)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| gpl-3.0 |
grpc/grpc-swift | Package@swift-5.5.swift | 1 | 11357 | // swift-tools-version:5.5
/*
* Copyright 2022, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import PackageDescription
// swiftformat puts the next import before the tools version.
// swiftformat:disable:next sortedImports
import class Foundation.ProcessInfo
let grpcPackageName = "grpc-swift"
let grpcProductName = "GRPC"
let cgrpcZlibProductName = "CGRPCZlib"
let grpcTargetName = grpcProductName
let cgrpcZlibTargetName = cgrpcZlibProductName
let includeNIOSSL = ProcessInfo.processInfo.environment["GRPC_NO_NIO_SSL"] == nil
// MARK: - Package Dependencies
let packageDependencies: [Package.Dependency] = [
.package(
url: "https://github.com/apple/swift-nio.git",
from: "2.42.0"
),
.package(
url: "https://github.com/apple/swift-nio-http2.git",
from: "1.22.0"
),
.package(
url: "https://github.com/apple/swift-nio-transport-services.git",
from: "1.15.0"
),
.package(
url: "https://github.com/apple/swift-nio-extras.git",
from: "1.4.0"
),
.package(
name: "SwiftProtobuf",
url: "https://github.com/apple/swift-protobuf.git",
from: "1.20.2"
),
.package(
url: "https://github.com/apple/swift-log.git",
from: "1.4.0"
),
.package(
url: "https://github.com/apple/swift-argument-parser.git",
from: "1.0.0"
),
].appending(
.package(
url: "https://github.com/apple/swift-nio-ssl.git",
from: "2.14.0"
),
if: includeNIOSSL
)
// MARK: - Target Dependencies
extension Target.Dependency {
// Target dependencies; external
static let grpc: Self = .target(name: grpcTargetName)
static let cgrpcZlib: Self = .target(name: cgrpcZlibTargetName)
static let protocGenGRPCSwift: Self = .target(name: "protoc-gen-grpc-swift")
// Target dependencies; internal
static let grpcSampleData: Self = .target(name: "GRPCSampleData")
static let echoModel: Self = .target(name: "EchoModel")
static let echoImplementation: Self = .target(name: "EchoImplementation")
static let helloWorldModel: Self = .target(name: "HelloWorldModel")
static let routeGuideModel: Self = .target(name: "RouteGuideModel")
static let interopTestModels: Self = .target(name: "GRPCInteroperabilityTestModels")
static let interopTestImplementation: Self =
.target(name: "GRPCInteroperabilityTestsImplementation")
// Product dependencies
static let argumentParser: Self = .product(
name: "ArgumentParser",
package: "swift-argument-parser"
)
static let nio: Self = .product(name: "NIO", package: "swift-nio")
static let nioConcurrencyHelpers: Self = .product(
name: "NIOConcurrencyHelpers",
package: "swift-nio"
)
static let nioCore: Self = .product(name: "NIOCore", package: "swift-nio")
static let nioEmbedded: Self = .product(name: "NIOEmbedded", package: "swift-nio")
static let nioExtras: Self = .product(name: "NIOExtras", package: "swift-nio-extras")
static let nioFoundationCompat: Self = .product(name: "NIOFoundationCompat", package: "swift-nio")
static let nioHTTP1: Self = .product(name: "NIOHTTP1", package: "swift-nio")
static let nioHTTP2: Self = .product(name: "NIOHTTP2", package: "swift-nio-http2")
static let nioPosix: Self = .product(name: "NIOPosix", package: "swift-nio")
static let nioSSL: Self = .product(name: "NIOSSL", package: "swift-nio-ssl")
static let nioTLS: Self = .product(name: "NIOTLS", package: "swift-nio")
static let nioTransportServices: Self = .product(
name: "NIOTransportServices",
package: "swift-nio-transport-services"
)
static let logging: Self = .product(name: "Logging", package: "swift-log")
static let protobuf: Self = .product(name: "SwiftProtobuf", package: "SwiftProtobuf")
static let protobufPluginLibrary: Self = .product(
name: "SwiftProtobufPluginLibrary",
package: "SwiftProtobuf"
)
}
// MARK: - Targets
extension Target {
static let grpc: Target = .target(
name: grpcTargetName,
dependencies: [
.cgrpcZlib,
.nio,
.nioCore,
.nioPosix,
.nioEmbedded,
.nioFoundationCompat,
.nioTLS,
.nioTransportServices,
.nioHTTP1,
.nioHTTP2,
.nioExtras,
.logging,
.protobuf,
].appending(
.nioSSL, if: includeNIOSSL
),
path: "Sources/GRPC"
)
static let cgrpcZlib: Target = .target(
name: cgrpcZlibTargetName,
path: "Sources/CGRPCZlib",
linkerSettings: [
.linkedLibrary("z"),
]
)
static let protocGenGRPCSwift: Target = .executableTarget(
name: "protoc-gen-grpc-swift",
dependencies: [
.protobuf,
.protobufPluginLibrary,
],
exclude: [
"README.md",
]
)
static let grpcTests: Target = .testTarget(
name: "GRPCTests",
dependencies: [
.grpc,
.echoModel,
.echoImplementation,
.helloWorldModel,
.interopTestModels,
.interopTestImplementation,
.grpcSampleData,
.nioCore,
.nioConcurrencyHelpers,
.nioPosix,
.nioTLS,
.nioHTTP1,
.nioHTTP2,
.nioEmbedded,
.nioTransportServices,
.logging,
].appending(
.nioSSL, if: includeNIOSSL
),
exclude: [
"Codegen/Normalization/normalization.proto",
]
)
static let interopTestModels: Target = .target(
name: "GRPCInteroperabilityTestModels",
dependencies: [
.grpc,
.nio,
.protobuf,
],
exclude: [
"README.md",
"generate.sh",
"src/proto/grpc/testing/empty.proto",
"src/proto/grpc/testing/empty_service.proto",
"src/proto/grpc/testing/messages.proto",
"src/proto/grpc/testing/test.proto",
"unimplemented_call.patch",
]
)
static let interopTestImplementation: Target = .target(
name: "GRPCInteroperabilityTestsImplementation",
dependencies: [
.grpc,
.interopTestModels,
.nioCore,
.nioPosix,
.nioHTTP1,
.logging,
].appending(
.nioSSL, if: includeNIOSSL
)
)
static let interopTests: Target = .executableTarget(
name: "GRPCInteroperabilityTests",
dependencies: [
.grpc,
.interopTestImplementation,
.nioCore,
.nioPosix,
.logging,
.argumentParser,
]
)
static let backoffInteropTest: Target = .executableTarget(
name: "GRPCConnectionBackoffInteropTest",
dependencies: [
.grpc,
.interopTestModels,
.nioCore,
.nioPosix,
.logging,
.argumentParser,
],
exclude: [
"README.md",
]
)
static let perfTests: Target = .executableTarget(
name: "GRPCPerformanceTests",
dependencies: [
.grpc,
.grpcSampleData,
.nioCore,
.nioEmbedded,
.nioPosix,
.nioHTTP2,
.argumentParser,
]
)
static let grpcSampleData: Target = .target(
name: "GRPCSampleData",
dependencies: includeNIOSSL ? [.nioSSL] : [],
exclude: [
"bundle.p12",
]
)
static let echoModel: Target = .target(
name: "EchoModel",
dependencies: [
.grpc,
.nio,
.protobuf,
],
path: "Sources/Examples/Echo/Model",
exclude: [
"echo.proto",
]
)
static let echoImplementation: Target = .target(
name: "EchoImplementation",
dependencies: [
.echoModel,
.grpc,
.nioCore,
.nioHTTP2,
.protobuf,
],
path: "Sources/Examples/Echo/Implementation"
)
static let echo: Target = .executableTarget(
name: "Echo",
dependencies: [
.grpc,
.echoModel,
.echoImplementation,
.grpcSampleData,
.nioCore,
.nioPosix,
.logging,
.argumentParser,
].appending(
.nioSSL, if: includeNIOSSL
),
path: "Sources/Examples/Echo/Runtime"
)
static let helloWorldModel: Target = .target(
name: "HelloWorldModel",
dependencies: [
.grpc,
.nio,
.protobuf,
],
path: "Sources/Examples/HelloWorld/Model",
exclude: [
"helloworld.proto",
]
)
static let helloWorldClient: Target = .executableTarget(
name: "HelloWorldClient",
dependencies: [
.grpc,
.helloWorldModel,
.nioCore,
.nioPosix,
.argumentParser,
],
path: "Sources/Examples/HelloWorld/Client"
)
static let helloWorldServer: Target = .executableTarget(
name: "HelloWorldServer",
dependencies: [
.grpc,
.helloWorldModel,
.nioCore,
.nioPosix,
.argumentParser,
],
path: "Sources/Examples/HelloWorld/Server"
)
static let routeGuideModel: Target = .target(
name: "RouteGuideModel",
dependencies: [
.grpc,
.nio,
.protobuf,
],
path: "Sources/Examples/RouteGuide/Model",
exclude: [
"route_guide.proto",
]
)
static let routeGuideClient: Target = .executableTarget(
name: "RouteGuideClient",
dependencies: [
.grpc,
.routeGuideModel,
.nioCore,
.nioPosix,
.argumentParser,
],
path: "Sources/Examples/RouteGuide/Client"
)
static let routeGuideServer: Target = .executableTarget(
name: "RouteGuideServer",
dependencies: [
.grpc,
.routeGuideModel,
.nioCore,
.nioConcurrencyHelpers,
.nioPosix,
.argumentParser,
],
path: "Sources/Examples/RouteGuide/Server"
)
static let packetCapture: Target = .executableTarget(
name: "PacketCapture",
dependencies: [
.grpc,
.echoModel,
.nioCore,
.nioPosix,
.nioExtras,
.argumentParser,
],
path: "Sources/Examples/PacketCapture",
exclude: [
"README.md",
]
)
}
// MARK: - Products
extension Product {
static let grpc: Product = .library(
name: grpcProductName,
targets: [grpcTargetName]
)
static let cgrpcZlib: Product = .library(
name: cgrpcZlibProductName,
targets: [cgrpcZlibTargetName]
)
static let protocGenGRPCSwift: Product = .executable(
name: "protoc-gen-grpc-swift",
targets: ["protoc-gen-grpc-swift"]
)
}
// MARK: - Package
let package = Package(
name: grpcPackageName,
products: [
.grpc,
.cgrpcZlib,
.protocGenGRPCSwift,
],
dependencies: packageDependencies,
targets: [
// Products
.grpc,
.cgrpcZlib,
.protocGenGRPCSwift,
// Tests etc.
.grpcTests,
.interopTestModels,
.interopTestImplementation,
.interopTests,
.backoffInteropTest,
.perfTests,
.grpcSampleData,
// Examples
.echoModel,
.echoImplementation,
.echo,
.helloWorldModel,
.helloWorldClient,
.helloWorldServer,
.routeGuideModel,
.routeGuideClient,
.routeGuideServer,
.packetCapture,
]
)
extension Array {
func appending(_ element: Element, if condition: Bool) -> [Element] {
if condition {
return self + [element]
} else {
return self
}
}
}
| apache-2.0 |
austinzheng/swift | validation-test/compiler_crashers_fixed/00349-swift-typechecker-resolveidentifiertype.swift | 65 | 462 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func o<t>() -> (t, t -> t) -> t {
o = {
}
{
t) }
}
class func o
| apache-2.0 |
xuduo/socket.io-push-ios | source/SocketIOClientSwift/SocketIOClient.swift | 1 | 17018 | //
// SocketIOClient.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 11/23/14.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public final class SocketIOClient: NSObject, SocketEngineClient {
public let socketURL: String
public private(set) var engine: SocketEngineSpec?
public private(set) var status = SocketIOClientStatus.NotConnected
public var forceNew = false
public var nsp = "/"
public var options: Set<SocketIOClientOption>
public var reconnects = true
public var reconnectWait = 10
public var sid: String? {
return engine?.sid
}
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
private let logType = "SocketIOClient"
private let parseQueue = dispatch_queue_create("com.socketio.parseQueue", DISPATCH_QUEUE_SERIAL)
private var anyHandler: ((SocketAnyEvent) -> Void)?
private var currentReconnectAttempt = 0
private var handlers = [SocketEventHandler]()
private var connectParams: [String: AnyObject]?
private var reconnectTimer: NSTimer?
private var ackHandlers = SocketAckManager()
private(set) var currentAck = -1
private(set) var handleQueue = dispatch_get_main_queue()
private(set) var reconnectAttempts = -1
var waitingData = [SocketPacket]()
/**
Type safe way to create a new SocketIOClient. opts can be omitted
*/
public init(socketURL: String, options: Set<SocketIOClientOption> = []) {
self.options = options
if socketURL["https://"].matches().count != 0 {
self.options.insertIgnore(.Secure(true))
}
self.socketURL = socketURL["https?://"] ~= ""
for option in options ?? [] {
switch option {
case .ConnectParams(let params):
connectParams = params
case .Reconnects(let reconnects):
self.reconnects = reconnects
case .ReconnectAttempts(let attempts):
reconnectAttempts = attempts
case .ReconnectWait(let wait):
reconnectWait = abs(wait)
case .Nsp(let nsp):
self.nsp = nsp
case .Log(let log):
DefaultSocketLogger.Logger.log = log
case .Logger(let logger):
DefaultSocketLogger.Logger = logger
case .HandleQueue(let queue):
handleQueue = queue
case .ForceNew(let force):
forceNew = force
default:
continue
}
}
self.options.insertIgnore(.Path("/socket.io"))
super.init()
}
/**
Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
If using Swift it's recommended to use `init(var socketURL: String, opts: SocketOptionsDictionary? = nil)`
*/
public convenience init(socketURL: String, options: NSDictionary?) {
self.init(socketURL: socketURL,
options: Set<SocketIOClientOption>.NSDictionaryToSocketOptionsSet(options ?? [:]))
}
deinit {
DefaultSocketLogger.Logger.log("Client is being deinit", type: logType)
engine?.close()
}
private func addEngine() -> SocketEngine {
DefaultSocketLogger.Logger.log("Adding engine", type: logType)
let newEngine = SocketEngine(client: self, url: socketURL, options: options ?? [])
engine = newEngine
return newEngine
}
private func clearReconnectTimer() {
reconnectTimer?.invalidate()
reconnectTimer = nil
}
/**
Closes the socket. Only reopen the same socket if you know what you're doing.
Will turn off automatic reconnects.
Pass true to fast if you're closing from a background task
*/
public func close() {
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
reconnects = false
didDisconnect("Closed")
}
/**
Connect to the server.
*/
public func connect() {
connect(timeoutAfter: 0, withTimeoutHandler: nil)
}
/**
Connect to the server. If we aren't connected after timeoutAfter, call handler
*/
public func connect(timeoutAfter timeoutAfter: Int,
withTimeoutHandler handler: (() -> Void)?) {
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
guard status != .Connected else {
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket",
type: logType)
return
}
status = .Connecting
if engine == nil || forceNew {
addEngine().open(connectParams)
} else {
engine?.open(connectParams)
}
guard timeoutAfter != 0 else { return }
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
dispatch_after(time, handleQueue) {[weak self] in
if let this = self where this.status != .Connected {
this.status = .Closed
this.engine?.close()
handler?()
}
}
}
private func createOnAck(items: [AnyObject]) -> OnAckCallback {
return {[weak self, ack = ++currentAck] timeout, callback in
if let this = self {
this.ackHandlers.addAck(ack, callback: callback)
dispatch_async(this.emitQueue) {
this._emit(items, ack: ack)
}
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
this.ackHandlers.timeoutAck(ack)
}
}
}
}
}
func didConnect() {
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
status = .Connected
currentReconnectAttempt = 0
clearReconnectTimer()
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
handleEvent("connect", data: [], isInternalMessage: false)
}
func didDisconnect(reason: String) {
guard status != .Closed else {
return
}
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
status = .Closed
reconnects = false
// Make sure the engine is actually dead.
engine?.close()
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/// error
public func didError(reason: AnyObject) {
DefaultSocketLogger.Logger.error("%@", type: logType, args: reason)
handleEvent("error", data: reason as? [AnyObject] ?? [reason],
isInternalMessage: true)
}
/**
Same as close
*/
public func disconnect() {
close()
}
/**
Send a message to the server
*/
public func emit(event: String, _ items: AnyObject...) {
emit(event, withItems: items)
}
/**
Same as emit, but meant for Objective-C
*/
public func emit(event: String, withItems items: [AnyObject]) {
guard status == .Connected else {
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
return
}
dispatch_async(emitQueue) {
self._emit([event] + items)
}
}
/**
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
an ack.
*/
public func emitWithAck(event: String, _ items: AnyObject...) -> OnAckCallback {
return emitWithAck(event, withItems: items)
}
/**
Same as emitWithAck, but for Objective-C
*/
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
return createOnAck([event] + items)
}
private func _emit(data: [AnyObject], ack: Int? = nil) {
guard status == .Connected else {
handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
return
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str)
engine?.send(str, withData: packet.binary)
}
// If the server wants to know that the client received data
func emitAck(ack: Int, withItems items: [AnyObject]) {
dispatch_async(emitQueue) {
if self.status == .Connected {
let packet = SocketPacket.packetFromEmit(items, id: ack ?? -1, nsp: self.nsp, ack: true)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting Ack: %@", type: self.logType, args: str)
self.engine?.send(str, withData: packet.binary)
}
}
}
public func engineDidClose(reason: String) {
waitingData.removeAll()
if status == .Closed || !reconnects {
didDisconnect(reason)
} else if status != .Reconnecting {
status = .Reconnecting
handleEvent("reconnect", data: [reason], isInternalMessage: true)
tryReconnect()
}
}
// Called when the socket gets an ack for something it sent
func handleAck(ack: Int, data: AnyObject?) {
guard status == .Connected else {return}
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
ackHandlers.executeAck(ack,
items: (data as? [AnyObject]) ?? (data != nil ? [data!] : []))
}
/**
Causes an event to be handled. Only use if you know what you're doing.
*/
public func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool,
withAck ack: Int = -1) {
guard status == .Connected || isInternalMessage else {
return
}
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
dispatch_async(handleQueue) {
self.anyHandler?(SocketAnyEvent(event: event, items: data))
for handler in self.handlers where handler.event == event {
handler.executeCallback(data, withAck: ack, withSocket: self)
}
}
}
/**
Leaves nsp and goes back to /
*/
public func leaveNamespace() {
if nsp != "/" {
engine?.send("1\(nsp)", withData: [])
nsp = "/"
}
}
/**
Joins nsp if it is not /
*/
public func joinNamespace() {
DefaultSocketLogger.Logger.log("Joining namespace", type: logType)
if nsp != "/" {
engine?.send("0\(nsp)", withData: [])
}
}
/**
Joins namespace /
*/
public func joinNamespace(namespace: String) {
self.nsp = namespace
joinNamespace()
}
/**
Removes handler(s)
*/
public func off(event: String) {
DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: logType, args: event)
handlers = handlers.filter { $0.event != event }
}
/**
Removes a handler with the specified UUID gotten from an `on` or `once`
*/
public func off(id id: NSUUID) {
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id)
handlers = handlers.filter { $0.id != id }
}
/**
Adds a handler for an event.
Returns: A unique id for the handler
*/
public func on(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: logType, args: event)
let handler = SocketEventHandler(event: event, id: NSUUID(), callback: callback)
handlers.append(handler)
return handler.id
}
/**
Adds a single-use handler for an event.
Returns: A unique id for the handler
*/
public func once(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event)
let id = NSUUID()
let handler = SocketEventHandler(event: event, id: id) {[weak self] data, ack in
guard let this = self else {return}
this.off(id: id)
callback(data, ack)
}
handlers.append(handler)
return handler.id
}
/**
Adds a handler that will be called on every event.
*/
public func onAny(handler: (SocketAnyEvent) -> Void) {
anyHandler = handler
}
/**
Same as connect
*/
public func open() {
connect()
}
public func parseSocketMessage(msg: String) {
dispatch_async(parseQueue) {
SocketParser.parseSocketMessage(msg, socket: self)
}
}
public func parseBinaryData(data: NSData) {
dispatch_async(parseQueue) {
SocketParser.parseBinaryData(data, socket: self)
}
}
/**
Tries to reconnect to the server.
*/
public func reconnect() {
tryReconnect()
}
/**
Removes all handlers.
Can be used after disconnecting to break any potential remaining retain cycles.
*/
public func removeAllHandlers() {
handlers.removeAll(keepCapacity: false)
}
private func tryReconnect() {
if reconnectTimer == nil {
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
status = .Reconnecting
dispatch_async(dispatch_get_main_queue()) {
self.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self.reconnectWait),
target: self, selector: "_tryReconnect", userInfo: nil, repeats: true)
self.reconnectTimer?.fire()
}
}
}
@objc private func _tryReconnect() {
if status == .Connected {
clearReconnectTimer()
return
}
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
clearReconnectTimer()
didDisconnect("Reconnect Failed")
return
}
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
isInternalMessage: true)
currentReconnectAttempt++
connect()
}
}
// Test extensions
extension SocketIOClient {
var testHandlers: [SocketEventHandler] {
return handlers
}
func setTestable() {
status = .Connected
}
func setTestEngine(engine: SocketEngineSpec?) {
self.engine = engine
}
func emitTest(event: String, _ data: AnyObject...) {
self._emit([event] + data)
}
}
| mit |
yoichitgy/SwinjectMVVMExample_ForBlog | Carthage/Checkouts/Himotoki/Tests/RawRepresentableTest.swift | 3 | 1277 | //
// RawRepresentableTest.swift
// Himotoki
//
// Created by Syo Ikeda on 9/27/15.
// Copyright ยฉ 2015 Syo Ikeda. All rights reserved.
//
import XCTest
import Himotoki
enum StringEnum: String {
case A, B, C
}
enum IntEnum: Int {
case Zero, One
}
enum DoubleEnum: Double {
case One = 1.0
case Two = 2.0
}
extension StringEnum: Decodable {}
extension IntEnum: Decodable {}
extension DoubleEnum: Decodable {}
class RawRepresentableTest: XCTestCase {
func testRawRepresentable() {
let JSON: [String: AnyObject] = [
"string_1": "A",
"string_2": "D",
"int_1": 1,
"int_2": 3,
"double_1": 2.0,
"double_2": 4.0,
]
let e: Extractor = try! decode(JSON)
let A: StringEnum? = try? e <| "string_1"
let D: StringEnum? = try? e <| "string_2"
XCTAssert(A == .A)
XCTAssert(D == nil)
let int1: IntEnum? = try? e <| "int_1"
let int3: IntEnum? = try? e <| "int_3"
XCTAssert(int1 == .One)
XCTAssert(int3 == nil)
let double2: DoubleEnum? = try? e <| "double_1"
let double4: DoubleEnum? = try? e <| "double_2"
XCTAssert(double2 == .Two)
XCTAssert(double4 == nil)
}
}
| mit |
austinzheng/swift | validation-test/compiler_crashers_fixed/27843-llvm-foldingset-swift-classtype-nodeequals.swift | 65 | 451 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct S<T{let:{class b.protocol P{func f func f:T.C
| apache-2.0 |
kzietek/SampleApp | KZSampleApp/Modules/DemoFlow/SelectionDetailsScreen/Interactor/SelectionDetailsScreenInteractor.swift | 1 | 918 | //
// SelectionDetailsScreenInteractor.swift
// KZSampleApp
//
// Created by Kamil Ziฤtek on 04.07.2017.
// Copyright ยฉ 2017 Kamil Ziฤtek. All rights reserved.
//
import Foundation
protocol SelectionDetailsScreenInteracting {
func viewDidLoad()
var controller: SelectionDetailsViewControlling? { get set }
}
fileprivate struct Constants {
static let resultFormat = NSLocalizedString("And the result is... <%@>", comment: "Result format on SelectionDetailsScreen")
}
final class SelectionDetailsScreenInteractor: SelectionDetailsScreenInteracting {
var controller: SelectionDetailsViewControlling?
let result: SelectionResult
required init(result:SelectionResult) {
self.result = result
}
func viewDidLoad() {
let displayText = String(format: Constants.resultFormat, result.description)
controller?.setSelectionLabelText(displayText)
}
}
| mit |
benlangmuir/swift | test/IRGen/temporary_allocation/non_power2_alignment.swift | 9 | 347 | // RUN: not %target-swift-frontend -primary-file %s -O -emit-ir -o /dev/null 2>&1 | %FileCheck %s
@_silgen_name("blackHole")
func blackHole(_ value: UnsafeMutableRawPointer?) -> Void
withUnsafeTemporaryAllocation(byteCount: 1, alignment: 3) { buffer in
blackHole(buffer.baseAddress)
}
// CHECK: error: alignment value must be a power of two
| apache-2.0 |
Ben21hao/edx-app-ios-enterprise-new | Test/RatingViewControllerTests.swift | 1 | 4597 | //
// RatingViewControllerTests.swift
// edX
//
// Created by Danial Zahid on 2/7/17.
// Copyright ยฉ 2017 edX. All rights reserved.
//
import XCTest
@testable import edX
class RatingViewControllerTests: SnapshotTestCase {
let environment = TestRouterEnvironment()
func testDefaultContent() {
let controller = RatingViewController(environment: environment)
inScreenNavigationContext(controller) {
assertSnapshotValidWithContent(controller.navigationController!)
}
}
func testFilledStars() {
let controller = RatingViewController(environment: environment)
controller.setRating(5)
inScreenNavigationContext(controller) {
assertSnapshotValidWithContent(controller.navigationController!)
}
}
func testPositiveRating() {
let controller = RatingViewController(environment: environment)
controller.setRating(RatingViewController.minimumPositiveRating)
controller.didSubmitRating(RatingViewController.minimumPositiveRating)
XCTAssertEqual(controller.alertController?.actions.count, 2)
}
func testNegativeRating() {
let controller = RatingViewController(environment: environment)
controller.setRating(RatingViewController.minimumPositiveRating-1)
controller.didSubmitRating(RatingViewController.minimumPositiveRating-1)
XCTAssertEqual(controller.alertController?.actions.count, 2)
}
func testCanShowAppReview() {
let defaultsMockRemover = OEXMockUserDefaults().installAsStandardUserDefaults()
let config = OEXConfig(dictionary: [
"APP_REVIEWS_ENABLED": true,
"APP_REVIEW_URI" : "www.test.com"
])
let interface = OEXInterface()
interface.reachable = true
let testEnvironment = TestRouterEnvironment(config: config, interface: interface)
XCTAssertTrue(RatingViewController.canShowAppReview(testEnvironment))
defaultsMockRemover.remove()
}
func testCanShowAppReviewForAppReviewsDisabled() {
let defaultsMockRemover = OEXMockUserDefaults().installAsStandardUserDefaults()
let config = OEXConfig(dictionary: [
"APP_REVIEWS_ENABLED": false,
"APP_REVIEW_URI" : "www.test.com"
])
let interface = OEXInterface()
interface.reachable = true
let testEnvironment = TestRouterEnvironment(config: config, interface: interface)
XCTAssertFalse(RatingViewController.canShowAppReview(testEnvironment))
defaultsMockRemover.remove()
}
func testCanShowAppReviewForNilAppURI() {
let defaultsMockRemover = OEXMockUserDefaults().installAsStandardUserDefaults()
let config = OEXConfig(dictionary: [
"APP_REVIEWS_ENABLED": true,
])
let interface = OEXInterface()
interface.reachable = true
let testEnvironment = TestRouterEnvironment(config: config, interface: interface)
XCTAssertFalse(RatingViewController.canShowAppReview(testEnvironment))
defaultsMockRemover.remove()
}
func testCanShowAppReviewForPositiveRating() {
let defaultsMockRemover = OEXMockUserDefaults().installAsStandardUserDefaults()
let config = OEXConfig(dictionary: [
"APP_REVIEWS_ENABLED": true,
"APP_REVIEW_URI" : "www.test.com"
])
let interface = OEXInterface()
interface.reachable = true
interface.saveAppVersionWhenLastRated()
interface.saveAppRating(RatingViewController.minimumPositiveRating)
let testEnvironment = TestRouterEnvironment(config: config, interface: interface)
XCTAssertFalse(RatingViewController.canShowAppReview(testEnvironment))
defaultsMockRemover.remove()
}
func testCanShowAppReviewForNegativeRating() {
let defaultsMockRemover = OEXMockUserDefaults().installAsStandardUserDefaults()
let config = OEXConfig(dictionary: [
"APP_REVIEWS_ENABLED": true,
"APP_REVIEW_URI" : "www.test.com"
])
let interface = OEXInterface()
interface.reachable = true
interface.saveAppRating(RatingViewController.minimumPositiveRating-1)
interface.saveAppVersionWhenLastRated(nil)
let testEnvironment = TestRouterEnvironment(config: config, interface: interface)
XCTAssertFalse(RatingViewController.canShowAppReview(testEnvironment))
defaultsMockRemover.remove()
}
}
| apache-2.0 |
josipbernat/DrawingPlayground | Drawing.playground/Sources/CoreGraphics.swift | 1 | 1520 | import UIKit
import CoreGraphics
//MARK: - CoreGraphicsView
public class CoreGraphicsView : UIView {
override public func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
// Save Context
CGContextSaveGState(context)
// Call draw and enable renderer for drawing.
draw(context)
// Restore Context
CGContextRestoreGState(context)
}
public var draw: (CGContext)->() = { _ in () }
}
//MARK: - The Real Thing - Core Graphics
extension CGContext : Renderer {
public func moveTo(p: CGPoint) {
CGContextMoveToPoint(self, p.x, p.y)
}
public func lineTo(p: CGPoint) {
CGContextAddLineToPoint(self, p.x, p.y)
}
public func closePath() {
CGContextClosePath(self)
CGContextDrawPath(self, kCGPathEOFillStroke)
}
public func arcAt(center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat) {
let arc = CGPathCreateMutable()
CGPathAddArc(arc, nil, center.x, center.y, radius, startAngle, endAngle, true)
CGContextAddPath(self, arc)
}
public func setLineWidth(width: CGFloat) {
CGContextSetLineWidth(self, width)
}
public func setStrokeColor(color: UIColor) {
CGContextSetStrokeColorWithColor(self, color.CGColor)
}
public func setFillColor(color: UIColor) {
CGContextSetFillColorWithColor(self, color.CGColor)
}
} | mit |
syxc/ZhihuDaily | ZhihuDaily/Classes/API/ZhihuAPI.swift | 1 | 825 | //
// ZhihuAPI.swift
// ZhihuDaily
//
// Created by syxc on 15/12/5.
// Copyright ยฉ 2015ๅนด syxc. All rights reserved.
//
import Foundation
import PromiseKit
/* typealias Callback = (AnyObject?, NSError?) -> Void */
protocol ZhihuAPI {
/**
่ทๅๅฏๅจๅพ็ไฟกๆฏ
```
ๅพๅๅ่พจ็ๆฅๅๅฆไธๆ ผๅผ
- 320*432
- 480*728
- 720*1184
- 1080*1776
```
- parameter resolution: ๅพๅๅ่พจ็
- returns: `Promise<Splash>`
*/
func fetchSplashScreen(resolution: SplashResolution) -> Promise<Splash>
/**
่ทๅๆๆฐๆถๆฏ
- returns: `Promise<LatestNews>`
*/
func fetchLatestNews() -> Promise<LatestNews>
/**
่ทๅๆฐ้ป่ฏฆๆ
- parameter id: ๆฐ้ปID
- returns: `Promise<News>`
*/
func fetchNewsDetail(id: String) -> Promise<News>
}
| mit |
medvedzzz/FrameLayout | FrameLayout/Extensions/CALayer+FrameLayoutSupport.swift | 1 | 897 | //
// CALayer+FrameLayoutSupport.swift
// SwiftLayoutExample
//
// Created by Evgeny Mikhaylov on 14/12/2016.
// Copyright ยฉ 2016 Evgeny Mikhaylov. All rights reserved.
//
import QuartzCore
extension CALayer: FrameLayoutSupport {
#if os(OSX)
override open class func initialize() {
if self != CALayer.self {
return
}
let swizzlingClosure: () = {
CALayer.swizzle(#selector(layoutSublayers), with: #selector(fl_layoutChilds))
}()
swizzlingClosure
}
@objc private func fl_layoutChilds() {
fl_layoutChilds()
frameLayout.didLayoutChilds()
}
#endif
public var parent: FrameLayoutSupport? {
return superlayer
}
public var childs: [FrameLayoutSupport] {
guard let sublayers = sublayers else {
return []
}
return sublayers
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Views/SegmentedView/SegmentedTabViewController/SegmentedTabViewController.swift | 1 | 3730 | // Copyright ยฉ Blockchain Luxembourg S.A. All rights reserved.
import RxRelay
import RxSwift
import ToolKit
/// `SegmentedTabViewController` should be a `child` of `SegmentedViewController`.
/// The `UITabBar` is hidden. Upon selecting an index of the `UISegmentedControl`
/// we select the appropriate `UIViewController`. Having a `UITabBarController` gives us
/// lifecycle events that are the same as a `UITabBarController` while using the segmented control.
/// This also gives us the option to include custom transitions.
public final class SegmentedTabViewController: UITabBarController {
// MARK: - Public Properties
let itemIndexSelectedRelay = PublishRelay<(index: Int, animated: Bool)>()
public var segmentedViewControllers: [SegmentedViewScreenViewController] {
items.map(\.viewController)
}
// MARK: - Private Properties
private let items: [SegmentedViewScreenItem]
private let disposeBag = DisposeBag()
// MARK: - Init
required init?(coder: NSCoder) { unimplemented() }
public init(items: [SegmentedViewScreenItem]) {
self.items = items
super.init(nibName: nil, bundle: nil)
}
// MARK: - Lifecycle
override public func viewDidLoad() {
super.viewDidLoad()
setViewControllers(
items.map(\.viewController),
animated: false
)
tabBar.isHidden = true
itemIndexSelectedRelay
.map(weak: self) { (self, value) in
(self.viewControllers?[value.index], value.animated)
}
.bindAndCatch(weak: self) { (self, value) in
guard let vc = value.0 else { return }
self.setSelectedViewController(vc, animated: value.1)
}
.disposed(by: disposeBag)
}
private func setSelectedViewController(_ viewController: UIViewController, animated: Bool) {
guard animated else {
selectedViewController = viewController
return
}
guard let fromView = selectedViewController?.view,
let toView = viewController.view,
fromView != toView,
let controllerIndex = viewControllers?.firstIndex(of: viewController)
else {
return
}
let viewSize = fromView.frame
let scrollRight = controllerIndex > selectedIndex
// Avoid UI issues when switching tabs fast
guard fromView.superview?.subviews.contains(toView) == false else {
return
}
fromView.superview?.addSubview(toView)
let screenWidth = view.frame.width
toView.frame = CGRect(
x: scrollRight ? screenWidth : -screenWidth,
y: viewSize.origin.y,
width: screenWidth,
height: viewSize.size.height
)
UIView.animate(
withDuration: 0.25,
delay: 0,
options: [.curveEaseOut, .preferredFramesPerSecond60],
animations: {
fromView.frame = CGRect(
x: scrollRight ? -screenWidth : screenWidth,
y: viewSize.origin.y,
width: screenWidth,
height: viewSize.size.height
)
toView.frame = CGRect(
x: 0,
y: viewSize.origin.y,
width: screenWidth,
height: viewSize.size.height
)
},
completion: { [weak self] finished in
if finished {
fromView.removeFromSuperview()
self?.selectedIndex = controllerIndex
}
}
)
}
}
| lgpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/CryptoAssets/Sources/BitcoinChainKit/Transactions/NativeBitcoin/Models/WalletKeyPair.swift | 1 | 316 | // Copyright ยฉ Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public struct WalletKeyPair {
/// The wallet private key
public let xpriv: String
/// The wallet private key data
public let privateKeyData: Data
/// The wallet extended public key
public let xpub: XPub
}
| lgpl-3.0 |
rahulnadella/CalculationUtility | src/CalculationUtility.swift | 1 | 46741 | /*
The MIT License (MIT)
Copyright (c) 2015 Rahul Nadella http://github.com/rahulnadella
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 CoreGraphics
import Foundation
/*
The NumericType protocol has the common requirements for types that support
arithmetic operators that take numerical values (either literals or variables)
as their operands and return a single numerical value. The standard arithmetic
operators are addition (+), subtraction (-), multiplication (*), and division (/).
:version 1.0
*/
protocol NumericType
{
/*
Add `lhs` and `rhs`, returns a result and trapping in case of
arithmetic overflow.
*/
func +(lhs: Self, rhs: Self) -> Self
/*
Subtract `lhs` and `rhs`, returns a result and trapping in case of
arithmetic overflow.
*/
func -(lhs: Self, rhs: Self) -> Self
/*
Multiply `lhs` and `rhs`, returns a result and trapping in case of
arithmetic overflow.
*/
func *(lhs: Self, rhs: Self) -> Self
/*
Divide `lhs` and `rhs`, returns a result and trapping in case of
arithmetic overflow.
*/
func /(lhs: Self, rhs: Self) -> Self
/*
Divide `lhs` and `rhs`, returns the remainder and trapping in case of
arithmetic overflow.
*/
func %(lhs: Self, rhs: Self) -> Self
/*
`lhs` is less than 'rhs' returns true otherwise false
*/
func <(lhs: Self, rhs: Self) -> Bool
/*
`lhs` is greater than 'rhs' returns true otherwise false
*/
func >(lhs: Self, rhs: Self) -> Bool
/*
Initializer for NumericType that currently takes not arguments
*/
init()
}
/*
All of the numeric types already implement these, but at this point the compiler
doesnโt know that they conform to the new NumericType protocol. This done through
an Extension (in Swift also known as a Category in Objective-C).
Apple calls this โdeclaring protocol adoption with an extension.โ
*/
extension Double : NumericType {}
extension Float : NumericType {}
extension Int : NumericType {}
extension Int8 : NumericType {}
extension Int16 : NumericType {}
extension Int32 : NumericType {}
extension Int64 : NumericType {}
extension UInt : NumericType {}
extension UInt8 : NumericType {}
extension UInt16 : NumericType {}
extension UInt32 : NumericType {}
extension UInt64 : NumericType {}
//MARK: ###########################Summation Functions###########################
/* The SUMMATION Prefix (similiar to ++counter) */
prefix operator โ {}
/*
The prefix of the sum function using an Array.
:param T
The Array of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
prefix func โ<T: NumericType>(input: [T]) -> T
{
return sumOf(input)
}
/*
The prefix of the sum function using a specific section of MutableCollectionType
:param T
The MutableCollectionType (Array, etc.) of specific NumericType
(using the NumericType protocol as a generic constraint, and call
it with any numeric type we like for instance, Double, Float, Int, etc.)
*/
prefix func โ<T: NumericType>(input : ArraySlice<T>) -> T
{
return sumOf(input)
}
/*
The sumOf function using variable arguments of specific NumericType (Double, Float, Int, etc.).
:param T
The variable arguments of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
func sumOf<T: NumericType>(input : T...) -> T
{
return sumOf(input)
}
/*
The sumOf function using MutableCollectionType (for instance, Array, Set, etc.) of specific
NumericType (Double, Float, Int, etc.).
:param T
The MutableCollectionType of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.))
*/
func sumOf<T: NumericType>(input : ArraySlice<T>) -> T
{
return sumOf([] + input)
}
/*
The sumOf function of the array of specific NumericType (Double, Float, Int, etc.).
:param T
The Array of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
func sumOf<T: NumericType>(input : [T]) -> T
{
return reduce(input, T()) {$0 + $1}
}
//MARK: ################################Factorial################################
/* The FACTORIAL Postfix (similiar to counter++) */
postfix operator ~! {}
/*
The prefix of the factorial function using an IntegerType.
:param T
The specific Integer (greater than 0) value used to calculate the factorial value
:return The factorial of a positive Integer greater than 1
*/
postfix public func ~! <T: IntegerType>(var num: T) -> T
{
assert(num > 0, "Factorial function can not receive a number less than 1")
var result: T = 1
while (num > 1)
{
result = result * num
num--
}
return result
}
//MARK: ###########################Multiplication Functions###########################
/* The MULTIPLY Prefix (similiar to ++counter) */
prefix operator โ {}
/*
The prefix of the multiply function using an Array.
:param T
The Array of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
prefix func โ<T: NumericType>(input: [T]) -> T
{
return productOf(input)
}
/*
The prefix of the multiply function using a specific section of MutableCollectionType
:param T
The MutableCollectionType (Array, etc.) of specific NumericType
(using the NumericType protocol as a generic constraint, and call
it with any numeric type we like for instance, Double, Float, Int, etc.)
*/
prefix func โ<T: NumericType>(input : ArraySlice<T>) -> T
{
return productOf(input)
}
/*
The productOf function using variable arguments of specific NumericType (Double, Float, Int, etc.).
:param T
The variable arguments of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
func productOf<T: NumericType>(input : T...) -> T
{
return productOf(input)
}
/*
The productOf function using MutableCollectionType (for instance, Array, Set, etc.) of specific
NumericType (Double, Float, Int, etc.).
:param T
The MutableCollectionType of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.))
*/
func productOf<T: NumericType>(input : ArraySlice<T>) -> T
{
return productOf([] + input)
}
/*
The productOf function of the array of specific NumericType (Double, Float, Int, etc.).
:param T
The Array of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
func productOf<T: NumericType>(var input : [T]) -> T
{
return input.count == 0 ? T() : reduce(input[1..<input.count], input[0]) {$0 * $1}
}
//MARK: ###########Additional Functions for Calculated Numerical Values###########
/*
The squared function returns a NumericTypeยฒ (nยฒ = n x n)
:param T
The specific NumberType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
func squared<T : NumericType>(number: T) -> T
{
/* Uses * Operator */
return number * number
}
/*
The cubic function returns a NumericTypeยณ (nยณ = n ร n ร n).
:param T
The specific NumberType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
func cubed<T : NumericType>(number : T) -> T
{
return number * number * number
}
/*
The min function returns the minimum value within the Collection
:param T
The Collection consisting of specific values
*/
func min<T : Comparable> (input : [T]) -> T
{
return reduce(input, input[0]) {$0 > $1 ? $1 : $0}
}
/*
The max function returns the maximum value within the Collection
:param T
The Collection consisting of specific values
*/
func max<T : Comparable> (input : [T]) -> T
{
return reduce(input, input[0]) {$0 < $1 ? $1 : $0}
}
//MARK: ####################Explicit Addition (+) Cast Functions####################
/*
The + function overloaded to take the parameters of Int,Double and return
an explicit conversion of a Double.
:param lhs
The Integer value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func +(lhs: Int, rhs: Double) -> Double
{
return Double(lhs) + rhs
}
/*
The + function overloaded to take the parameters of Double,Int and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Integer value
:return An explicitly cast Double value
*/
func +(lhs: Double, rhs: Int) -> Double
{
return lhs + Double(rhs)
}
/*
The + function overloaded to take the parameters of Int,Float and return
an explicit conversion of a Float.
:param lhs
The Integer value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func +(lhs: Int, rhs: Float) -> Float
{
return Float(lhs) + rhs
}
/*
The + function overloaded to take the parameters of Float,Int and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The Integer value
:return An explicitly cast Float value
*/
func +(lhs: Float, rhs: Int) -> Float
{
return lhs + Float(rhs)
}
/*
The + function overloaded to take the parameters of Float,Double and return
an explicit conversion of a Double.
:param lhs
The Float value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func +(lhs: Float, rhs: Double) -> Double
{
return Double(lhs) + rhs
}
/*
The + function overloaded to take the parameters of Double,Float and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Float value
:return An explicitly cast Double value
*/
func +(lhs: Double, rhs: Float) -> Double
{
return lhs + Double(rhs)
}
/*
The + function overloaded to take the parameters of UInt,Double and return
an explicit conversion of a Double.
:param lhs
The UInt value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func +(lhs: UInt, rhs: Double) -> Double
{
return Double(lhs) + rhs
}
/*
The + function overloaded to take the parameters of Double,UInt and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The UInt value
:return An explicitly cast Double value
*/
func +(lhs: Double, rhs: UInt) -> Double
{
return lhs + Double(rhs)
}
/*
The + function overloaded to take the parameters of UInt,Float and return
an explicit conversion of a Float.
:param lhs
The UInt value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func +(lhs: UInt, rhs: Float) -> Float
{
return Float(lhs) + rhs
}
/*
The + function overloaded to take the parameters of Float,UInt and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The UInt value
:return An explicitly cast Float value
*/
func +(lhs: Float, rhs: UInt) -> Float
{
return lhs + Float(rhs)
}
//MARK: ####################Explicit Subtraction (-) Cast Functions####################
/*
The - function overloaded to take the parameters of Int,Double and return
an explicit conversion of a Double.
:param lhs
The Integer value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func -(lhs: Int, rhs: Double) -> Double
{
return Double(lhs) - rhs
}
/*
The - function overloaded to take the parameters of Double,Int and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Integer value
:return An explicitly cast Double value
*/
func -(lhs: Double, rhs: Int) -> Double
{
return lhs - Double(rhs)
}
/*
The - function overloaded to take the parameters of Int,Float and return
an explicit conversion of a Float.
:param lhs
The Int value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func -(lhs: Int, rhs: Float) -> Float
{
return Float(lhs) - rhs
}
/*
The - function overloaded to take the parameters of Float,Int and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The Int value
:return An explicitly cast Float value
*/
func -(lhs: Float, rhs: Int) -> Float
{
return lhs - Float(rhs)
}
/*
The - function overloaded to take the parameters of Float,Double and return
an explicit conversion of a Double.
:param lhs
The Float value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func -(lhs: Float, rhs: Double) -> Double
{
return Double(lhs) - rhs
}
/*
The - function overloaded to take the parameters of Double,Float and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Float value
:return An explicitly cast Double value
*/
func -(lhs: Double, rhs: Float) -> Double
{
return lhs - Double(rhs)
}
/*
The - function overloaded to take the parameters of UInt,Double and return
an explicit conversion of a Double.
:param lhs
The UInt value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func -(lhs: UInt, rhs: Double) -> Double
{
return Double(lhs) - rhs
}
/*
The - function overloaded to take the parameters of Double,UInt and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The UInt value
:return An explicitly cast Double value
*/
func -(lhs: Double, rhs: UInt) -> Double
{
return lhs - Double(rhs)
}
/*
The - function overloaded to take the parameters of UInt,Float and return
an explicit conversion of a Float.
:param lhs
The UInt value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func -(lhs: UInt, rhs: Float) -> Float
{
return Float(lhs) - rhs
}
/*
The - function overloaded to take the parameters of Float,UInt and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The UInt value
:return An explicitly cast Float value
*/
func -(lhs: Float, rhs: UInt) -> Float
{
return lhs - Float(rhs)
}
//MARK: ####################Explicit Multiplication (*) Cast Functions####################
/*
The * function overloaded to take the parameters of Int,Double and return
an explicit conversion of a Double.
:param lhs
The Int value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func *(lhs: Int, rhs: Double) -> Double
{
return Double(lhs) * rhs
}
/*
The * function overloaded to take the parameters of Double,Int and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Int value
:return An explicitly cast Double value
*/
func *(lhs: Double, rhs: Int) -> Double
{
return lhs * Double(rhs)
}
/*
The * function overloaded to take the parameters of Int,Float and return
an explicit conversion of a Float.
:param lhs
The Int value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func *(lhs: Int, rhs: Float) -> Float
{
return Float(lhs) * rhs
}
/*
The * function overloaded to take the parameters of Float,Int and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The Int value
:return An explicitly cast Float value
*/
func *(lhs: Float, rhs: Int) -> Float
{
return lhs * Float(rhs)
}
/*
The * function overloaded to take the parameters of Float,Double and return
an explicit conversion of a Double.
:param lhs
The Float value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func *(lhs: Float, rhs: Double) -> Double
{
return Double(lhs) * rhs
}
/*
The * function overloaded to take the parameters of Double,Float and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Float value
:return An explicitly cast Double value
*/
func *(lhs: Double, rhs: Float) -> Double
{
return lhs * Double(rhs)
}
/*
The * function overloaded to take the parameters of UInt,Double and return
an explicit conversion of a Double.
:param lhs
The UInt value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func *(lhs: UInt, rhs: Double) -> Double
{
return Double(lhs) * rhs
}
/*
The * function overloaded to take the parameters of Double,UInt and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The UInt value
:return An explicitly cast Double value
*/
func *(lhs: Double, rhs: UInt) -> Double
{
return lhs * Double(rhs)
}
/*
The * function overloaded to take the parameters of UInt,Float and return
an explicit conversion of a Float.
:param lhs
The UInt value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func *(lhs: UInt, rhs: Float) -> Float
{
return Float(lhs) * rhs
}
/*
The * function overloaded to take the parameters of Float,UInt and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The UInt value
:return An explicitly cast Float value
*/
func *(lhs: Float, rhs: UInt) -> Float
{
return lhs * Float(rhs)
}
//MARK: ####################Explicit Division (/) Cast Functions####################
/*
The / function overloaded to take the parameters of Int,Double and return
an explicit conversion of a Double.
:param lhs
The Int value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func /(lhs: Int, rhs: Double) -> Double
{
return Double(lhs) / rhs
}
/*
The / function overloaded to take the parameters of Double,Int and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Int value
:return An explicitly cast Double value
*/
func /(lhs: Double, rhs: Int) -> Double
{
return lhs / Double(rhs)
}
/*
The / function overloaded to take the parameters of Int,Float and return
an explicit conversion of a Float.
:param lhs
The Int value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func /(lhs: Int, rhs: Float) -> Float
{
return Float(lhs) / rhs
}
/*
The / function overloaded to take the parameters of Float,Int and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The Int value
:return An explicitly cast Float value
*/
func /(lhs: Float, rhs: Int) -> Float
{
return lhs / Float(rhs)
}
/*
The / function overloaded to take the parameters of Float,Double and return
an explicit conversion of a Double.
:param lhs
The Float value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func /(lhs: Float, rhs: Double) -> Double
{
return Double(lhs) / rhs
}
/*
The / function overloaded to take the parameters of Double,Float and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Float value
:return An explicitly cast Double value
*/
func /(lhs: Double, rhs: Float) -> Double
{
return lhs / Double(rhs)
}
/*
The / function overloaded to take the parameters of UInt,Double and return
an explicit conversion of a Double.
:param lhs
The UInt value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func /(lhs: UInt, rhs: Double) -> Double
{
return Double(lhs) / rhs
}
/*
The / function overloaded to take the parameters of Double,UInt and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The UInt value
:return An explicitly cast Double value
*/
func /(lhs: Double, rhs: UInt) -> Double
{
return lhs / Double(rhs)
}
/*
The / function overloaded to take the parameters of UInt,Float and return
an explicit conversion of a Float.
:param lhs
The UInt value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func /(lhs: UInt, rhs: Float) -> Float
{
return Float(lhs) / rhs
}
/*
The / function overloaded to take the parameters of Float,UInt and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The UInt value
:return An explicitly cast Float value
*/
func /(lhs: Float, rhs: UInt) -> Float
{
return lhs / Float(rhs)
}
//MARK: ####################Explicit Modulus (%) Cast Functions####################
/*
The % function overloaded to take the parameters of Int,Double and return
an explicit conversion of a Double.
:param lhs
The Int value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func %(lhs: Int, rhs: Double) -> Double
{
return Double(lhs) % rhs
}
/*
The % function overloaded to take the parameters of Double,Int and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Int value
:return An explicitly cast Double value
*/
func %(lhs: Double, rhs: Int) -> Double
{
return lhs % Double(rhs)
}
/*
The % function overloaded to take the parameters of Int,Float and return
an explicit conversion of a Float.
:param lhs
The Int value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func %(lhs: Int, rhs: Float) -> Float
{
return Float(lhs) % rhs
}
/*
The % function overloaded to take the parameters of Float,Int and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The Int value
:return An explicitly cast Float value
*/
func %(lhs: Float, rhs: Int) -> Float
{
return lhs % Float(rhs)
}
/*
The % function overloaded to take the parameters of Float,Double and return
an explicit conversion of a Double.
:param lhs
The Float value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func %(lhs: Float, rhs: Double) -> Double
{
return Double(lhs) % rhs
}
/*
The % function overloaded to take the parameters of Double,Float and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Float value
:return An explicitly cast Double value
*/
func %(lhs: Double, rhs: Float) -> Double
{
return lhs % Float(rhs)
}
/*
The % function overloaded to take the parameters of UInt,Double and return
an explicit conversion of a Double.
:param lhs
The UInt value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func %(lhs: UInt, rhs: Double) -> Double
{
return Double(lhs) % rhs
}
/*
The % function overloaded to take the parameters of Double,UInt and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The UInt value
:return An explicitly cast Double value
*/
func %(lhs: Double, rhs: UInt) -> Double
{
return lhs % Double(rhs)
}
/*
The % function overloaded to take the parameters of UInt,Float and return
an explicit conversion of a Float.
:param lhs
The UInt value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func %(lhs: UInt, rhs: Float) -> Float
{
return Float(lhs) % rhs
}
/*
The % function overloaded to take the parameters of Float,UInt and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The UInt value
:return An explicitly cast Float value
*/
func %(lhs: Float, rhs: UInt) -> Float
{
return lhs % Float(rhs)
}
//MARK: ####################Explicit Less Than (<) Cast Functions####################
/*
The < function overloaded to take the parameters of Int,Double and return
a Boolean value to indicate a true (if Int is less than Double) otherwise
false (Double greater than Int)
:param lhs
The Int value
:param rhs
The Double value
:return An explicit cast less than Boolean value of true (Int less than Double) otherwise false
*/
func <(lhs: Int, rhs: Double) -> Bool
{
return Double(lhs) < rhs
}
/*
The < function overloaded to take the parameters of Double,Int and return
a Boolean value to indicate a true (if Double is less than Int) otherwise
false (Int greater than Double)
:param lhs
The Double value
:param rhs
The Int value
:return An explicit cast less than Boolean value of true (Double less than Int) otherwise false
*/
func <(lhs: Double, rhs: Int) -> Bool
{
return lhs < Double(rhs)
}
/*
The < function overloaded to take the parameters of Int,Float and return
a Boolean value to indicate a true (if Int is less than Float) otherwise
false (Float greater than Int)
:param lhs
The Int value
:param rhs
The Float value
:return An explicit cast less than Boolean value of true (Int less than Float) otherwise false
*/
func <(lhs: Int, rhs: Float) -> Bool
{
return Float(lhs) < rhs
}
/*
The < function overloaded to take the parameters of Float,Int and return
a Boolean value to indicate a true (if Float is less than Int) otherwise
false (Int greater than Float)
:param lhs
The Float value
:param rhs
The Int value
:return An explicit cast less than Boolean value of true (Float less than Int) otherwise false
*/
func <(lhs: Float, rhs: Int) -> Bool
{
return lhs < Float(rhs)
}
/*
The < function overloaded to take the parameters of Float,Double and return
a Boolean value to indicate a true (if Float is less than Double) otherwise
false (Double greater than Float)
:param lhs
The Float value
:param rhs
The Double value
:return An explicit cast less than Boolean value of true (Float less than Double) otherwise false
*/
func <(lhs: Float, rhs: Double) -> Bool
{
return Double(lhs) < rhs
}
/*
The < function overloaded to take the parameters of Double,Float and return
a Boolean value to indicate a true (if Double is less than Float) otherwise
false (Float greater than Double)
:param lhs
The Double value
:param rhs
The Float value
:return An explicit cast less than Boolean value of true (Double less than Float) otherwise false
*/
func <(lhs: Double, rhs: Float) -> Bool
{
return lhs < Double(rhs)
}
/*
The < function overloaded to take the parameters of UInt,Double and return
a Boolean value to indicate a true (if UInt is less than Double) otherwise
false (Double greater than UInt)
:param lhs
The UInt value
:param rhs
The Double value
:return An explicit cast less than Boolean value of true (UInt less than Double) otherwise false
*/
func <(lhs: UInt, rhs: Double) -> Bool
{
return Double(lhs) < rhs
}
/*
The < function overloaded to take the parameters of Double,UInt and return
a Boolean value to indicate a true (if Double is less than UInt) otherwise
false (UInt greater than Double)
:param lhs
The Double value
:param rhs
The UInt value
:return An explicit cast less than Boolean value of true (Double less than UInt) otherwise false
*/
func <(lhs: Double, rhs: UInt) -> Bool
{
return lhs < Double(rhs)
}
/*
The < function overloaded to take the parameters of UInt,Float and return
a Boolean value to indicate a true (if UInt is less than Float) otherwise
false (Float greater than UInt)
:param lhs
The UInt value
:param rhs
The Float value
:return An explicit cast less than Boolean value of true (UInt less than Float) otherwise false
*/
func <(lhs: UInt, rhs:Float) -> Bool
{
return Float(lhs) < rhs
}
/*
The < function overloaded to take the parameters of Float,UInt and return
a Boolean value to indicate a true (if Float is less than UInt) otherwise
false (UInt greater than Float)
:param lhs
The Float value
:param rhs
The UInt value
:return An explicit cast less than Boolean value of true (Float less than UInt) otherwise false
*/
func <(lhs: Float, rhs:UInt) -> Bool
{
return lhs < Float(rhs)
}
//MARK: ####################Explicit Greater Than (>) Cast Functions####################
/*
The > function overloaded to take the parameters of Int,Double and return
a Boolean value to indicate a true (if Int is greater than Double) otherwise
false (Double less than Int)
:param lhs
The Int value
:param rhs
The Double value
:return An explicit cast greater than Boolean value of true (Int greater than Double) otherwise false
*/
func >(lhs: Int, rhs: Double) -> Bool
{
return Double(lhs) > rhs
}
/*
The > function overloaded to take the parameters of Double,Int and return
a Boolean value to indicate a true (if Double is greater than Int) otherwise
false (Int less than Double)
:param lhs
The Double value
:param rhs
The Int value
:return An explicit cast greater than Boolean value of true (Double greater than Int) otherwise false
*/
func >(lhs: Double, rhs: Int) -> Bool
{
return lhs > Double(rhs)
}
/*
The > function overloaded to take the parameters of Int,Float and return
a Boolean value to indicate a true (if Int is greater than Float) otherwise
false (Float less than Int)
:param lhs
The Int value
:param rhs
The Float value
:return An explicit cast greater than Boolean value of true (Int greater than Float) otherwise false
*/
func >(lhs: Int, rhs: Float) -> Bool
{
return Float(lhs) > rhs
}
/*
The > function overloaded to take the parameters of Float,Int and return
a Boolean value to indicate a true (if Float is greater than Int) otherwise
false (Int less than Float)
:param lhs
The Float value
:param rhs
The Int value
:return An explicit cast greater than Boolean value of true (Float greater than Int) otherwise false
*/
func >(lhs: Float, rhs: Int) -> Bool
{
return lhs > Float(rhs)
}
/*
The > function overloaded to take the parameters of Float,Double and return
a Boolean value to indicate a true (if Float is greater than Double) otherwise
false (Double less than Float)
:param lhs
The Float value
:param rhs
The Double value
:return An explicit cast greater than Boolean value of true (Float greater than Double) otherwise false
*/
func >(lhs: Float, rhs: Double) -> Bool
{
return Double(lhs) > rhs
}
/*
The > function overloaded to take the parameters of Double,Float and return
a Boolean value to indicate a true (if Double is greater than Float) otherwise
false (Float less than Double)
:param lhs
The Double value
:param rhs
The Float value
:return An explicit cast greater than Boolean value of true (Double greater than Float) otherwise false
*/
func >(lhs: Double, rhs: Float) -> Bool
{
return lhs > Double(rhs)
}
/*
The > function overloaded to take the parameters of UInt,Double and return
a Boolean value to indicate a true (if UInt is greater than Double) otherwise
false (Double less than UInt)
:param lhs
The UInt value
:param rhs
The Double value
:return An explicit cast greater than Boolean value of true (UInt greater than Double) otherwise false
*/
func >(lhs: UInt, rhs: Double) -> Bool
{
return Double(lhs) > rhs
}
/*
The > function overloaded to take the parameters of Double,UInt and return
a Boolean value to indicate a true (if Double is greater than UInt) otherwise
false (UInt less than Double)
:param lhs
The Double value
:param rhs
The UInt value
:return An explicit cast greater than Boolean value of true (Double greater than UInt) otherwise false
*/
func >(lhs: Double, rhs: UInt) -> Bool
{
return lhs > Double(rhs)
}
/*
The > function overloaded to take the parameters of UInt,Float and return
a Boolean value to indicate a true (if UInt is greater than Float) otherwise
false (Float less than UInt)
:param lhs
The UInt value
:param rhs
The Float value
:return An explicit cast greater than Boolean value of true (UInt greater than Float) otherwise false
*/
func >(lhs: UInt, rhs:Float) -> Bool
{
return Float(lhs) > rhs
}
/*
The > function overloaded to take the parameters of Float,UInt and return
a Boolean value to indicate a true (if Float is greater than UInt) otherwise
false (UInt less than Float)
:param lhs
The Float value
:param rhs
The UInt value
:return An explicit cast greater than Boolean value of true (Float greater than UInt) otherwise false
*/
func >(lhs: Float, rhs:UInt) -> Bool
{
return lhs > Float(rhs)
}
//MARK: ##################Explicit CGFloat Addition (+) Cast Functions##################
/*
The + function overloaded to take the parameters of CGFloat,Float and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Float value
:return An explicitly cast CGFloat value
*/
func +(lhs: CGFloat, rhs: Float) -> CGFloat
{
return lhs + CGFloat(rhs)
}
/*
The + function overloaded to take the parameters of Float,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Float value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func +(lhs: Float, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) + rhs
}
/*
The + function overloaded to take the parameters of CGFloat,Double and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Double value
:return An explicitly cast CGFloat value
*/
func +(lhs: CGFloat, rhs: Double) -> CGFloat
{
return lhs + CGFloat(rhs)
}
/*
The + function overloaded to take the parameters of Double,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Double value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func +(lhs: Double, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) + rhs
}
/*
The + function overloaded to take the parameters of CGFloat,Int and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Int value
:return An explicitly cast CGFloat value
*/
func +(lhs: CGFloat, rhs: Int) -> CGFloat
{
return lhs + CGFloat(rhs)
}
/*
The + function overloaded to take the parameters of Int,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Int value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func +(lhs: Int, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) + rhs
}
/*
The + function overloaded to take the parameters of CGFloat,UInt and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The UInt value
:return An explicitly cast CGFloat value
*/
func +(lhs: CGFloat, rhs: UInt) -> CGFloat
{
return lhs + CGFloat(rhs)
}
/*
The + function overloaded to take the parameters of UInt,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The UInt value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func +(lhs: UInt, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) + rhs
}
//MARK: ##################Explicit CGFloat Subtraction (-) Cast Functions##################
/*
The - function overloaded to take the parameters of CGFloat,Float and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Float value
:return An explicitly cast CGFloat value
*/
func -(lhs: CGFloat, rhs: Float) -> CGFloat
{
return lhs - CGFloat(rhs)
}
/*
The - function overloaded to take the parameters of Float,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Float value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func -(lhs: Float, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) - rhs
}
/*
The - function overloaded to take the parameters of CGFloat,Double and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Double value
:return An explicitly cast CGFloat value
*/
func -(lhs: CGFloat, rhs: Double) -> CGFloat
{
return lhs - CGFloat(rhs)
}
/*
The - function overloaded to take the parameters of Double,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Double value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func -(lhs: Double, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) - rhs
}
/*
The - function overloaded to take the parameters of CGFloat,Int and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Int value
:return An explicitly cast CGFloat value
*/
func -(lhs: CGFloat, rhs: Int) -> CGFloat
{
return lhs - CGFloat(rhs)
}
/*
The - function overloaded to take the parameters of Int,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Int value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func -(lhs: Int, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) - rhs
}
/*
The - function overloaded to take the parameters of CGFloat,UInt and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The UInt value
:return An explicitly cast CGFloat value
*/
func -(lhs: CGFloat, rhs: UInt) -> CGFloat
{
return lhs - CGFloat(rhs)
}
/*
The - function overloaded to take the parameters of UInt,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The UInt value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func -(lhs: UInt, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) - rhs
}
//MARK: ##################Explicit CGFloat Multiplication (*) Cast Functions##################
/*
The * function overloaded to take the parameters of CGFloat,Float and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Float value
:return An explicitly cast CGFloat value
*/
func *(lhs: CGFloat, rhs: Float) -> CGFloat
{
return lhs * CGFloat(rhs)
}
/*
The * function overloaded to take the parameters of Float,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Float value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func *(lhs: Float, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) * rhs
}
/*
The * function overloaded to take the parameters of CGFloat,Double and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Double value
:return An explicitly cast CGFloat value
*/
func *(lhs: CGFloat, rhs: Double) -> CGFloat
{
return lhs * CGFloat(rhs)
}
/*
The * function overloaded to take the parameters of Double,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Double value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func *(lhs: Double, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) * rhs
}
/*
The * function overloaded to take the parameters of CGFloat,Int and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Int value
:return An explicitly cast CGFloat value
*/
func *(lhs: CGFloat, rhs: Int) -> CGFloat
{
return lhs * CGFloat(rhs)
}
/*
The * function overloaded to take the parameters of Int,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Int value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func *(lhs: Int, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) * rhs
}
/*
The * function overloaded to take the parameters of CGFloat,UInt and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The UInt value
:return An explicitly cast CGFloat value
*/
func *(lhs: CGFloat, rhs: UInt) -> CGFloat
{
return lhs * CGFloat(rhs)
}
/*
The * function overloaded to take the parameters of UInt,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The UInt value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func *(lhs: UInt, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) * rhs
}
//MARK: ##################Explicit CGFloat Division (/) Cast Functions##################
/*
The / function overloaded to take the parameters of CGFloat,Float and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Float value
:return An explicitly cast CGFloat value
*/
func /(lhs: CGFloat, rhs: Float) -> CGFloat
{
return lhs / CGFloat(rhs)
}
/*
The / function overloaded to take the parameters of Float,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Float value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func /(lhs: Float, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) / rhs
}
/*
The / function overloaded to take the parameters of CGFloat,Double and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Double value
:return An explicitly cast CGFloat value
*/
func /(lhs: CGFloat, rhs: Double) -> CGFloat
{
return lhs / CGFloat(rhs)
}
/*
The / function overloaded to take the parameters of Double,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Double value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func /(lhs: Double, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) / rhs
}
/*
The / function overloaded to take the parameters of CGFloat,Int and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Int value
:return An explicitly cast CGFloat value
*/
func /(lhs: CGFloat, rhs: Int) -> CGFloat
{
return lhs / CGFloat(rhs)
}
/*
The / function overloaded to take the parameters of Int,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Int value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func /(lhs: Int, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) / rhs
}
/*
The / function overloaded to take the parameters of CGFloat,UInt and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The UInt value
:return An explicitly cast CGFloat value
*/
func /(lhs: CGFloat, rhs: UInt) -> CGFloat
{
return lhs / CGFloat(rhs)
}
/*
The / function overloaded to take the parameters of UInt,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The UInt value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func /(lhs: UInt, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) / rhs
}
//MARK: ##################Explicit CGFloat Modulus (%) Cast Functions##################
/*
The % function overloaded to take the parameters of CGFloat,Float and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Float value
:return An explicitly cast CGFloat value
*/
func %(lhs: CGFloat, rhs: Float) -> CGFloat
{
return lhs % CGFloat(rhs)
}
/*
The % function overloaded to take the parameters of Float,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Float value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func %(lhs: Float, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) % rhs
}
/*
The % function overloaded to take the parameters of CGFloat,Double and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Double value
:return An explicitly cast CGFloat value
*/
func %(lhs: CGFloat, rhs: Double) -> CGFloat
{
return lhs % CGFloat(rhs)
}
/*
The % function overloaded to take the parameters of Double,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Double value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func %(lhs: Double, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) % rhs
}
/*
The % function overloaded to take the parameters of CGFloat,Int and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Int value
:return An explicitly cast CGFloat value
*/
func %(lhs: CGFloat, rhs: Int) -> CGFloat
{
return lhs % CGFloat(rhs)
}
/*
The % function overloaded to take the parameters of Int,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Int value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func %(lhs: Int, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) % rhs
}
/*
The % function overloaded to take the parameters of CGFloat,UInt and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The UInt value
:return An explicitly cast CGFloat value
*/
func %(lhs: CGFloat, rhs: UInt) -> CGFloat
{
return lhs % CGFloat(rhs)
}
/*
The % function overloaded to take the parameters of UInt,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The UInt value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func %(lhs: UInt, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) % rhs
} | mit |
scalessec/Toast-Swift | Example/ViewController.swift | 1 | 9630 | //
// ViewController.swift
// Toast-Swift
//
// Copyright (c) 2015-2019 Charles Scalesse.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
class ViewController: UITableViewController {
fileprivate var showingActivity = false
fileprivate struct ReuseIdentifiers {
static let switchCellId = "switchCell"
static let exampleCellId = "exampleCell"
}
// MARK: - Constructors
override init(style: UITableView.Style) {
super.init(style: style)
self.title = "Toast-Swift"
}
required init?(coder aDecoder: NSCoder) {
fatalError("not used")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: ReuseIdentifiers.exampleCellId)
}
// MARK: - Events
@objc
private func handleTapToDismissToggled() {
ToastManager.shared.isTapToDismissEnabled = !ToastManager.shared.isTapToDismissEnabled
}
@objc
private func handleQueueToggled() {
ToastManager.shared.isQueueEnabled = !ToastManager.shared.isQueueEnabled
}
}
// MARK: - UITableViewDelegate & DataSource Methods
extension ViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
} else {
return 11
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60.0
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40.0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "SETTINGS"
} else {
return "EXAMPLES"
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
var cell = tableView.dequeueReusableCell(withIdentifier: ReuseIdentifiers.switchCellId)
if indexPath.row == 0 {
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: ReuseIdentifiers.switchCellId)
let tapToDismissSwitch = UISwitch()
tapToDismissSwitch.onTintColor = .darkBlue
tapToDismissSwitch.isOn = ToastManager.shared.isTapToDismissEnabled
tapToDismissSwitch.addTarget(self, action: #selector(ViewController.handleTapToDismissToggled), for: .valueChanged)
cell?.accessoryView = tapToDismissSwitch
cell?.selectionStyle = .none
cell?.textLabel?.font = UIFont.systemFont(ofSize: 16.0)
}
cell?.textLabel?.text = "Tap to dismiss"
} else {
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: ReuseIdentifiers.switchCellId)
let queueSwitch = UISwitch()
queueSwitch.onTintColor = .darkBlue
queueSwitch.isOn = ToastManager.shared.isQueueEnabled
queueSwitch.addTarget(self, action: #selector(ViewController.handleQueueToggled), for: .valueChanged)
cell?.accessoryView = queueSwitch
cell?.selectionStyle = .none
cell?.textLabel?.font = UIFont.systemFont(ofSize: 16.0)
}
cell?.textLabel?.text = "Queue toast"
}
return cell!
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: ReuseIdentifiers.exampleCellId, for: indexPath)
cell.textLabel?.numberOfLines = 2
cell.textLabel?.font = UIFont.systemFont(ofSize: 16.0)
cell.accessoryType = .disclosureIndicator
switch indexPath.row {
case 0: cell.textLabel?.text = "Make toast"
case 1: cell.textLabel?.text = "Make toast on top for 3 seconds"
case 2: cell.textLabel?.text = "Make toast with a title"
case 3: cell.textLabel?.text = "Make toast with an image"
case 4: cell.textLabel?.text = "Make toast with a title, image, and completion closure"
case 5: cell.textLabel?.text = "Make toast with a custom style"
case 6: cell.textLabel?.text = "Show a custom view as toast"
case 7: cell.textLabel?.text = "Show an image as toast at point\n(110, 110)"
case 8: cell.textLabel?.text = showingActivity ? "Hide toast activity" : "Show toast activity"
case 9: cell.textLabel?.text = "Hide toast"
case 10: cell.textLabel?.text = "Hide all toasts"
default: cell.textLabel?.text = nil
}
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.section > 0 else { return }
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.row {
case 0:
// Make Toast
self.navigationController?.view.makeToast("This is a piece of toast")
case 1:
// Make toast with a duration and position
self.navigationController?.view.makeToast("This is a piece of toast on top for 3 seconds", duration: 3.0, position: .top)
case 2:
// Make toast with a title
self.navigationController?.view.makeToast("This is a piece of toast with a title", duration: 2.0, position: .top, title: "Toast Title", image: nil)
case 3:
// Make toast with an image
self.navigationController?.view.makeToast("This is a piece of toast with an image", duration: 2.0, position: .center, title: nil, image: UIImage(named: "toast.png"))
case 4:
// Make toast with an image, title, and completion closure
self.navigationController?.view.makeToast("This is a piece of toast with a title, image, and completion closure", duration: 2.0, position: .bottom, title: "Toast Title", image: UIImage(named: "toast.png")) { didTap in
if didTap {
print("completion from tap")
} else {
print("completion without tap")
}
}
case 5:
// Make toast with a custom style
var style = ToastStyle()
style.messageFont = UIFont(name: "Zapfino", size: 14.0)!
style.messageColor = UIColor.red
style.messageAlignment = .center
style.backgroundColor = UIColor.yellow
self.navigationController?.view.makeToast("This is a piece of toast with a custom style", duration: 3.0, position: .bottom, style: style)
case 6:
// Show a custom view as toast
let customView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 80.0, height: 400.0))
customView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
customView.backgroundColor = .lightBlue
self.navigationController?.view.showToast(customView, duration: 2.0, position: .center)
case 7:
// Show an image view as toast, on center at point (110,110)
let toastView = UIImageView(image: UIImage(named: "toast.png"))
self.navigationController?.view.showToast(toastView, duration: 2.0, point: CGPoint(x: 110.0, y: 110.0))
case 8:
// Make toast activity
if !showingActivity {
self.navigationController?.view.makeToastActivity(.center)
} else {
self.navigationController?.view.hideToastActivity()
}
showingActivity.toggle()
tableView.reloadData()
case 9:
// Hide toast
self.navigationController?.view.hideToast()
case 10:
// Hide all toasts
self.navigationController?.view.hideAllToasts()
default:
break
}
}
}
| mit |
soffes/Static | Sources/Static/Row.swift | 1 | 6164 | import UIKit
/// Row or Accessory selection callback.
public typealias Selection = () -> Void
public typealias ValueChange = (Bool) -> ()
public typealias SegmentedControlValueChange = (Int, Any?) -> ()
/// Representation of a table row.
public struct Row: Hashable, Equatable {
// MARK: - Types
/// Representation of a row accessory.
public enum Accessory: Equatable {
/// No accessory
case none
/// Chevron
case disclosureIndicator
/// Info button with chevron. Handles selection.
case detailDisclosureButton(Selection)
/// Checkmark
case checkmark
/// Checkmark Placeholder.
/// Allows spacing to continue to work when switching back & forth between checked states.
case checkmarkPlaceholder
/// Info button. Handles selection.
case detailButton(Selection)
/// Switch. Handles value change.
case switchToggle(value: Bool, ValueChange)
/// Segmented control. Handles value change.
case segmentedControl(items: [Any], selectedIndex: Int, SegmentedControlValueChange)
/// Custom view
case view(UIView)
/// Table view cell accessory type
public var type: UITableViewCell.AccessoryType {
switch self {
case .disclosureIndicator: return .disclosureIndicator
case .detailDisclosureButton(_): return .detailDisclosureButton
case .checkmark: return .checkmark
case .detailButton(_): return .detailButton
default: return .none
}
}
/// Accessory view
public var view: UIView? {
switch self {
case .view(let view): return view
case .switchToggle(let value, let valueChange):
return SwitchAccessory(initialValue: value, valueChange: valueChange)
case .checkmarkPlaceholder:
return UIView(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
case .segmentedControl(let items, let selectedIndex, let valueChange):
return SegmentedControlAccessory(items: items, selectedIndex: selectedIndex, valueChange: valueChange)
default: return nil
}
}
/// Selection block for accessory buttons
public var selection: Selection? {
switch self {
case .detailDisclosureButton(let selection): return selection
case .detailButton(let selection): return selection
default: return nil
}
}
}
public typealias Context = [String: Any]
public typealias EditActionSelection = (IndexPath) -> ()
/// Representation of an editing action, when swiping to edit a cell.
public struct EditAction {
/// Title of the action's button.
public let title: String
/// Styling for button's action, used primarily for destructive actions.
public let style: UITableViewRowAction.Style
/// Background color of the button.
public let backgroundColor: UIColor?
/// Visual effect to be applied to the button's background.
public let backgroundEffect: UIVisualEffect?
/// Invoked when selecting the action.
public let selection: EditActionSelection?
public init(title: String, style: UITableViewRowAction.Style = .default, backgroundColor: UIColor? = nil, backgroundEffect: UIVisualEffect? = nil, selection: EditActionSelection? = nil) {
self.title = title
self.style = style
self.backgroundColor = backgroundColor
self.backgroundEffect = backgroundEffect
self.selection = selection
}
}
// MARK: - Properties
/// The row's accessibility identifier.
public var accessibilityIdentifier: String?
/// Unique identifier for the row.
public let uuid: String
/// The row's primary text.
public var text: String?
/// The row's secondary text.
public var detailText: String?
/// Accessory for the row.
public var accessory: Accessory
/// Image for the row
public var image: UIImage?
/// Action to run when the row is selected.
public var selection: Selection?
/// View to be used for the row.
public var cellClass: Cell.Type
/// Additional information for the row.
public var context: Context?
/// Actions to show when swiping the cell, such as Delete.
public var editActions: [EditAction]
var canEdit: Bool {
return editActions.count > 0
}
var isSelectable: Bool {
return selection != nil
}
var cellIdentifier: String {
return cellClass.description()
}
public func hash(into hasher: inout Hasher) {
hasher.combine(uuid)
}
// MARK: - Initializers
public init(text: String? = nil, detailText: String? = nil, selection: Selection? = nil,
image: UIImage? = nil, accessory: Accessory = .none, cellClass: Cell.Type? = nil, context: Context? = nil, editActions: [EditAction] = [], uuid: String = UUID().uuidString, accessibilityIdentifier: String? = nil) {
self.accessibilityIdentifier = accessibilityIdentifier
self.uuid = uuid
self.text = text
self.detailText = detailText
self.selection = selection
self.image = image
self.accessory = accessory
self.cellClass = cellClass ?? Value1Cell.self
self.context = context
self.editActions = editActions
}
}
public func ==(lhs: Row, rhs: Row) -> Bool {
return lhs.uuid == rhs.uuid
}
public func ==(lhs: Row.Accessory, rhs: Row.Accessory) -> Bool {
switch (lhs, rhs) {
case (.none, .none): return true
case (.disclosureIndicator, .disclosureIndicator): return true
case (.detailDisclosureButton(_), .detailDisclosureButton(_)): return true
case (.checkmark, .checkmark): return true
case (.detailButton(_), .detailButton(_)): return true
case (.view(let l), .view(let r)): return l == r
default: return false
}
}
| mit |
lifcio/youtube-app-syncano | youtube-app-syncano/ViewController.swift | 1 | 3770 | //
// ViewController.swift
// youtube-app-syncano
//
// Created by Mariusz Wisniewski on 9/2/15.
// Copyright (c) 2015 Mariusz Wisniewski. All rights reserved.
//
import UIKit
import MediaPlayer
let instanceName = ""
let apiKey = ""
let channelName = "youtube_videos"
class ViewController: UIViewController {
var videos : [Video] = []
let syncano = Syncano.sharedInstanceWithApiKey(apiKey, instanceName: instanceName)
let channel = SCChannel(name: channelName)
@IBOutlet weak var tableView: UITableView!
@IBAction func refreshPressed(sender: UIBarButtonItem) {
self.downloadVideosFromSyncano()
}
override func viewDidLoad() {
super.viewDidLoad()
self.channel.delegate = self
self.channel.subscribeToChannel()
self.downloadVideosFromSyncano()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func removeVideoWithId(objectId: Int?) {
self.videos = self.videos.filter {
return $0.objectId != objectId
}
}
}
//MARK - Syncano
extension ViewController {
func downloadVideosFromSyncano() {
Video.please().giveMeDataObjectsWithCompletion { objects, error in
if let youtubeVideos = objects {
self.videos.removeAll(keepCapacity: true)
for item in youtubeVideos {
if let video = item as? Video {
self.videos.append(video)
}
}
self.tableView.reloadData()
}
}
}
}
//MARK - SCChannelDelegate
extension ViewController : SCChannelDelegate {
func chanellDidReceivedNotificationMessage(notificationMessage: SCChannelNotificationMessage!) {
switch(notificationMessage.action) {
case .Create:
let video = Video.fromDictionary(notificationMessage.payload)
self.videos += [video]
self.tableView.reloadData()
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: (self.videos.count - 1), inSection: 0), atScrollPosition: .Bottom, animated: true)
break
case .Delete:
self.removeVideoWithId(notificationMessage.payload["id"] as! Int?)
self.tableView.reloadData()
break
case .Update:
break
default:
break
}
}
}
//MARK - UITableViewDelegate
extension ViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if let sourceId = self.videos[indexPath.row].sourceId {
let videoPlayerViewController = XCDYouTubeVideoPlayerViewController(videoIdentifier: sourceId)
self.presentMoviePlayerViewControllerAnimated(videoPlayerViewController)
}
}
}
//MARK - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.videos.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as! UITableViewCell?
if (cell == nil) {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: identifier)
}
cell?.textLabel?.text = videos[indexPath.row].title
cell?.detailTextLabel?.text = videos[indexPath.row].videoDescription
return cell!
}
}
| mit |
yosan/AwsChat | AwsChat/AppDelegate.swift | 1 | 3792 | //
// AppDelegate.swift
// AwsChat
//
// Created by Takahashi Yosuke on 2016/07/09.
// Copyright ยฉ 2016ๅนด Yosan. All rights reserved.
//
import UIKit
import FBSDKLoginKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
/**
Called when user allows push notification
- parameter application: application
- parameter notificationSettings: notificationSettings
*/
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
application.registerForRemoteNotifications()
}
/**
Called when device token is provided
- parameter application: application
- parameter deviceToken: deviceToken
*/
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = "\(deviceToken)"
.trimmingCharacters(in: CharacterSet(charactersIn:"<>"))
.replacingOccurrences(of: " ", with: "")
let notification = Notification(name: Notification.Name(rawValue: "DeviceTokenUpdated"), object: self, userInfo: ["token" : deviceTokenString])
NotificationCenter.default.post(notification)
}
/**
Called when token registration is failed
- parameter application: application
- parameter error: error
*/
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
let error = error as NSError
print("error: \(error.code), \(error.description)")
// Simulate device token is received for iOS Simulator.
if TARGET_OS_SIMULATOR != 0 {
let dummy = "0000000000000000000000000000000000000000000000000000000000000000"
let notification = Notification(name: Notification.Name(rawValue: "DeviceTokenUpdated"), object: self, userInfo: ["token" : dummy])
NotificationCenter.default.post(notification)
}
}
/**
Called when remote notification is received. (DynamoDB's message table is updated in this case)
- parameter application: application
- parameter userInfo: userInfo
*/
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print(userInfo)
let notification = Notification(name: Notification.Name(rawValue: "MessageUpdated"), object: self, userInfo: userInfo)
NotificationCenter.default.post(notification)
}
/**
Call FBSDKAppEvents.activateApp() for Facebool login.
- parameter application: application
*/
func applicationDidBecomeActive(_ application: UIApplication) {
FBSDKAppEvents.activateApp()
}
/**
Call FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) for Facebook login.
- parameter application: application
- parameter url: url
- parameter sourceApplication: sourceApplication
- parameter annotation: annotation
- returns: return value
*/
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
FBSDKProfile.enableUpdates(onAccessTokenChange: true)
return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
}
| mit |
didierbrun/DBPathRecognizer | PathRecognizer/AppDelegate.swift | 1 | 2180 | //
// AppDelegate.swift
// PathRecognizer
//
// Created by Didier Brun on 15/03/2015.
// Copyright (c) 2015 Didier Brun. 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 |
abertelrud/swift-package-manager | Sources/Build/BuildOperationBuildSystemDelegateHandler.swift | 2 | 39444 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2018-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 Basics
import Dispatch
import Foundation
import LLBuildManifest
import PackageModel
import SPMBuildCore
import SPMLLBuild
import TSCBasic
import class TSCUtility.IndexStore
import class TSCUtility.IndexStoreAPI
import protocol TSCUtility.ProgressAnimationProtocol
#if canImport(llbuildSwift)
typealias LLBuildBuildSystemDelegate = llbuildSwift.BuildSystemDelegate
#else
typealias LLBuildBuildSystemDelegate = llbuild.BuildSystemDelegate
#endif
typealias Diagnostic = TSCBasic.Diagnostic
class CustomLLBuildCommand: SPMLLBuild.ExternalCommand {
let context: BuildExecutionContext
required init(_ context: BuildExecutionContext) {
self.context = context
}
func getSignature(_ command: SPMLLBuild.Command) -> [UInt8] {
return []
}
func execute(
_ command: SPMLLBuild.Command,
_ buildSystemCommandInterface: SPMLLBuild.BuildSystemCommandInterface
) -> Bool {
fatalError("subclass responsibility")
}
}
private extension IndexStore.TestCaseClass.TestMethod {
var allTestsEntry: String {
let baseName = name.hasSuffix("()") ? String(name.dropLast(2)) : name
return "(\"\(baseName)\", \(isAsync ? "asyncTest(\(baseName))" : baseName ))"
}
}
final class TestDiscoveryCommand: CustomLLBuildCommand, TestBuildCommand {
private func write(
tests: [IndexStore.TestCaseClass],
forModule module: String,
to path: AbsolutePath
) throws {
let stream = try LocalFileOutputByteStream(path)
let testsByClassNames = Dictionary(grouping: tests, by: { $0.name }).sorted(by: { $0.key < $1.key })
stream <<< "import XCTest" <<< "\n"
stream <<< "@testable import " <<< module <<< "\n"
for iterator in testsByClassNames {
let className = iterator.key
let testMethods = iterator.value.flatMap{ $0.testMethods }
stream <<< "\n"
stream <<< "fileprivate extension " <<< className <<< " {" <<< "\n"
stream <<< indent(4) <<< "@available(*, deprecated, message: \"Not actually deprecated. Marked as deprecated to allow inclusion of deprecated tests (which test deprecated functionality) without warnings\")" <<< "\n"
// 'className' provides uniqueness for derived class.
stream <<< indent(4) <<< "static let __allTests__\(className) = [" <<< "\n"
for method in testMethods {
stream <<< indent(8) <<< method.allTestsEntry <<< ",\n"
}
stream <<< indent(4) <<< "]" <<< "\n"
stream <<< "}" <<< "\n"
}
stream <<< """
@available(*, deprecated, message: "Not actually deprecated. Marked as deprecated to allow inclusion of deprecated tests (which test deprecated functionality) without warnings")
func __\(module)__allTests() -> [XCTestCaseEntry] {
return [\n
"""
for iterator in testsByClassNames {
let className = iterator.key
stream <<< indent(8) <<< "testCase(\(className).__allTests__\(className)),\n"
}
stream <<< """
]
}
"""
stream.flush()
}
private func execute(fileSystem: TSCBasic.FileSystem, tool: LLBuildManifest.TestDiscoveryTool) throws {
let index = self.context.buildParameters.indexStore
let api = try self.context.indexStoreAPI.get()
let store = try IndexStore.open(store: index, api: api)
// FIXME: We can speed this up by having one llbuild command per object file.
let tests = try store.listTests(in: tool.inputs.map{ try AbsolutePath(validating: $0.name) })
let outputs = tool.outputs.compactMap{ try? AbsolutePath(validating: $0.name) }
let testsByModule = Dictionary(grouping: tests, by: { $0.module.spm_mangledToC99ExtendedIdentifier() })
func isMainFile(_ path: AbsolutePath) -> Bool {
return path.basename == LLBuildManifest.TestDiscoveryTool.mainFileName
}
var maybeMainFile: AbsolutePath?
// Write one file for each test module.
//
// We could write everything in one file but that can easily run into type conflicts due
// in complex packages with large number of test targets.
for file in outputs {
if maybeMainFile == nil && isMainFile(file) {
maybeMainFile = file
continue
}
// FIXME: This is relying on implementation detail of the output but passing the
// the context all the way through is not worth it right now.
let module = file.basenameWithoutExt.spm_mangledToC99ExtendedIdentifier()
guard let tests = testsByModule[module] else {
// This module has no tests so just write an empty file for it.
try fileSystem.writeFileContents(file, bytes: "")
continue
}
try write(tests: tests, forModule: module, to: file)
}
guard let mainFile = maybeMainFile else {
throw InternalError("main output (\(LLBuildManifest.TestDiscoveryTool.mainFileName)) not found")
}
let testsKeyword = tests.isEmpty ? "let" : "var"
// Write the main file.
let stream = try LocalFileOutputByteStream(mainFile)
stream <<< "import XCTest" <<< "\n\n"
stream <<< "@available(*, deprecated, message: \"Not actually deprecated. Marked as deprecated to allow inclusion of deprecated tests (which test deprecated functionality) without warnings\")" <<< "\n"
stream <<< "public func __allDiscoveredTests() -> [XCTestCaseEntry] {" <<< "\n"
stream <<< indent(4) <<< "\(testsKeyword) tests = [XCTestCaseEntry]()" <<< "\n\n"
for module in testsByModule.keys {
stream <<< indent(4) <<< "tests += __\(module)__allTests()" <<< "\n"
}
stream <<< "\n"
stream <<< indent(4) <<< "return tests" <<< "\n"
stream <<< "}" <<< "\n"
stream.flush()
}
override func execute(
_ command: SPMLLBuild.Command,
_ buildSystemCommandInterface: SPMLLBuild.BuildSystemCommandInterface
) -> Bool {
do {
// This tool will never run without the build description.
guard let buildDescription = self.context.buildDescription else {
throw InternalError("unknown build description")
}
guard let tool = buildDescription.testDiscoveryCommands[command.name] else {
throw InternalError("command \(command.name) not registered")
}
try execute(fileSystem: self.context.fileSystem, tool: tool)
return true
} catch {
self.context.observabilityScope.emit(error)
return false
}
}
}
final class TestEntryPointCommand: CustomLLBuildCommand, TestBuildCommand {
private func execute(fileSystem: TSCBasic.FileSystem, tool: LLBuildManifest.TestEntryPointTool) throws {
// Find the inputs, which are the names of the test discovery module(s)
let inputs = tool.inputs.compactMap { try? AbsolutePath(validating: $0.name) }
let discoveryModuleNames = inputs.map { $0.basenameWithoutExt }
let outputs = tool.outputs.compactMap { try? AbsolutePath(validating: $0.name) }
// Find the main output file
guard let mainFile = outputs.first(where: { path in
path.basename == LLBuildManifest.TestEntryPointTool.mainFileName
}) else {
throw InternalError("main file output (\(LLBuildManifest.TestEntryPointTool.mainFileName)) not found")
}
// Write the main file.
let stream = try LocalFileOutputByteStream(mainFile)
stream <<< "import XCTest" <<< "\n"
for discoveryModuleName in discoveryModuleNames {
stream <<< "import \(discoveryModuleName)" <<< "\n"
}
stream <<< "\n"
stream <<< "@main" <<< "\n"
stream <<< "@available(*, deprecated, message: \"Not actually deprecated. Marked as deprecated to allow inclusion of deprecated tests (which test deprecated functionality) without warnings\")" <<< "\n"
stream <<< "struct Runner" <<< " {" <<< "\n"
stream <<< indent(4) <<< "static func main()" <<< " {" <<< "\n"
stream <<< indent(8) <<< "XCTMain(__allDiscoveredTests())" <<< "\n"
stream <<< indent(4) <<< "}" <<< "\n"
stream <<< "}" <<< "\n"
stream.flush()
}
override func execute(
_ command: SPMLLBuild.Command,
_ buildSystemCommandInterface: SPMLLBuild.BuildSystemCommandInterface
) -> Bool {
do {
// This tool will never run without the build description.
guard let buildDescription = self.context.buildDescription else {
throw InternalError("unknown build description")
}
guard let tool = buildDescription.testEntryPointCommands[command.name] else {
throw InternalError("command \(command.name) not registered")
}
try execute(fileSystem: self.context.fileSystem, tool: tool)
return true
} catch {
self.context.observabilityScope.emit(error)
return false
}
}
}
private protocol TestBuildCommand {}
/// Functionality common to all build commands related to test targets.
extension TestBuildCommand {
/// Returns a value containing `spaces` number of space characters.
/// Intended to facilitate indenting generated code a specified number of levels.
fileprivate func indent(_ spaces: Int) -> ByteStreamable {
return Format.asRepeating(string: " ", count: spaces)
}
}
private final class InProcessTool: Tool {
let context: BuildExecutionContext
let type: CustomLLBuildCommand.Type
init(_ context: BuildExecutionContext, type: CustomLLBuildCommand.Type) {
self.context = context
self.type = type
}
func createCommand(_ name: String) -> ExternalCommand? {
return type.init(self.context)
}
}
/// Contains the description of the build that is needed during the execution.
public struct BuildDescription: Codable {
public typealias CommandName = String
public typealias TargetName = String
public typealias CommandLineFlag = String
/// The Swift compiler invocation targets.
let swiftCommands: [BuildManifest.CmdName : SwiftCompilerTool]
/// The Swift compiler frontend invocation targets.
let swiftFrontendCommands: [BuildManifest.CmdName : SwiftFrontendTool]
/// The map of test discovery commands.
let testDiscoveryCommands: [BuildManifest.CmdName: LLBuildManifest.TestDiscoveryTool]
/// The map of test entry point commands.
let testEntryPointCommands: [BuildManifest.CmdName: LLBuildManifest.TestEntryPointTool]
/// The map of copy commands.
let copyCommands: [BuildManifest.CmdName: LLBuildManifest.CopyTool]
/// A flag that inidcates this build should perform a check for whether targets only import
/// their explicitly-declared dependencies
let explicitTargetDependencyImportCheckingMode: BuildParameters.TargetDependencyImportCheckingMode
/// Every target's set of dependencies.
let targetDependencyMap: [TargetName: [TargetName]]
/// A full swift driver command-line invocation used to dependency-scan a given Swift target
let swiftTargetScanArgs: [TargetName: [CommandLineFlag]]
/// A set of all targets with generated source
let generatedSourceTargetSet: Set<TargetName>
/// The built test products.
public let builtTestProducts: [BuiltTestProduct]
/// Distilled information about any plugins defined in the package.
let pluginDescriptions: [PluginDescription]
public init(
plan: BuildPlan,
swiftCommands: [BuildManifest.CmdName : SwiftCompilerTool],
swiftFrontendCommands: [BuildManifest.CmdName : SwiftFrontendTool],
testDiscoveryCommands: [BuildManifest.CmdName: LLBuildManifest.TestDiscoveryTool],
testEntryPointCommands: [BuildManifest.CmdName: LLBuildManifest.TestEntryPointTool],
copyCommands: [BuildManifest.CmdName: LLBuildManifest.CopyTool],
pluginDescriptions: [PluginDescription]
) throws {
self.swiftCommands = swiftCommands
self.swiftFrontendCommands = swiftFrontendCommands
self.testDiscoveryCommands = testDiscoveryCommands
self.testEntryPointCommands = testEntryPointCommands
self.copyCommands = copyCommands
self.explicitTargetDependencyImportCheckingMode = plan.buildParameters.explicitTargetDependencyImportCheckingMode
self.targetDependencyMap = try plan.targets.reduce(into: [TargetName: [TargetName]]()) {
let deps = try $1.target.recursiveDependencies(satisfying: plan.buildParameters.buildEnvironment).compactMap { $0.target }.map { $0.c99name }
$0[$1.target.c99name] = deps
}
var targetCommandLines: [TargetName: [CommandLineFlag]] = [:]
var generatedSourceTargets: [TargetName] = []
for (target, description) in plan.targetMap {
guard case .swift(let desc) = description else {
continue
}
targetCommandLines[target.c99name] =
try desc.emitCommandLine(scanInvocation: true) + ["-driver-use-frontend-path",
plan.buildParameters.toolchain.swiftCompilerPath.pathString]
if case .discovery = desc.testTargetRole {
generatedSourceTargets.append(target.c99name)
}
}
generatedSourceTargets.append(contentsOf: plan.graph.allTargets.filter {$0.type == .plugin}
.map { $0.c99name })
self.swiftTargetScanArgs = targetCommandLines
self.generatedSourceTargetSet = Set(generatedSourceTargets)
self.builtTestProducts = plan.buildProducts.filter{ $0.product.type == .test }.map { desc in
return BuiltTestProduct(
productName: desc.product.name,
binaryPath: desc.binaryPath
)
}
self.pluginDescriptions = pluginDescriptions
}
public func write(fileSystem: TSCBasic.FileSystem, path: AbsolutePath) throws {
let encoder = JSONEncoder.makeWithDefaults()
let data = try encoder.encode(self)
try fileSystem.writeFileContents(path, bytes: ByteString(data))
}
public static func load(fileSystem: TSCBasic.FileSystem, path: AbsolutePath) throws -> BuildDescription {
let contents: Data = try fileSystem.readFileContents(path)
let decoder = JSONDecoder.makeWithDefaults()
return try decoder.decode(BuildDescription.self, from: contents)
}
}
/// A provider of advice about build errors.
public protocol BuildErrorAdviceProvider {
/// Invoked after a command fails and an error message is detected in the output. Should return a string containing advice or additional information, if any, based on the build plan.
func provideBuildErrorAdvice(for target: String, command: String, message: String) -> String?
}
/// The context available during build execution.
public final class BuildExecutionContext {
/// Reference to the index store API.
var indexStoreAPI: Result<IndexStoreAPI, Error> {
indexStoreAPICache.getValue(self)
}
/// The build parameters.
let buildParameters: BuildParameters
/// The build description.
///
/// This is optional because we might not have a valid build description when performing the
/// build for PackageStructure target.
let buildDescription: BuildDescription?
/// The package structure delegate.
let packageStructureDelegate: PackageStructureDelegate
/// Optional provider of build error resolution advice.
let buildErrorAdviceProvider: BuildErrorAdviceProvider?
let fileSystem: TSCBasic.FileSystem
let observabilityScope: ObservabilityScope
public init(
_ buildParameters: BuildParameters,
buildDescription: BuildDescription? = nil,
fileSystem: TSCBasic.FileSystem,
observabilityScope: ObservabilityScope,
packageStructureDelegate: PackageStructureDelegate,
buildErrorAdviceProvider: BuildErrorAdviceProvider? = nil
) {
self.buildParameters = buildParameters
self.buildDescription = buildDescription
self.fileSystem = fileSystem
self.observabilityScope = observabilityScope
self.packageStructureDelegate = packageStructureDelegate
self.buildErrorAdviceProvider = buildErrorAdviceProvider
}
// MARK:- Private
private var indexStoreAPICache = LazyCache(createIndexStoreAPI)
private func createIndexStoreAPI() -> Result<IndexStoreAPI, Error> {
Result {
#if os(Windows)
// The library's runtime component is in the `bin` directory on
// Windows rather than the `lib` directory as on unicies. The `lib`
// directory contains the import library (and possibly static
// archives) which are used for linking. The runtime component is
// not (necessarily) part of the SDK distributions.
//
// NOTE: the library name here `libIndexStore.dll` is technically
// incorrect as per the Windows naming convention. However, the
// library is currently installed as `libIndexStore.dll` rather than
// `IndexStore.dll`. In the future, this may require a fallback
// search, preferring `IndexStore.dll` over `libIndexStore.dll`.
let indexStoreLib = buildParameters.toolchain.swiftCompilerPath
.parentDirectory
.appending(component: "libIndexStore.dll")
#else
let ext = buildParameters.hostTriple.dynamicLibraryExtension
let indexStoreLib = try buildParameters.toolchain.toolchainLibDir.appending(component: "libIndexStore" + ext)
#endif
return try IndexStoreAPI(dylib: indexStoreLib)
}
}
}
public protocol PackageStructureDelegate {
func packageStructureChanged() -> Bool
}
final class PackageStructureCommand: CustomLLBuildCommand {
override func getSignature(_ command: SPMLLBuild.Command) -> [UInt8] {
let encoder = JSONEncoder.makeWithDefaults()
// Include build parameters and process env in the signature.
var hash = Data()
hash += try! encoder.encode(self.context.buildParameters)
hash += try! encoder.encode(ProcessEnv.vars)
return [UInt8](hash)
}
override func execute(
_ command: SPMLLBuild.Command,
_ commandInterface: SPMLLBuild.BuildSystemCommandInterface
) -> Bool {
return self.context.packageStructureDelegate.packageStructureChanged()
}
}
final class CopyCommand: CustomLLBuildCommand {
override func execute(
_ command: SPMLLBuild.Command,
_ commandInterface: SPMLLBuild.BuildSystemCommandInterface
) -> Bool {
do {
// This tool will never run without the build description.
guard let buildDescription = self.context.buildDescription else {
throw InternalError("unknown build description")
}
guard let tool = buildDescription.copyCommands[command.name] else {
throw StringError("command \(command.name) not registered")
}
let input = try AbsolutePath(validating: tool.inputs[0].name)
let output = try AbsolutePath(validating: tool.outputs[0].name)
try self.context.fileSystem.createDirectory(output.parentDirectory, recursive: true)
try self.context.fileSystem.removeFileTree(output)
try self.context.fileSystem.copy(from: input, to: output)
} catch {
self.context.observabilityScope.emit(error)
return false
}
return true
}
}
/// Convenient llbuild build system delegate implementation
final class BuildOperationBuildSystemDelegateHandler: LLBuildBuildSystemDelegate, SwiftCompilerOutputParserDelegate {
private let outputStream: ThreadSafeOutputByteStream
private let progressAnimation: ProgressAnimationProtocol
var commandFailureHandler: (() -> Void)?
private let logLevel: Basics.Diagnostic.Severity
private weak var delegate: SPMBuildCore.BuildSystemDelegate?
private let buildSystem: SPMBuildCore.BuildSystem
private let queue = DispatchQueue(label: "org.swift.swiftpm.build-delegate")
private var taskTracker = CommandTaskTracker()
private var errorMessagesByTarget: [String: [String]] = [:]
private let observabilityScope: ObservabilityScope
/// Swift parsers keyed by llbuild command name.
private var swiftParsers: [String: SwiftCompilerOutputParser] = [:]
/// Buffer to accumulate non-swift output until command is finished
private var nonSwiftMessageBuffers: [String: [UInt8]] = [:]
/// The build execution context.
private let buildExecutionContext: BuildExecutionContext
init(
buildSystem: SPMBuildCore.BuildSystem,
buildExecutionContext: BuildExecutionContext,
outputStream: OutputByteStream,
progressAnimation: ProgressAnimationProtocol,
logLevel: Basics.Diagnostic.Severity,
observabilityScope: ObservabilityScope,
delegate: SPMBuildCore.BuildSystemDelegate?
) {
self.buildSystem = buildSystem
self.buildExecutionContext = buildExecutionContext
// FIXME: Implement a class convenience initializer that does this once they are supported
// https://forums.swift.org/t/allow-self-x-in-class-convenience-initializers/15924
self.outputStream = outputStream as? ThreadSafeOutputByteStream ?? ThreadSafeOutputByteStream(outputStream)
self.progressAnimation = progressAnimation
self.logLevel = logLevel
self.observabilityScope = observabilityScope
self.delegate = delegate
let swiftParsers = buildExecutionContext.buildDescription?.swiftCommands.mapValues { tool in
SwiftCompilerOutputParser(targetName: tool.moduleName, delegate: self)
} ?? [:]
self.swiftParsers = swiftParsers
self.taskTracker.onTaskProgressUpdateText = { progressText, _ in
self.queue.async {
self.delegate?.buildSystem(self.buildSystem, didUpdateTaskProgress: progressText)
}
}
}
// MARK: llbuildSwift.BuildSystemDelegate
var fs: SPMLLBuild.FileSystem? {
return nil
}
func lookupTool(_ name: String) -> Tool? {
switch name {
case TestDiscoveryTool.name:
return InProcessTool(buildExecutionContext, type: TestDiscoveryCommand.self)
case TestEntryPointTool.name:
return InProcessTool(buildExecutionContext, type: TestEntryPointCommand.self)
case PackageStructureTool.name:
return InProcessTool(buildExecutionContext, type: PackageStructureCommand.self)
case CopyTool.name:
return InProcessTool(buildExecutionContext, type: CopyCommand.self)
default:
return nil
}
}
func hadCommandFailure() {
self.commandFailureHandler?()
}
func handleDiagnostic(_ diagnostic: SPMLLBuild.Diagnostic) {
switch diagnostic.kind {
case .note:
self.observabilityScope.emit(info: diagnostic.message)
case .warning:
self.observabilityScope.emit(warning: diagnostic.message)
case .error:
self.observabilityScope.emit(error: diagnostic.message)
@unknown default:
self.observabilityScope.emit(info: diagnostic.message)
}
}
func commandStatusChanged(_ command: SPMLLBuild.Command, kind: CommandStatusKind) {
guard !self.logLevel.isVerbose else { return }
guard command.shouldShowStatus else { return }
guard !swiftParsers.keys.contains(command.name) else { return }
queue.async {
self.taskTracker.commandStatusChanged(command, kind: kind)
self.updateProgress()
}
}
func commandPreparing(_ command: SPMLLBuild.Command) {
queue.async {
self.delegate?.buildSystem(self.buildSystem, willStartCommand: BuildSystemCommand(command))
}
}
func commandStarted(_ command: SPMLLBuild.Command) {
guard command.shouldShowStatus else { return }
queue.async {
self.delegate?.buildSystem(self.buildSystem, didStartCommand: BuildSystemCommand(command))
if self.logLevel.isVerbose {
self.outputStream <<< command.verboseDescription <<< "\n"
self.outputStream.flush()
}
}
}
func shouldCommandStart(_ command: SPMLLBuild.Command) -> Bool {
return true
}
func commandFinished(_ command: SPMLLBuild.Command, result: CommandResult) {
guard command.shouldShowStatus else { return }
guard !swiftParsers.keys.contains(command.name) else { return }
queue.async {
self.delegate?.buildSystem(self.buildSystem, didFinishCommand: BuildSystemCommand(command))
if !self.logLevel.isVerbose {
let targetName = self.swiftParsers[command.name]?.targetName
self.taskTracker.commandFinished(command, result: result, targetName: targetName)
self.updateProgress()
}
}
}
func commandHadError(_ command: SPMLLBuild.Command, message: String) {
self.observabilityScope.emit(error: message)
}
func commandHadNote(_ command: SPMLLBuild.Command, message: String) {
self.observabilityScope.emit(info: message)
}
func commandHadWarning(_ command: SPMLLBuild.Command, message: String) {
self.observabilityScope.emit(warning: message)
}
func commandCannotBuildOutputDueToMissingInputs(
_ command: SPMLLBuild.Command,
output: BuildKey,
inputs: [BuildKey]
) {
self.observabilityScope.emit(.missingInputs(output: output, inputs: inputs))
}
func cannotBuildNodeDueToMultipleProducers(output: BuildKey, commands: [SPMLLBuild.Command]) {
self.observabilityScope.emit(.multipleProducers(output: output, commands: commands))
}
func commandProcessStarted(_ command: SPMLLBuild.Command, process: ProcessHandle) {
}
func commandProcessHadError(_ command: SPMLLBuild.Command, process: ProcessHandle, message: String) {
self.observabilityScope.emit(.commandError(command: command, message: message))
}
func commandProcessHadOutput(_ command: SPMLLBuild.Command, process: ProcessHandle, data: [UInt8]) {
guard command.shouldShowStatus else { return }
if let swiftParser = swiftParsers[command.name] {
swiftParser.parse(bytes: data)
} else {
queue.async {
self.nonSwiftMessageBuffers[command.name, default: []] += data
}
}
}
func commandProcessFinished(
_ command: SPMLLBuild.Command,
process: ProcessHandle,
result: CommandExtendedResult
) {
queue.async {
if let buffer = self.nonSwiftMessageBuffers[command.name] {
self.progressAnimation.clear()
self.outputStream <<< buffer
self.outputStream.flush()
self.nonSwiftMessageBuffers[command.name] = nil
}
}
if result.result == .failed {
// The command failed, so we queue up an asynchronous task to see if we have any error messages from the target to provide advice about.
queue.async {
guard let target = self.swiftParsers[command.name]?.targetName else { return }
guard let errorMessages = self.errorMessagesByTarget[target] else { return }
for errorMessage in errorMessages {
// Emit any advice that's provided for each error message.
if let adviceMessage = self.buildExecutionContext.buildErrorAdviceProvider?.provideBuildErrorAdvice(for: target, command: command.name, message: errorMessage) {
self.outputStream <<< "note: " <<< adviceMessage <<< "\n"
self.outputStream.flush()
}
}
}
}
}
func cycleDetected(rules: [BuildKey]) {
self.observabilityScope.emit(.cycleError(rules: rules))
queue.async {
self.delegate?.buildSystemDidDetectCycleInRules(self.buildSystem)
}
}
func shouldResolveCycle(rules: [BuildKey], candidate: BuildKey, action: CycleAction) -> Bool {
return false
}
/// Invoked right before running an action taken before building.
func preparationStepStarted(_ name: String) {
queue.async {
self.taskTracker.buildPreparationStepStarted(name)
self.updateProgress()
}
}
/// Invoked when an action taken before building emits output.
func preparationStepHadOutput(_ name: String, output: String) {
queue.async {
self.progressAnimation.clear()
if self.logLevel.isVerbose {
self.outputStream <<< output.spm_chomp() <<< "\n"
self.outputStream.flush()
}
}
}
/// Invoked right after running an action taken before building. The result
/// indicates whether the action succeeded, failed, or was cancelled.
func preparationStepFinished(_ name: String, result: CommandResult) {
queue.async {
self.taskTracker.buildPreparationStepFinished(name)
self.updateProgress()
}
}
// MARK: SwiftCompilerOutputParserDelegate
func swiftCompilerOutputParser(_ parser: SwiftCompilerOutputParser, didParse message: SwiftCompilerMessage) {
queue.async {
if self.logLevel.isVerbose {
if let text = message.verboseProgressText {
self.outputStream <<< text <<< "\n"
self.outputStream.flush()
}
} else {
self.taskTracker.swiftCompilerDidOutputMessage(message, targetName: parser.targetName)
self.updateProgress()
}
if let output = message.standardOutput {
// first we want to print the output so users have it handy
if !self.logLevel.isVerbose {
self.progressAnimation.clear()
}
self.outputStream <<< output
self.outputStream.flush()
// next we want to try and scoop out any errors from the output (if reasonable size, otherwise this will be very slow),
// so they can later be passed to the advice provider in case of failure.
if output.utf8.count < 1024 * 10 {
let regex = try! RegEx(pattern: #".*(error:[^\n]*)\n.*"#, options: .dotMatchesLineSeparators)
for match in regex.matchGroups(in: output) {
self.errorMessagesByTarget[parser.targetName] = (self.errorMessagesByTarget[parser.targetName] ?? []) + [match[0]]
}
}
}
}
}
func swiftCompilerOutputParser(_ parser: SwiftCompilerOutputParser, didFailWith error: Error) {
let message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription
self.observabilityScope.emit(.swiftCompilerOutputParsingError(message))
self.commandFailureHandler?()
}
func buildStart(configuration: BuildConfiguration) {
queue.sync {
self.progressAnimation.clear()
self.outputStream <<< "Building for \(configuration == .debug ? "debugging" : "production")...\n"
self.outputStream.flush()
}
}
func buildComplete(success: Bool, duration: DispatchTimeInterval) {
queue.sync {
self.progressAnimation.complete(success: success)
if success {
self.progressAnimation.clear()
self.outputStream <<< "Build complete! (\(duration.descriptionInSeconds))\n"
self.outputStream.flush()
}
}
}
// MARK: Private
private func updateProgress() {
if let progressText = taskTracker.latestFinishedText {
self.progressAnimation.update(
step: taskTracker.finishedCount,
total: taskTracker.totalCount,
text: progressText
)
}
}
}
/// Tracks tasks based on command status and swift compiler output.
fileprivate struct CommandTaskTracker {
private(set) var totalCount = 0
private(set) var finishedCount = 0
private var swiftTaskProgressTexts: [Int: String] = [:]
/// The last task text before the task list was emptied.
private(set) var latestFinishedText: String?
var onTaskProgressUpdateText: ((_ text: String, _ targetName: String?) -> Void)?
mutating func commandStatusChanged(_ command: SPMLLBuild.Command, kind: CommandStatusKind) {
switch kind {
case .isScanning:
self.totalCount += 1
case .isUpToDate:
self.totalCount -= 1
case .isComplete:
self.finishedCount += 1
@unknown default:
assertionFailure("unhandled command status kind \(kind) for command \(command)")
break
}
}
mutating func commandFinished(_ command: SPMLLBuild.Command, result: CommandResult, targetName: String?) {
let progressTextValue = progressText(of: command, targetName: targetName)
self.onTaskProgressUpdateText?(progressTextValue, targetName)
self.latestFinishedText = progressTextValue
}
mutating func swiftCompilerDidOutputMessage(_ message: SwiftCompilerMessage, targetName: String) {
switch message.kind {
case .began(let info):
if let text = progressText(of: message, targetName: targetName) {
swiftTaskProgressTexts[info.pid] = text
onTaskProgressUpdateText?(text, targetName)
}
totalCount += 1
case .finished(let info):
if let progressText = swiftTaskProgressTexts[info.pid] {
latestFinishedText = progressText
swiftTaskProgressTexts[info.pid] = nil
}
finishedCount += 1
case .unparsableOutput, .signalled, .skipped:
break
}
}
private func progressText(of command: SPMLLBuild.Command, targetName: String?) -> String {
// Transforms descriptions like "Linking ./.build/x86_64-apple-macosx/debug/foo" into "Linking foo".
if let firstSpaceIndex = command.description.firstIndex(of: " "),
let lastDirectorySeparatorIndex = command.description.lastIndex(of: "/")
{
let action = command.description[..<firstSpaceIndex]
let fileNameStartIndex = command.description.index(after: lastDirectorySeparatorIndex)
let fileName = command.description[fileNameStartIndex...]
if let targetName = targetName {
return "\(action) \(targetName) \(fileName)"
} else {
return "\(action) \(fileName)"
}
} else {
return command.description
}
}
private func progressText(of message: SwiftCompilerMessage, targetName: String) -> String? {
if case .began(let info) = message.kind {
switch message.name {
case "compile":
if let sourceFile = info.inputs.first {
let sourceFilePath = try! AbsolutePath(validating: sourceFile)
return "Compiling \(targetName) \(sourceFilePath.components.last!)"
}
case "link":
return "Linking \(targetName)"
case "merge-module":
return "Merging module \(targetName)"
case "emit-module":
return "Emitting module \(targetName)"
case "generate-dsym":
return "Generating \(targetName) dSYM"
case "generate-pch":
return "Generating \(targetName) PCH"
default:
break
}
}
return nil
}
mutating func buildPreparationStepStarted(_ name: String) {
self.totalCount += 1
}
mutating func buildPreparationStepFinished(_ name: String) {
latestFinishedText = name
self.finishedCount += 1
}
}
extension SwiftCompilerMessage {
fileprivate var verboseProgressText: String? {
switch kind {
case .began(let info):
return ([info.commandExecutable] + info.commandArguments).joined(separator: " ")
case .skipped, .finished, .signalled, .unparsableOutput:
return nil
}
}
fileprivate var standardOutput: String? {
switch kind {
case .finished(let info),
.signalled(let info):
return info.output
case .unparsableOutput(let output):
return output
case .skipped, .began:
return nil
}
}
}
private extension Basics.Diagnostic {
static func cycleError(rules: [BuildKey]) -> Self {
.error("build cycle detected: " + rules.map{ $0.key }.joined(separator: ", "))
}
static func missingInputs(output: BuildKey, inputs: [BuildKey]) -> Self {
let missingInputs = inputs.map{ $0.key }.joined(separator: ", ")
return .error("couldn't build \(output.key) because of missing inputs: \(missingInputs)")
}
static func multipleProducers(output: BuildKey, commands: [SPMLLBuild.Command]) -> Self {
let producers = commands.map{ $0.description }.joined(separator: ", ")
return .error("couldn't build \(output.key) because of missing producers: \(producers)")
}
static func commandError(command: SPMLLBuild.Command, message: String) -> Self {
.error("command \(command.description) failed: \(message)")
}
static func swiftCompilerOutputParsingError(_ error: String) -> Self {
.error("failed parsing the Swift compiler output: \(error)")
}
}
private extension BuildSystemCommand {
init(_ command: SPMLLBuild.Command) {
self.init(
name: command.name,
description: command.description,
verboseDescription: command.verboseDescription
)
}
}
| apache-2.0 |
cc001/learnSwiftBySmallProjects | 17-TrumblrMenu/TrumblrMenu/MenuViewController.swift | 1 | 1290 | //
// MenuViewController.swift
// TrumblrMenu
//
// Created by ้้ฏ on 2016/12/23.
// Copyright ยฉ 2016ๅนด CC. All rights reserved.
//
import UIKit
class MenuViewController: UIViewController {
let transitionManager = MenuTransitionManager()
@IBOutlet weak var leftTopView: UIStackView!
@IBOutlet weak var rightTopView: UIStackView!
@IBOutlet weak var leftCenterView: UIStackView!
@IBOutlet weak var rightCenterView: UIStackView!
@IBOutlet weak var leftBottomView: UIStackView!
@IBOutlet weak var rightBottomView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.transitioningDelegate = self.transitionManager
}
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 |
CodaFi/PersistentStructure.swift | Persistent/LazilyPersistentVector.swift | 1 | 860 | //
// LazilyPersistentVector.swift
// Persistent
//
// Created by Robert Widmann on 12/22/15.
// Copyright ยฉ 2015 TypeLift. All rights reserved.
//
class LazilyPersistentVector {
class func createOwning(items: Array<AnyObject>) -> IPersistentVector {
if items.count == 0 {
return PersistentVector.empty
} else if items.count <= 32 {
return PersistentVector(cnt: items.count, shift: 5, root: (PersistentVector.emptyNode as? INode)!, tail: items)
}
return PersistentVector.createWithItems(items)
}
class func create(collec: ICollection?) -> IPersistentVector {
guard let coll = collec as? ISeq else {
return LazilyPersistentVector.createOwning(collec?.toArray ?? [])
}
if coll.count <= 32 {
return LazilyPersistentVector.createOwning(collec?.toArray ?? [])
}
return PersistentVector.createWithSeq(Utils.seq(coll))
}
}
| mit |
White-Label/Swift-SDK | WhiteLabel/CoreData/WLLabel+CoreDataClass.swift | 1 | 2623 | //
// WLLabel+CoreDataClass.swift
//
// Created by Alex Givens http://alexgivens.com on 7/24/17
// Copyright ยฉ 2017 Noon Pacific LLC http://noonpacific.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import CoreData
@objc(WLLabel)
final public class WLLabel: NSManagedObject, ResponseObjectSerializable, ResponseCollectionSerializable {
public static let entityName = "WLLabel"
convenience init?(response: HTTPURLResponse, representation: Any) {
let context = CoreDataStack.shared.backgroundManagedObjectContext
let entity = NSEntityDescription.entity(forEntityName: WLLabel.entityName, in: context)!
self.init(entity: entity, insertInto: context)
guard
let representation = representation as? [String: Any],
let id = representation["id"] as? Int32,
let slug = representation["slug"] as? String,
let name = representation["name"] as? String
// let serviceRepresentation = representation["service"]
else {
return nil
}
self.id = id
self.slug = slug
self.name = name
iconURL = representation["icon"] as? String
// self.service = WLService(response: response, representation: serviceRepresentation)
}
func updateInstanceWith(response: HTTPURLResponse, representation: Any) {
}
static func existingInstance(response: HTTPURLResponse, representation: Any) -> Self? {
return nil
}
}
| mit |
Xopoko/SpaceView | Example/ViewController.swift | 1 | 4781 | //
// ViewController.swift
// SpaceViewExample
//
// Created by user on 25.12.16.
// Copyright ยฉ 2016 horoko. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var timeStepper: UIStepper!
@IBOutlet weak var autohideTimeLabel: UILabel!
private var timeToAutoHide = 3.0
private var shouldAutoHide = true
private var leftSwipeAccepted = true
private var topSwipeAccepted = true
private var rightSwipeAccepted = true
private var botSwipeAccepted = true
private var spaceStyle: SpaceStyles? = nil
private var spaceTitle = "Title"
private var spaceDescr = "Description"
private var image: UIImage? = nil
private var withImage = false
private var spacePosition: SpacePosition = .top
var possibleDirectionsToHide: [HideDirection] = []
override func viewDidLoad() {
super.viewDidLoad()
autohideTimeLabel.text = String(timeStepper.value)
timeToAutoHide = timeStepper.value
}
@IBAction func positionsChanged(_ sender: Any) {
if let sc = sender as? UISegmentedControl {
switch sc.selectedSegmentIndex {
case 0:
spacePosition = .top
case 1:
spacePosition = .bot
default:
break
}
}
}
@IBAction func styleChanged(_ sender: Any) {
if let sc = sender as? UISegmentedControl {
switch sc.selectedSegmentIndex {
case 0:
spaceStyle = .success
case 1:
spaceStyle = .error
case 2:
spaceStyle = .warning
case 3:
spaceStyle = nil
default:
break
}
}
}
@IBAction func showSpace(_ sender: Any) {
image = nil
possibleDirectionsToHide.removeAll()
if spaceStyle != nil {
switch spaceStyle! {
case .success:
if withImage {
image = UIImage(named: "ic_success")
}
spaceTitle = "Success"
spaceDescr = "Operation complete"
case .error:
if withImage {
image = UIImage(named: "ic_error")
}
spaceTitle = "Error"
spaceDescr = "Operation failed"
case .warning:
if withImage {
image = UIImage(named: "ic_warning")
}
spaceTitle = "Warning!"
spaceDescr = "Look at this!"
}
}
if leftSwipeAccepted {
possibleDirectionsToHide.append(.left)
}
if rightSwipeAccepted {
possibleDirectionsToHide.append(.right)
}
if topSwipeAccepted {
possibleDirectionsToHide.append(.top)
}
if botSwipeAccepted {
possibleDirectionsToHide.append(.bot)
}
self.showSpace(title: spaceTitle, description: spaceDescr, spaceOptions: [
.spaceHideTimer(timer: timeToAutoHide),
.possibleDirectionToHide(possibleDirectionsToHide),
.shouldAutoHide(should: shouldAutoHide),
.spaceStyle(style: spaceStyle),
.image(img: image),
.spacePosition(position: spacePosition),
.swipeAction {print("SWIPE")},
])
}
@IBAction func withImageSwitch(_ sender: Any) {
if let switcher = sender as? UISwitch {
withImage = switcher.isOn
}
}
@IBAction func stepperAutohide(_ sender: Any) {
if let stepper = sender as? UIStepper {
timeToAutoHide = stepper.value
autohideTimeLabel.text = String(stepper.value)
}
}
@IBAction func BotSwipeDirectionSwitch(_ sender: UISwitch) {
botSwipeAccepted = sender.isOn
}
@IBAction func TopSwipeDirectionSwitch(_ sender: Any) {
if let switcher = sender as? UISwitch {
topSwipeAccepted = switcher.isOn
}
}
@IBAction func RightSwipeDirectionSwitch(_ sender: Any) {
if let switcher = sender as? UISwitch {
rightSwipeAccepted = switcher.isOn
}
}
@IBAction func LeftSwipeDirectionSwitch(_ sender: Any) {
if let switcher = sender as? UISwitch {
leftSwipeAccepted = switcher.isOn
}
}
@IBAction func shouldAutohideSwitch(_ sender: Any) {
if let switcher = sender as? UISwitch {
shouldAutoHide = switcher.isOn
}
}
}
| mit |
Mrwerdo/QuickShare | QuickShare/QuickShare/VibrantWindow.swift | 1 | 1801 | //
// VibrantWindow.swift
// QuickShare
//
// Copyright (c) 2016 Andrew Thompson
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Cocoa
class VibrantWindow : NSWindow {
var titleItem: NSToolbarItem? {
if let items = self.toolbar?.items {
return items[1]
}
return nil
}
override var title: String {
didSet {
let textfield = titleItem?.view as? NSTextField
textfield?.stringValue = title
textfield?.needsDisplay = true
}
}
override func awakeFromNib() {
self.titlebarAppearsTransparent = true
self.appearance = NSAppearance(named: NSAppearanceNameVibrantLight)
self.titleVisibility = .Hidden
}
} | mit |
contentful-labs/markdown-example-ios | Code/MDTextViewController.swift | 1 | 1252 | //
// MDTextViewController.swift
// Markdown
//
// Created by Boris Bรผgling on 01/12/15.
// Copyright ยฉ 2015 Contentful GmbH. All rights reserved.
//
import CocoaMarkdown
import UIKit
class MDTextViewController: UIViewController {
var entryId = "4bJdF7zhwkwcWq202gmkuM"
convenience init() {
self.init(nibName: nil, bundle: nil)
self.tabBarItem = UITabBarItem(title: "TextView", image: UIImage(named: "lightning"), tag: 0)
}
override func viewDidLoad() {
super.viewDidLoad()
let textView = UITextView(frame: view.bounds)
textView.isEditable = false
view.addSubview(textView)
client.fetchEntry(identifier: entryId).1.next { (entry) in
if let markdown = entry.fields["body"] as? String {
let data = markdown.data(using: String.Encoding.utf8)
let document = CMDocument(data: data, options: [])
let renderer = CMAttributedStringRenderer(document: document, attributes: CMTextAttributes())
DispatchQueue.main.async {
textView.attributedText = renderer?.render()
}
}
}.error { (error) in
showError(error, self)
}
}
}
| mit |
IngmarStein/swift | test/ClangModules/MixedSource/mixed-nsuinteger.swift | 4 | 1525 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/user-module -parse %s -verify
// REQUIRES: objc_interop
// Type checker should not report any errors in the code below.
import Foundation
import user
var ui: UInt = 5
var i: Int = 56
var p: UnsafeMutablePointer<NSFastEnumerationState>?
var pp: AutoreleasingUnsafeMutablePointer<AnyObject?>?
var userTypedObj = NSUIntTest()
// Check that the NSUInteger comes across as UInt from user Obj C modules.
var ur: UInt = userTypedObj.myCustomMethodThatOperates(onNSUIntegers: ui)
userTypedObj.intProp = ui
userTypedObj.typedefProp = ui
ur = testFunction(ui)
testFunctionInsideMacro(ui)
// Test that nesting works.
var pui: UnsafeMutablePointer<UInt>
ur = testFunctionWithPointerParam(pui)
// NSUIntTest is a user class that conforms to a system defined protocol.
// The types are treated as system types when working with objects having
// protocol type.
var a: [NSFastEnumeration] = [NSUIntTest(), NSUIntTest()]
var r: Int = a[0].countByEnumerating(with: p!, objects: pp!, count: i)
// When working with instances typed as user-defined, NSUInteger comes
// across as UInt.
var rr: UInt = userTypedObj.countByEnumerating(with: p!, objects: pp!, count: ui)
// Check exercising protocol conformance.
func gen<T:NSFastEnumeration>(_ t:T) {
let i: Int = 56
let p: UnsafeMutablePointer<NSFastEnumerationState>?
let pp: AutoreleasingUnsafeMutablePointer<AnyObject?>?
t.countByEnumerating(with: p!, objects: pp!, count: i)
}
gen(userTypedObj)
| apache-2.0 |
motoom/ios-apps | Pour/Pour/SelectingState.swift | 1 | 848 |
// Let the user select a source and destination vessel.
// TODO: Might be more states?
import GameplayKit
class SelectingState: GameState {
override init(controller: GameController) {
super.init(controller: controller)
}
override func didEnterWithPreviousState(prevState: GKState?) {
super.didEnterWithPreviousState(prevState)
print("Entered Selecting from \(prevState)")
}
override func updateWithDeltaTime(seconds: NSTimeInterval) {
print("SelectingState.updateWithDeltaTime(\(seconds))")
super.updateWithDeltaTime(seconds)
// TODO: Let user do their thing, and when done:
self.stateMachine?.enterState(PouringState)
}
override func isValidNextState(stateClass: AnyClass) -> Bool {
return stateClass is PouringState.Type
}
}
| mit |
evilpunisher24/HooperPics | HooperPics/HooperPicsDigger.swift | 1 | 838 | //
// HooperPicsDigger.swift
// HooperPics
//
// Created by YeYiquan on 15/12/1.
// Copyright (c) 2015ๅนด YeYiquan. All rights reserved.
//
import Foundation
import UIKit
class HooperPicsDigger{
let homePage = "http://tu.hupu.com"
var picsAddress = [String]()//ๅญๅจไป็ฝ้กตไธๆชๅ็ๅพ็ipๅฐๅๆฐๆฎ
init() {
let url = NSURL(string: homePage)!
let data = NSData(contentsOfURL: url)!
let htmlDoc = TFHpple(HTMLData: data)
let txtNodes = htmlDoc.searchWithXPathQuery("//a[@class='img-a']")
for eachTxtNodes in txtNodes{
if let elements = eachTxtNodes.childrenWithTagName("img"){
for eachElement in elements {
picsAddress.append(eachElement.objectForKey("src")!)
}
}
}
}
} | mit |
chai2010/ptyy | ios-app/yjyy-swift/MainViewController.swift | 1 | 7920 | // Copyright 2016 <chaishushan{AT}gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
import UIKit
class MainViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
var refreshControl = UIRefreshControl()
var db:DataEngin = DataEngin()
var results = [[String]]()
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
let footerBar = UILabel()
footerBar.text = "ๅ
ฑ N ไธช็ปๆ\n"
footerBar.textAlignment = NSTextAlignment.Center
footerBar.numberOfLines = 0
footerBar.lineBreakMode = NSLineBreakMode.ByWordWrapping
footerBar.textColor = UIColor.darkGrayColor()
footerBar.sizeToFit()
self.tableView.tableFooterView = footerBar
self.tableView.dataSource = self
self.tableView.delegate = self
self.refreshControl.addTarget(self, action: #selector(MainViewController.refreshData), forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(self.refreshControl)
// ๆณจๅTableViewCell
self.tableView.registerClass(MyCustomMenuCell.self, forCellReuseIdentifier: MyCustomMenuCell.ReuseIdentifier)
// ็ๆๅๅงๅ่กจ
self.searchBarSearchButtonClicked(searchBar)
}
// ๅทๆฐๆฐๆฎ
func refreshData() {
NSThread.sleepForTimeInterval(1.0)
self.refreshControl.endRefreshing()
}
// ๅไบซApp
@IBAction func onShareApp(sender: UIBarButtonItem) {
let utlTilte = "้้ธกๅป้ข - ่็ฐ็ณปๅป้ขๆฅ่ฏข"
let urlStr = "https://appsto.re/cn/QH8ocb.i"
let appStoreUrl = NSURL(string: urlStr.stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLQueryAllowedCharacterSet())!)
let activity = UIActivityViewController(activityItems: [utlTilte, appStoreUrl!], applicationActivities: nil)
self.presentViewController(activity, animated: true, completion: nil)
// ไฟฎๅค iPad ไธๅดฉๆบ้ฎ้ข
if #available(iOS 8.0, *) {
let presentationController = activity.popoverPresentationController
presentationController?.sourceView = view
}
}
// ๅ
ณไบๆ้ฎ
@IBAction func onAbout(sender: UIBarButtonItem) {
let title = "ๅ
ณไบ ้้ธกๅป้ข"
let message = "" +
"็จไบๆฅ่ฏขไธญๅฝๅคง้่พๅธธ่ง็้ๅ
ฌๆๆ็งไบบๆฟๅ
็้้ธกๅป้ขๆ็งๅฎค(ไปฅ่็ฐ็ณปไธบไธป)๏ผๆฏๆ ๆผ้ณ/ๆฑๅญ/ๆฐๅญ/ๆญฃๅ ๆฅ่ฏขใ\n" +
"\n" +
"ๆฅ่ฏขๆฐๆฎๆฅๆบไบไบ่็ฝ, ๆฌๅบ็จๅนถไธไฟ่ฏๆฐๆฎ็็ๅฎๆงๅๅ็กฎๆง๏ผๆฅ่ฏข็ปๆๅชไฝไธบๅฐฑๅปๅ็ไธไธชๅ่ใ\n" +
"\n" +
"็ๆ 2016 @chaishushan"
if #available(iOS 8.0, *) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let githubAction = UIAlertAction(title: "Github", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
let urlStr = "https://github.com/chai2010/ptyy"
let githubUrl = NSURL(string: urlStr.stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLQueryAllowedCharacterSet())!)
UIApplication.sharedApplication().openURL(githubUrl!)
}
let cancelAction = UIAlertAction(title: "ๅๆถ", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
// OK
}
alertController.addAction(githubAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: "็กฎๅฎ")
alert.show()
}
}
// -------------------------------------------------------
// UITableViewDataSource
// -------------------------------------------------------
// ่กจๆ ผๅๅ
ๆฐ็ฎ
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.results.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.results[section].count
}
// ่กจๆ ผๅๅ
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier(MyCustomMenuCell.ReuseIdentifier, forIndexPath: indexPath)
cell.textLabel?.text = self.results[indexPath.section][indexPath.row]
return cell
}
// ๅณไพง็ดขๅผ
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
var keys:[String] = []
for ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ#".characters {
keys.append("\(ch)")
}
return keys
}
// -------------------------------------------------------
// UITableViewDelegate
// -------------------------------------------------------
func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return action == MenuAction.Copy.selector() || MenuAction.supportedAction(action)
}
func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
if action == #selector(NSObject.copy(_:)) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
UIPasteboard.generalPasteboard().string = cell!.textLabel!.text
}
}
// ้ๆฉๅๆถ้่ๆ็ดข้ฎ็
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.searchBar.showsCancelButton = false
// ๆดๆฐๆฃ็ดขๆ ็ถๆ
self.searchBar.resignFirstResponder()
// ๅทฒ็ป้ๆฉ็่ฏ, ๅๅๆถ้ๆฉ
if indexPath == tableView.indexPathForSelectedRow {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
// -------------------------------------------------------
// UISearchBarDelegate
// -------------------------------------------------------
// ๆฃ็ดขๆ ็ถๆ
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
self.searchBar.showsCancelButton = true
}
// ็นๅปๆ็ดขๆ้ฎ
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
// ๆ นๆฎๆฅ่ฏขๆกไปถๆฅ่ฏข็ปๆ
self.results = self.db.SearchV2(searchBar.text!)
self.searchBar.showsCancelButton = false
let footerBar = self.tableView.tableFooterView as? UILabel
footerBar!.text = "ๅ
ฑ \(self.numberOfResult()) ไธช็ปๆ\n"
// ๆดๆฐๅ่กจ่งๅพ
self.tableView.reloadData()
self.searchBar.resignFirstResponder()
}
// ๆฃ็ดข่ฏๅ็ๅๅ
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
// ๆ นๆฎๆฅ่ฏขๆกไปถๆฅ่ฏข็ปๆ
self.results = self.db.SearchV2(searchBar.text!)
let footerBar = self.tableView.tableFooterView as? UILabel
footerBar!.text = "ๅ
ฑ \(self.numberOfResult()) ไธช็ปๆ\n"
// ๆดๆฐๅ่กจ่งๅพ
self.tableView.reloadData()
}
// ๅๆถๆ็ดข
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// ้่ๅๆถๆ้ฎ
self.searchBar.showsCancelButton = false
self.searchBar.text = ""
// ๆ นๆฎๆฅ่ฏขๆกไปถๆฅ่ฏข็ปๆ(ๆฒกๆๆฅ่ฏขๆกไปถ)
self.results = self.db.SearchV2("")
let footerBar = self.tableView.tableFooterView as? UILabel
footerBar!.text = "ๅ
ฑ \(self.numberOfResult()) ไธช็ปๆ\n"
// ๆดๆฐๅ่กจ่งๅพ
self.tableView.reloadData()
// ๆดๆฐๆฃ็ดขๆ ็ถๆ
self.searchBar.resignFirstResponder()
}
// -------------------------------------------------------
// ่พ
ๅฉๅฝๆฐ
// -------------------------------------------------------
// ็ปๆๆปๆฐ
private func numberOfResult() -> Int {
var sum:Int = 0
for x in self.results {
sum += x.count
}
return sum
}
// -------------------------------------------------------
// END
// -------------------------------------------------------
}
| bsd-3-clause |
haifengkao/NightWatch | Example/StationModel.swift | 1 | 2000 | //
// StationModel.swift
// UbikeTracer
//
// Created by rosa on 2017/7/21.
// Copyright ยฉ 2017ๅนด CocoaPods. All rights reserved.
//
import CoreLocation
import Foundation
struct StationModel {
let id: String
let name: String
let coordinate: CLLocationCoordinate2D
let numberOfSpaces: Int
let numberOfBikes: Int
let updateTime: Date
var distance: Double = 0.0
var bikesHistory: [Int] = []
var predict30MinChange: Int = 0
var fullPercent: Double {
return Double(self.numberOfBikes) / (Double(self.numberOfSpaces) + Double(self.numberOfBikes))
}
}
extension StationModel {
enum ParseDataError: Error { case Missingid, MissingName, MissingCoor, MissingData, MissingTime }
init(dict: [String:Any] ) throws {
guard let id = dict["sno"] as? String else { throw ParseDataError.Missingid }
self.id = id
guard let name = dict["sna"] as? String else { throw ParseDataError.MissingName }
self.name = name
guard let latStr = dict["lat"] as? String,
let lngStr = dict["lng"] as? String,
let lat = Double(latStr),
let lng = Double(lngStr) else { throw ParseDataError.MissingCoor }
self.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
guard let spacesStr = dict["bemp"] as? String,
let bikesStr = dict["sbi"] as? String,
let spaces = Int(spacesStr),
let bikes = Int(bikesStr) else { throw ParseDataError.MissingData }
self.numberOfSpaces = spaces
self.numberOfBikes = bikes
guard let time = dict["mday"] as? String else { throw ParseDataError.MissingTime }
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddHHmmss"
dateFormatter.timeZone = TimeZone.current
let date = dateFormatter.date(from: time)!
self.updateTime = date
}
}
| mit |
Tnecniv/zenith | zenith/ViewController.swift | 1 | 459 | //
// ViewController.swift
// macme
//
// Created by Vincent Pacelli on 7/3/15.
// Copyright (c) 2015 tnecniv. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
| gpl-3.0 |
mcddx330/Pumpkin | Pumpkin/PKFileManage.swift | 1 | 1546 | //
// PKFileManage.swift
// Pumpkin
//
// Created by dimbow. on 2/6/15.
// Copyright (c) 2015 dimbow. All rights reserved.
//
import Foundation
public typealias PKSaveData = Dictionary<String,AnyObject>;
public class PKFileManage{
private var domainPaths:NSArray!;
private var docDir:NSString!;
private var filePath:NSString!;
private var fileData:NSData!;
private var DestinationFileName:String = "DefaultGameData.plist";
public var saveData = PKSaveData();
public init(plistName:String!){
if(plistName != nil){
DestinationFileName = plistName!;
}
domainPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray;
docDir = domainPaths!.objectAtIndex(0) as? NSString;
filePath = docDir!.stringByAppendingPathComponent(DestinationFileName);
}
}
extension PKFileManage {
public func Save()->Bool{
fileData = NSKeyedArchiver.archivedDataWithRootObject(saveData);
return fileData.writeToFile(filePath as! String, atomically: true);
}
public func Load()->PKSaveData{
let fileManager = NSFileManager.defaultManager();
var res = PKSaveData();
if(!fileManager.fileExistsAtPath(filePath! as! String)){
res = ["Result":false];
}else{
let data = NSData(contentsOfFile: filePath! as! String);
res = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! PKSaveData;
}
return res;
}
}
| mit |
ustwo/formvalidator-swift | Sources/Configurations/PostcodeConfiguration.swift | 1 | 1913 | //
// PostcodeConfiguration.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 04/01/2017.
// Copyright ยฉ 2017 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
/// Countries that are supported by `PostcodeCondition`. Each postcode is an ISO 3166-1 alpha-3 country code. There is a `regex` property that returns the regex for validating that country's postcode.
public enum PostcodeCountries: String {
case sweden = "SWE"
case turkey = "TUR"
case unitedKingdom = "GBR"
case unitedStates = "USA"
/// The regex for validating the country's postcode.
public var regex: String {
switch self {
case .sweden:
return "^(SE-)?[0-9]{3}\\s?[0-9]{2}$"
case .turkey:
return "^[0-9]{5}$"
case .unitedKingdom:
return "^([A-PR-UWYZa-pr-uwyz]([0-9]{1,2}|([A-HK-Ya-hk-y][0-9]|[A-HK-Ya-hk-y][0-9]([0-9]|[ABEHMNPRV-Yabehmnprv-y]))|[0-9][A-HJKS-UWa-hjks-uw])\\ {0,1}[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}|([Gg][Ii][Rr]\\ 0[Aa][Aa])|([Ss][Aa][Nn]\\ {0,1}[Tt][Aa]1)|([Bb][Ff][Pp][Oo]\\ {0,1}([Cc]\\/[Oo]\\ )?[0-9]{1,4})|(([Aa][Ss][Cc][Nn]|[Bb][Bb][Nn][Dd]|[BFSbfs][Ii][Qq][Qq]|[Pp][Cc][Rr][Nn]|[Ss][Tt][Hh][Ll]|[Tt][Dd][Cc][Uu]|[Tt][Kk][Cc][Aa])\\ {0,1}1[Zz][Zz]))$"
case .unitedStates:
return "^[0-9]{5}(?:[-|\\s][0-9]{4})?$"
}
}
public static let allValues: [PostcodeCountries] = [.sweden, .turkey, .unitedKingdom, .unitedStates]
}
/// Stores configuration for `PostcodeCondition`.
public struct PostcodeConfiguration: Configuration {
// MARK: - Properties
public var country: PostcodeCountries
// MARK: - Initializers
public init() {
self.init(country: .unitedKingdom)
}
public init(country: PostcodeCountries = .unitedKingdom) {
self.country = country
}
}
| mit |
natecook1000/swift | stdlib/public/core/StringBridge.swift | 2 | 13735 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
#if _runtime(_ObjC)
// Swift's String bridges NSString via this protocol and these
// variables, allowing the core stdlib to remain decoupled from
// Foundation.
/// Effectively an untyped NSString that doesn't require foundation.
public typealias _CocoaString = AnyObject
@inlinable // FIXME(sil-serialize-all)
public // @testable
func _stdlib_binary_CFStringCreateCopy(
_ source: _CocoaString
) -> _CocoaString {
let result = _swift_stdlib_CFStringCreateCopy(nil, source) as AnyObject
return result
}
@inlinable // FIXME(sil-serialize-all)
@_effects(readonly)
public // @testable
func _stdlib_binary_CFStringGetLength(
_ source: _CocoaString
) -> Int {
return _swift_stdlib_CFStringGetLength(source)
}
@inlinable // FIXME(sil-serialize-all)
public // @testable
func _stdlib_binary_CFStringGetCharactersPtr(
_ source: _CocoaString
) -> UnsafeMutablePointer<UTF16.CodeUnit>? {
return UnsafeMutablePointer(
mutating: _swift_stdlib_CFStringGetCharactersPtr(source))
}
/// Loading Foundation initializes these function variables
/// with useful values
/// Copies the entire contents of a _CocoaString into contiguous
/// storage of sufficient capacity.
@usableFromInline // FIXME(sil-serialize-all)
@inline(never) // Hide the CF dependency
internal func _cocoaStringReadAll(
_ source: _CocoaString, _ destination: UnsafeMutablePointer<UTF16.CodeUnit>
) {
_swift_stdlib_CFStringGetCharacters(
source, _swift_shims_CFRange(
location: 0, length: _swift_stdlib_CFStringGetLength(source)), destination)
}
/// Copies a slice of a _CocoaString into contiguous storage of
/// sufficient capacity.
@usableFromInline // FIXME(sil-serialize-all)
@inline(never) // Hide the CF dependency
internal func _cocoaStringCopyCharacters(
from source: _CocoaString,
range: Range<Int>,
into destination: UnsafeMutablePointer<UTF16.CodeUnit>
) {
_swift_stdlib_CFStringGetCharacters(
source,
_swift_shims_CFRange(location: range.lowerBound, length: range.count),
destination)
}
@usableFromInline // FIXME(sil-serialize-all)
@inline(never) // Hide the CF dependency
internal func _cocoaStringSlice(
_ target: _CocoaString, _ bounds: Range<Int>
) -> _CocoaString {
let cfSelf: _swift_shims_CFStringRef = target
_sanityCheck(
_swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil,
"Known contiguously stored strings should already be converted to Swift")
let cfResult = _swift_stdlib_CFStringCreateWithSubstring(
nil, cfSelf, _swift_shims_CFRange(
location: bounds.lowerBound, length: bounds.count)) as AnyObject
return cfResult
}
@usableFromInline // FIXME(sil-serialize-all)
@inline(never) // Hide the CF dependency
internal func _cocoaStringSubscript(
_ target: _CocoaString, _ position: Int
) -> UTF16.CodeUnit {
let cfSelf: _swift_shims_CFStringRef = target
_sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil,
"Known contiguously stored strings should already be converted to Swift")
return _swift_stdlib_CFStringGetCharacterAtIndex(cfSelf, position)
}
//
// Conversion from NSString to Swift's native representation
//
@inlinable // FIXME(sil-serialize-all)
internal var kCFStringEncodingASCII : _swift_shims_CFStringEncoding {
@inline(__always) get { return 0x0600 }
}
@inlinable // FIXME(sil-serialize-all)
internal var kCFStringEncodingUTF8 : _swift_shims_CFStringEncoding {
@inline(__always) get { return 0x8000100 }
}
@usableFromInline // @opaque
internal func _bridgeASCIICocoaString(
_ cocoa: _CocoaString,
intoUTF8 bufPtr: UnsafeMutableRawBufferPointer
) -> Int? {
let ptr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked.assumingMemoryBound(
to: UInt8.self)
let length = _stdlib_binary_CFStringGetLength(cocoa)
var count = 0
let numCharWritten = _swift_stdlib_CFStringGetBytes(
cocoa, _swift_shims_CFRange(location: 0, length: length),
kCFStringEncodingUTF8, 0, 0, ptr, bufPtr.count, &count)
return length == numCharWritten ? count : nil
}
@usableFromInline
internal func _bridgeToCocoa(_ small: _SmallUTF8String) -> _CocoaString {
return small.withUTF8CodeUnits { bufPtr in
return _swift_stdlib_CFStringCreateWithBytes(
nil, bufPtr.baseAddress._unsafelyUnwrappedUnchecked,
bufPtr.count,
small.isASCII ? kCFStringEncodingASCII : kCFStringEncodingUTF8, 0)
as AnyObject
}
}
internal func _getCocoaStringPointer(
_ cfImmutableValue: _CocoaString
) -> (UnsafeRawPointer?, isUTF16: Bool) {
// Look first for null-terminated ASCII
// Note: the code in clownfish appears to guarantee
// nul-termination, but I'm waiting for an answer from Chris Kane
// about whether we can count on it for all time or not.
let nulTerminatedASCII = _swift_stdlib_CFStringGetCStringPtr(
cfImmutableValue, kCFStringEncodingASCII)
// start will hold the base pointer of contiguous storage, if it
// is found.
var start: UnsafeRawPointer?
let isUTF16 = (nulTerminatedASCII == nil)
if isUTF16 {
let utf16Buf = _swift_stdlib_CFStringGetCharactersPtr(cfImmutableValue)
start = UnsafeRawPointer(utf16Buf)
} else {
start = UnsafeRawPointer(nulTerminatedASCII)
}
return (start, isUTF16: isUTF16)
}
@usableFromInline
@inline(never) // Hide the CF dependency
internal
func _makeCocoaStringGuts(_ cocoaString: _CocoaString) -> _StringGuts {
if let ascii = cocoaString as? _ASCIIStringStorage {
return _StringGuts(_large: ascii)
} else if let utf16 = cocoaString as? _UTF16StringStorage {
return _StringGuts(_large: utf16)
} else if let wrapped = cocoaString as? _NSContiguousString {
return wrapped._guts
} else if _isObjCTaggedPointer(cocoaString) {
guard let small = _SmallUTF8String(_cocoaString: cocoaString) else {
fatalError("Internal invariant violated: large tagged NSStrings")
}
return _StringGuts(small)
}
// "copy" it into a value to be sure nobody will modify behind
// our backs. In practice, when value is already immutable, this
// just does a retain.
let immutableCopy
= _stdlib_binary_CFStringCreateCopy(cocoaString) as AnyObject
if _isObjCTaggedPointer(immutableCopy) {
guard let small = _SmallUTF8String(_cocoaString: cocoaString) else {
fatalError("Internal invariant violated: large tagged NSStrings")
}
return _StringGuts(small)
}
let (start, isUTF16) = _getCocoaStringPointer(immutableCopy)
let length = _StringGuts.getCocoaLength(
_unsafeBitPattern: Builtin.reinterpretCast(immutableCopy))
return _StringGuts(
_largeNonTaggedCocoaObject: immutableCopy,
count: length,
isSingleByte: !isUTF16,
start: start)
}
extension String {
public // SPI(Foundation)
init(_cocoaString: AnyObject) {
self._guts = _makeCocoaStringGuts(_cocoaString)
}
}
// At runtime, this class is derived from `_SwiftNativeNSStringBase`,
// which is derived from `NSString`.
//
// The @_swift_native_objc_runtime_base attribute
// This allows us to subclass an Objective-C class and use the fast Swift
// memory allocator.
@_fixed_layout // FIXME(sil-serialize-all)
@objc @_swift_native_objc_runtime_base(_SwiftNativeNSStringBase)
public class _SwiftNativeNSString {
@usableFromInline // FIXME(sil-serialize-all)
@objc
internal init() {}
deinit {}
}
/// A shadow for the "core operations" of NSString.
///
/// Covers a set of operations everyone needs to implement in order to
/// be a useful `NSString` subclass.
@objc
public protocol _NSStringCore : _NSCopying /* _NSFastEnumeration */ {
// The following methods should be overridden when implementing an
// NSString subclass.
@objc(length)
var length: Int { get }
@objc(characterAtIndex:)
func character(at index: Int) -> UInt16
// We also override the following methods for efficiency.
@objc(getCharacters:range:)
func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>,
range aRange: _SwiftNSRange)
@objc(_fastCharacterContents)
func _fastCharacterContents() -> UnsafePointer<UInt16>?
}
/// An `NSString` built around a slice of contiguous Swift `String` storage.
@_fixed_layout // FIXME(sil-serialize-all)
public final class _NSContiguousString : _SwiftNativeNSString, _NSStringCore {
public let _guts: _StringGuts
@inlinable // FIXME(sil-serialize-all)
public init(_ _guts: _StringGuts) {
_sanityCheck(!_guts._isOpaque,
"_NSContiguousString requires contiguous storage")
self._guts = _guts
super.init()
}
@inlinable // FIXME(sil-serialize-all)
public init(_unmanaged guts: _StringGuts) {
_sanityCheck(!guts._isOpaque,
"_NSContiguousString requires contiguous storage")
if guts.isASCII {
self._guts = _StringGuts(_large: guts._unmanagedASCIIView)
} else {
self._guts = _StringGuts(_large: guts._unmanagedUTF16View)
}
super.init()
}
@inlinable // FIXME(sil-serialize-all)
public init(_unmanaged guts: _StringGuts, range: Range<Int>) {
_sanityCheck(!guts._isOpaque,
"_NSContiguousString requires contiguous storage")
if guts.isASCII {
self._guts = _StringGuts(_large: guts._unmanagedASCIIView[range])
} else {
self._guts = _StringGuts(_large: guts._unmanagedUTF16View[range])
}
super.init()
}
@usableFromInline // FIXME(sil-serialize-all)
@objc
init(coder aDecoder: AnyObject) {
_sanityCheckFailure("init(coder:) not implemented for _NSContiguousString")
}
@inlinable // FIXME(sil-serialize-all)
deinit {}
@inlinable
@objc(length)
public var length: Int {
return _guts.count
}
@inlinable
@objc(characterAtIndex:)
public func character(at index: Int) -> UInt16 {
defer { _fixLifetime(self) }
return _guts.codeUnit(atCheckedOffset: index)
}
@inlinable
@objc(getCharacters:range:)
public func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>,
range aRange: _SwiftNSRange) {
_precondition(aRange.location >= 0 && aRange.length >= 0)
let range: Range<Int> = aRange.location ..< aRange.location + aRange.length
_precondition(range.upperBound <= Int(_guts.count))
if _guts.isASCII {
_guts._unmanagedASCIIView[range]._copy(
into: UnsafeMutableBufferPointer(start: buffer, count: range.count))
} else {
_guts._unmanagedUTF16View[range]._copy(
into: UnsafeMutableBufferPointer(start: buffer, count: range.count))
}
_fixLifetime(self)
}
@inlinable
@objc(_fastCharacterContents)
public func _fastCharacterContents() -> UnsafePointer<UInt16>? {
guard !_guts.isASCII else { return nil }
return _guts._unmanagedUTF16View.start
}
@objc(copyWithZone:)
public func copy(with zone: _SwiftNSZone?) -> AnyObject {
// Since this string is immutable we can just return ourselves.
return self
}
/// The caller of this function guarantees that the closure 'body' does not
/// escape the object referenced by the opaque pointer passed to it or
/// anything transitively reachable form this object. Doing so
/// will result in undefined behavior.
@inlinable // FIXME(sil-serialize-all)
@_semantics("self_no_escaping_closure")
func _unsafeWithNotEscapedSelfPointer<Result>(
_ body: (OpaquePointer) throws -> Result
) rethrows -> Result {
let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self)
defer {
_fixLifetime(self)
}
return try body(selfAsPointer)
}
/// The caller of this function guarantees that the closure 'body' does not
/// escape either object referenced by the opaque pointer pair passed to it or
/// transitively reachable objects. Doing so will result in undefined
/// behavior.
@inlinable // FIXME(sil-serialize-all)
@_semantics("pair_no_escaping_closure")
func _unsafeWithNotEscapedSelfPointerPair<Result>(
_ rhs: _NSContiguousString,
_ body: (OpaquePointer, OpaquePointer) throws -> Result
) rethrows -> Result {
let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self)
let rhsAsPointer = unsafeBitCast(rhs, to: OpaquePointer.self)
defer {
_fixLifetime(self)
_fixLifetime(rhs)
}
return try body(selfAsPointer, rhsAsPointer)
}
}
extension String {
/// Same as `_bridgeToObjectiveC()`, but located inside the core standard
/// library.
@inlinable // FIXME(sil-serialize-all)
public func _stdlib_binary_bridgeToObjectiveCImpl() -> AnyObject {
if _guts._isSmall {
return _bridgeToCocoa(_guts._smallUTF8String)
}
if let cocoa = _guts._underlyingCocoaString {
return cocoa
}
return _NSContiguousString(_guts)
}
@inline(never) // Hide the CF dependency
public func _bridgeToObjectiveCImpl() -> AnyObject {
return _stdlib_binary_bridgeToObjectiveCImpl()
}
}
// Called by the SwiftObject implementation to get the description of a value
// as an NSString.
@_silgen_name("swift_stdlib_getDescription")
public func _getDescription<T>(_ x: T) -> AnyObject {
return String(reflecting: x)._bridgeToObjectiveCImpl()
}
#else // !_runtime(_ObjC)
@_fixed_layout // FIXME(sil-serialize-all)
public class _SwiftNativeNSString {
@usableFromInline // FIXME(sil-serialize-all)
internal init() {}
deinit {}
}
public protocol _NSStringCore: class {}
#endif
| apache-2.0 |
cocoa-ai/FacesVisionDemo | Faces/ClassificationService.swift | 1 | 2409 | import CoreML
import Vision
import VisionLab
/// Delegate protocol used for `ClassificationService`
protocol ClassificationServiceDelegate: class {
func classificationService(_ service: ClassificationService, didDetectGender gender: String)
func classificationService(_ service: ClassificationService, didDetectAge age: String)
func classificationService(_ service: ClassificationService, didDetectEmotion emotion: String)
}
/// Service used to perform gender, age and emotion classification
final class ClassificationService: ClassificationServiceProtocol {
/// The service's delegate
weak var delegate: ClassificationServiceDelegate?
/// Array of vision requests
private var requests = [VNRequest]()
/// Create CoreML model and classification requests
func setup() {
do {
// Gender request
requests.append(VNCoreMLRequest(
model: try VNCoreMLModel(for: GenderNet().model),
completionHandler: handleGenderClassification
))
// Age request
requests.append(VNCoreMLRequest(
model: try VNCoreMLModel(for: AgeNet().model),
completionHandler: handleAgeClassification
))
// Emotions request
requests.append(VNCoreMLRequest(
model: try VNCoreMLModel(for: CNNEmotions().model),
completionHandler: handleEmotionClassification
))
} catch {
assertionFailure("Can't load Vision ML model: \(error)")
}
}
/// Run individual requests one by one.
func classify(image: CIImage) {
do {
for request in self.requests {
let handler = VNImageRequestHandler(ciImage: image)
try handler.perform([request])
}
} catch {
print(error)
}
}
// MARK: - Handling
@objc private func handleGenderClassification(request: VNRequest, error: Error?) {
let result = extractClassificationResult(from: request, count: 1)
delegate?.classificationService(self, didDetectGender: result)
}
@objc private func handleAgeClassification(request: VNRequest, error: Error?) {
let result = extractClassificationResult(from: request, count: 1)
delegate?.classificationService(self, didDetectAge: result)
}
@objc private func handleEmotionClassification(request: VNRequest, error: Error?) {
let result = extractClassificationResult(from: request, count: 1)
delegate?.classificationService(self, didDetectEmotion: result)
}
}
| mit |
aranasaurus/ratings-app | mobile/LikeLike/Application/Model/Tag.swift | 1 | 197 | //
// Tag.swift
// LikeLike
//
// Created by Ryan Arana on 10/26/17.
// Copyright ยฉ 2017 aranasaurus. All rights reserved.
//
import Foundation
struct Tag: Codable {
let title: String
}
| mit |
just-a-computer/carton | src/desktop/mac/Carton/AppDelegate.swift | 1 | 366 | import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var win: CartonWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
NSURLProtocol.registerClass(CartonUrlProtocol)
win = CartonWindow()
}
func applicationWillTerminate(aNotification: NSNotification) {
}
}
| mit |
litt1e-p/LPStatusBarBackgroundColor-swift | LPStatusBarBackgroundColorSample/LPStatusBarBackgroundColor/NavigationController.swift | 1 | 1933 | //
// NavigationController.swift
// LPStatusBarBackgroundColor
//
// Created by litt1e-p on 16/1/6.
// Copyright ยฉ 2016ๅนด litt1e-p. All rights reserved.
//
import UIKit
class NavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.statusBarBackgroundColor = UIColor.blackColor()
var barSize: CGSize = CGSizeMake(self.navigationBar.frame.size.width, 44)
self.navigationBar.setBackgroundImage(self.imageWithColor(UIColor.purpleColor(), andSize: &barSize), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
self.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
}
func imageWithColor(color: UIColor, inout andSize imageSize: CGSize) -> UIImage {
if CGSizeEqualToSize(imageSize, CGSizeZero) {
imageSize = CGSizeMake(1, 1)
}
let rect: CGRect = CGRectMake(0, 0, imageSize.width, imageSize.height)
UIGraphicsBeginImageContext(rect.size)
let context: CGContextRef = UIGraphicsGetCurrentContext()!
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
jamesjmtaylor/weg-ios | weg-ios/Animations/LoadingView.swift | 1 | 1456 | //
// LoadingView.swift
// weg-ios
//
// Created by Taylor, James on 5/24/18.
// Copyright ยฉ 2018 James JM Taylor. All rights reserved.
//
import UIKit
import Lottie
class LoadingView: UIView {
@IBOutlet weak var loadingView: LoadingView!
var animationView : LOTAnimationView?
static func getAndStartLoadingView() -> LoadingView {
guard let rootView = UIApplication.shared.keyWindow?.rootViewController?.view else {
return LoadingView()
}
guard let loadingView = Bundle.main.loadNibNamed("LoadingView",
owner: self,
options: nil)?.first as? LoadingView else {
return LoadingView()
}
loadingView.frame = rootView.frame
rootView.addSubview(loadingView)
loadingView.startAnimation()
loadingView.startAnimation()
return loadingView
}
func startAnimation(){
animationView = LOTAnimationView(name: "loading")
animationView?.frame = CGRect(x: 0, y: 0, width: 200, height: 100)
loadingView.addSubview(animationView!)
animationView?.loopAnimation = true
animationView?.play()
}
func stopAnimation(){
DispatchQueue.main.asyncAfter(deadline: .now() + 2){
self.removeFromSuperview()
}
}
}
| mit |
Shivol/Swift-CS333 | playgrounds/uiKit/uiKitCatalog/UIKitCatalog/TextViewController.swift | 3 | 7511 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sampleโs licensing information
Abstract:
A view controller that demonstrates how to use UITextView.
*/
import UIKit
class TextViewController: UIViewController, UITextViewDelegate {
// MARK: - Properties
@IBOutlet weak var textView: UITextView!
/// Used to adjust the text view's height when the keyboard hides and shows.
@IBOutlet weak var textViewBottomLayoutGuideConstraint: NSLayoutConstraint!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureTextView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Listen for changes to keyboard visibility so that we can adjust the text view accordingly.
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(TextViewController.handleKeyboardNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(TextViewController.handleKeyboardNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
// MARK: - Keyboard Event Notifications
func handleKeyboardNotification(_ notification: Notification) {
let userInfo = notification.userInfo!
// Get information about the animation.
let animationDuration: TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let rawAnimationCurveValue = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).uintValue
let animationCurve = UIViewAnimationOptions(rawValue: rawAnimationCurveValue)
// Convert the keyboard frame from screen to view coordinates.
let keyboardScreenBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardViewBeginFrame = view.convert(keyboardScreenBeginFrame, from: view.window)
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
let originDelta = keyboardViewEndFrame.origin.y - keyboardViewBeginFrame.origin.y
// The text view should be adjusted, update the constant for this constraint.
textViewBottomLayoutGuideConstraint.constant -= originDelta
// Inform the view that its autolayout constraints have changed and the layout should be updated.
view.setNeedsUpdateConstraints()
// Animate updating the view's layout by calling layoutIfNeeded inside a UIView animation block.
let animationOptions: UIViewAnimationOptions = [animationCurve, .beginFromCurrentState]
UIView.animate(withDuration: animationDuration, delay: 0, options: animationOptions, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
// Scroll to the selected text once the keyboard frame changes.
let selectedRange = textView.selectedRange
textView.scrollRangeToVisible(selectedRange)
}
// MARK: - Configuration
func configureTextView() {
let bodyFontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.body)
let bodyFont = UIFont(descriptor: bodyFontDescriptor, size: 0)
textView.font = bodyFont
textView.textColor = UIColor.black
textView.backgroundColor = UIColor.white
textView.isScrollEnabled = true
/*
Let's modify some of the attributes of the attributed string.
You can modify these attributes yourself to get a better feel for what they do.
Note that the initial text is visible in the storyboard.
*/
let attributedText = NSMutableAttributedString(attributedString: textView.attributedText!)
/*
Use NSString so the result of rangeOfString is an NSRange, not Range<String.Index>.
This will then be the correct type to then pass to the addAttribute method of
NSMutableAttributedString.
*/
let text = textView.text! as NSString
// Find the range of each element to modify.
let boldRange = text.range(of: NSLocalizedString("bold", comment: ""))
let highlightedRange = text.range(of: NSLocalizedString("highlighted", comment: ""))
let underlinedRange = text.range(of: NSLocalizedString("underlined", comment: ""))
let tintedRange = text.range(of: NSLocalizedString("tinted", comment: ""))
/*
Add bold. Take the current font descriptor and create a new font descriptor
with an additional bold trait.
*/
let boldFontDescriptor = textView.font!.fontDescriptor.withSymbolicTraits(.traitBold)
let boldFont = UIFont(descriptor: boldFontDescriptor!, size: 0)
attributedText.addAttribute(NSFontAttributeName, value: boldFont, range: boldRange)
// Add highlight.
attributedText.addAttribute(NSBackgroundColorAttributeName, value: UIColor.applicationGreenColor, range: highlightedRange)
// Add underline.
attributedText.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: underlinedRange)
// Add tint.
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.applicationBlueColor, range: tintedRange)
// Add image attachment.
let textAttachment = NSTextAttachment()
let image = UIImage(named: "text_view_attachment")!
textAttachment.image = image
textAttachment.bounds = CGRect(origin: CGPoint.zero, size: image.size)
let textAttachmentString = NSAttributedString(attachment: textAttachment)
attributedText.append(textAttachmentString)
// Append a space with matching font of the rest of the body text.
let appendedSpace = NSMutableAttributedString.init(string: " ")
appendedSpace.addAttribute(NSFontAttributeName, value: bodyFont, range: NSMakeRange(0, 1))
attributedText.append(appendedSpace)
textView.attributedText = attributedText
}
// MARK: - UITextViewDelegate
func textViewDidBeginEditing(_ textView: UITextView) {
/*
Provide a "Done" button for the user to select to signify completion
with writing text in the text view.
*/
let doneBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(TextViewController.doneBarButtonItemClicked))
navigationItem.setRightBarButton(doneBarButtonItem, animated: true)
}
// MARK: - Actions
func doneBarButtonItemClicked() {
// Dismiss the keyboard by removing it as the first responder.
textView.resignFirstResponder()
navigationItem.setRightBarButton(nil, animated: true)
}
}
| mit |
pentateu/SpeedTracker | SpeedTracker/RunViewController.swift | 1 | 3478 | //
// ViewController.swift
// SpeedTracker
//
// Created by Rafael Almeida on 23/07/15.
// Copyright (c) 2015 ISWE. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class RunViewController: UIViewController, MovementTrackerDelegate, MKMapViewDelegate {
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var maxSpeedLabel: UILabel!
@IBOutlet weak var avgSpeedLabel: UILabel!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var statusLabel: UILabel!
let tracker = MovementTracker()
override func viewDidLoad() {
super.viewDidLoad()
setupMapView();
tracker.delegate = self
if(CLLocationManager.locationServicesEnabled()){
statusLabel.text = "starting ..."
tracker.start()
}
else{
statusLabel.text = "Location services disabled ;-("
}
}
func setupMapView(){
self.mapView.delegate = self
}
func updateSpeedDisplay(tracker:MovementTracker, locationInfo:LocationInfo){
maxSpeedLabel.text = "\(tracker.maxSpeed) km/h"
avgSpeedLabel.text = "\(tracker.averageSpeed) km/h"
speedLabel.text = "\(locationInfo.speed) km/h"
}
func calculateMapRegion(latitudeRange:MinMax, longitudeRange:MinMax) -> MKCoordinateRegion {
let lat = (latitudeRange.min + latitudeRange.max) / 2
let lng = (longitudeRange.min + longitudeRange.max) / 2
let center = CLLocationCoordinate2DMake(lat, lng)
let latitudeDelta = (latitudeRange.max - latitudeRange.min) * 1.1 // 10% padding
let longitudeDelta = (longitudeRange.max - longitudeRange.min) * 1.1 // 10% padding
let span = MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta)
let region = MKCoordinateRegionMake(center, span)
return region
}
func createPolyline() -> MKPolyline {
var coordinates = [
tracker.locations[tracker.locations.count - 2].location.coordinate,
tracker.locations[tracker.locations.count - 1].location.coordinate
]
return MKPolyline(coordinates: &coordinates , count: 2)
}
func updateMapDisplay(tracker:MovementTracker, locationInfo:LocationInfo){
let mapRegion = calculateMapRegion(tracker.latitudeRange, longitudeRange: tracker.longitudeRange)
self.mapView.region = mapRegion
if tracker.locations.count > 1 {
self.mapView.addOverlay(createPolyline())
}
}
//MovementTrackerDelegate
func locationAdded(tracker:MovementTracker, locationInfo:LocationInfo){
updateSpeedDisplay(tracker, locationInfo: locationInfo)
updateMapDisplay(tracker, locationInfo: locationInfo)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Map Delegate
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if let polyLine = overlay as? MKPolyline {
let renderer = MKPolylineRenderer(polyline: polyLine)
renderer.strokeColor = UIColor.blackColor()
renderer.lineWidth = 3
return renderer
}
return nil
}
}
| mit |
chenzhe555/core-ios-swift | core-ios-swift/Source/MCHttpEncryption_s.swift | 1 | 350 | //
// MCHttpEncryption_s.swift
// core-ios-swift
//
// Created by ้ๅฒ#376811578@qq.com on 16/2/25.
// Copyright ยฉ 2016ๅนด ้ๅฒๆฏไธชๅฅฝๅญฉๅญ. All rights reserved.
//
import UIKit
class MCHttpEncryption_s: BaseHttpEncryption_s {
override class func setParametersArray() throws -> NSArray{
return ["111","2222","333"];
}
}
| mit |
dduan/swift | validation-test/compiler_crashers_fixed/27015-swift-typechecker-validatedecl.swift | 11 | 469 | // 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
class B<T where g:f{var d{class A{class a{class a{enum b<b{class A{var f:T.h
| apache-2.0 |
indragiek/INDLinkLabel | INDLinkLabel.swift | 1 | 10646 | //
// INDLinkLabel.swift
// INDLinkLabel
//
// Created by Indragie on 12/31/14.
// Copyright (c) 2014 Indragie Karunaratne. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
@objc public protocol INDLinkLabelDelegate {
/// Called when a link is tapped.
@objc optional func linkLabel(_ label: INDLinkLabel, didTapLinkWithURL URL: URL)
/// Called when a link is long pressed.
@objc optional func linkLabel(_ label: INDLinkLabel, didLongPressLinkWithURL URL: URL)
/// Called when parsing links from attributed text.
/// The delegate may determine whether to use the text's original attributes,
/// use the proposed INDLinkLabel attributes (blue text color, and underlined),
/// or supply a completely custom set of attributes for the given link.
@objc optional func linkLabel(_ label: INDLinkLabel, attributesForURL URL: URL, originalAttributes: [String: AnyObject], proposedAttributes: [String: AnyObject]) -> [String: AnyObject]
}
/// A simple UILabel subclass that allows for tapping and long pressing on links
/// (i.e. anything marked with `NSLinkAttributeName`)
@IBDesignable open class INDLinkLabel: UILabel {
@IBOutlet open weak var delegate: INDLinkLabelDelegate?
// MARK: Styling
override open var attributedText: NSAttributedString? {
didSet { processLinks() }
}
override open var lineBreakMode: NSLineBreakMode {
didSet { textContainer.lineBreakMode = lineBreakMode }
}
/// The color of the highlight that appears over a link when tapping on it
@IBInspectable open var linkHighlightColor: UIColor = UIColor(white: 0, alpha: 0.2)
/// The corner radius of the highlight that appears over a link when
/// tapping on it
@IBInspectable open var linkHighlightCornerRadius: CGFloat = 2
// MARK: Text Layout
override open var numberOfLines: Int {
didSet {
textContainer.maximumNumberOfLines = numberOfLines
}
}
override open var adjustsFontSizeToFitWidth: Bool {
didSet {
if adjustsFontSizeToFitWidth {
fatalError("INDLinkLabel does not support the adjustsFontSizeToFitWidth property")
}
}
}
// MARK: Private
fileprivate var layoutManager = NSLayoutManager()
fileprivate var textStorage = NSTextStorage()
fileprivate var textContainer = NSTextContainer()
fileprivate struct LinkRange {
let URL: Foundation.URL
let glyphRange: NSRange
}
fileprivate var linkRanges: [LinkRange]?
fileprivate var tappedLinkRange: LinkRange? {
didSet {
setNeedsDisplay()
}
}
// MARK: Initialization
fileprivate func commonInit() {
precondition(!adjustsFontSizeToFitWidth, "INDLinkLabel does not support the adjustsFontSizeToFitWidth property")
textContainer.maximumNumberOfLines = numberOfLines
textContainer.lineBreakMode = lineBreakMode
textContainer.lineFragmentPadding = 0
layoutManager = NSLayoutManager()
layoutManager.addTextContainer(textContainer)
textStorage = NSTextStorage()
textStorage.addLayoutManager(layoutManager)
isUserInteractionEnabled = true
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(INDLinkLabel.handleTap(_:))))
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(INDLinkLabel.handleLongPress(_:))))
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// MARK: Attributes
fileprivate struct DefaultLinkAttributes {
static let Color = UIColor.blue
static let UnderlineStyle = NSUnderlineStyle.styleSingle
}
fileprivate func processLinks() {
var ranges = [LinkRange]()
if let attributedText = attributedText {
textStorage.setAttributedString(attributedText)
textStorage.enumerateAttribute(NSLinkAttributeName, in: NSRange(location: 0, length: textStorage.length), options: []) { (value, range, _) in
// Because NSLinkAttributeName supports both NSURL and NSString
// values. *sigh*
let URL: Foundation.URL? = {
if let string = value as? String {
return Foundation.URL(string: string)
} else {
return value as? Foundation.URL
}
}()
if let URL = URL {
let glyphRange = self.layoutManager.glyphRange(forCharacterRange: range, actualCharacterRange: nil)
ranges.append(LinkRange(URL: URL, glyphRange: glyphRange))
// Remove `NSLinkAttributeName` to prevent `UILabel` from applying
// the default styling.
self.textStorage.removeAttribute(NSLinkAttributeName, range: range)
let originalAttributes = self.textStorage.attributes(at: range.location, effectiveRange: nil)
var proposedAttributes = originalAttributes
if originalAttributes[NSForegroundColorAttributeName] == nil {
proposedAttributes[NSForegroundColorAttributeName] = DefaultLinkAttributes.Color
}
if originalAttributes[NSUnderlineStyleAttributeName] == nil {
proposedAttributes[NSUnderlineStyleAttributeName] = DefaultLinkAttributes.UnderlineStyle.rawValue
}
let acceptedAttributes = self.delegate?.linkLabel?(self, attributesForURL: URL, originalAttributes: originalAttributes as [String : AnyObject], proposedAttributes: proposedAttributes as [String : AnyObject])
?? proposedAttributes;
self.textStorage.setAttributes(acceptedAttributes, range: range)
}
}
}
linkRanges = ranges
super.attributedText = textStorage
}
// MARK: Drawing
open override func draw(_ rect: CGRect) {
super.draw(rect)
if let linkRange = tappedLinkRange {
linkHighlightColor.setFill()
for rect in highlightRectsForGlyphRange(linkRange.glyphRange) {
let path = UIBezierPath(roundedRect: rect, cornerRadius: linkHighlightCornerRadius)
path.fill()
}
}
}
fileprivate func highlightRectsForGlyphRange(_ range: NSRange) -> [CGRect] {
var rects = [CGRect]()
layoutManager.enumerateLineFragments(forGlyphRange: range) { (_, rect, _, effectiveRange, _) in
let boundingRect = self.layoutManager.boundingRect(forGlyphRange: NSIntersectionRange(range, effectiveRange), in: self.textContainer)
rects.append(boundingRect)
}
return rects
}
// MARK: Touches
fileprivate func linkRangeAtPoint(_ point: CGPoint) -> LinkRange? {
if let linkRanges = linkRanges {
// Passing in the UILabel's fitting size here doesn't work, the height
// needs to be unrestricted for it to correctly lay out all the text.
// Might be due to a difference in the computed text sizes of `UILabel`
// and `NSLayoutManager`.
textContainer.size = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
layoutManager.ensureLayout(for: textContainer)
let boundingRect = layoutManager.boundingRect(forGlyphRange: layoutManager.glyphRange(for: textContainer), in: textContainer)
if boundingRect.contains(point) {
let glyphIndex = layoutManager.glyphIndex(for: point, in: textContainer)
for linkRange in linkRanges {
if NSLocationInRange(glyphIndex, linkRange.glyphRange) {
return linkRange
}
}
}
}
return nil
}
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
// Any taps that don't hit a link are ignored and passed to the next
// responder.
return linkRangeAtPoint(point) != nil
}
@objc fileprivate func handleTap(_ gestureRecognizer: UIGestureRecognizer) {
switch gestureRecognizer.state {
case .ended:
tappedLinkRange = linkRangeAtPoint(gestureRecognizer.location(ofTouch: 0, in: self))
default:
tappedLinkRange = nil
}
if let linkRange = tappedLinkRange {
delegate?.linkLabel?(self, didTapLinkWithURL: linkRange.URL)
tappedLinkRange = nil
}
}
@objc fileprivate func handleLongPress(_ gestureRecognizer: UIGestureRecognizer) {
switch gestureRecognizer.state {
case .began:
tappedLinkRange = linkRangeAtPoint(gestureRecognizer.location(ofTouch: 0, in: self))
default:
tappedLinkRange = nil
}
if let linkRange = tappedLinkRange {
delegate?.linkLabel?(self, didLongPressLinkWithURL: linkRange.URL)
}
}
}
| mit |
jessesquires/JSQCoreDataKit | Tests/ResetStackTests.swift | 1 | 3912 | //
// Created by Jesse Squires
// https://www.jessesquires.com
//
//
// Documentation
// https://jessesquires.github.io/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright ยฉ 2015-present Jesse Squires
// Released under an MIT license: https://opensource.org/licenses/MIT
//
import CoreData
import ExampleModel
@testable import JSQCoreDataKit
import XCTest
// swiftlint:disable force_try
final class ResetStackTests: TestCase {
func test_ThatMainContext_WithChanges_DoesNotHaveObjects_AfterReset() {
// GIVEN: a stack and context with changes
let context = self.inMemoryStack.mainContext
context.performAndWait {
self.generateCompaniesInContext(context, count: 3)
}
let expectation = self.expectation(description: #function)
// WHEN: we attempt to reset the stack
self.inMemoryStack.reset { result in
if case .failure(let error) = result {
XCTFail("Error while resetting the stack: \(error)")
}
expectation.fulfill()
}
// THEN: the reset succeeds and the contexts contain no objects
self.waitForExpectations(timeout: defaultTimeout) { error -> Void in
XCTAssertNil(error, "Expectation should not error")
}
XCTAssertEqual(self.inMemoryStack.mainContext.registeredObjects.count, 0)
XCTAssertEqual(self.inMemoryStack.backgroundContext.registeredObjects.count, 0)
}
func test_ThatBackgroundContext_WithChanges_DoesNotHaveObjects_AfterReset() {
// GIVEN: a stack and context with changes
let context = self.inMemoryStack.backgroundContext
context.performAndWait {
self.generateCompaniesInContext(context, count: 3)
}
let expectation = self.expectation(description: #function)
// WHEN: we attempt to reset the stack
self.inMemoryStack.reset { result in
if case .failure(let error) = result {
XCTFail("Error while resetting the stack: \(error)")
}
expectation.fulfill()
}
// THEN: the reset succeeds and the contexts contain no objects
self.waitForExpectations(timeout: defaultTimeout) { error -> Void in
XCTAssertNil(error, "Expectation should not error")
}
XCTAssertEqual(self.inMemoryStack.mainContext.registeredObjects.count, 0)
XCTAssertEqual(self.inMemoryStack.backgroundContext.registeredObjects.count, 0)
}
func test_ThatPersistentStore_WithChanges_DoesNotHaveObjects_AfterReset() {
// GIVEN: a stack and persistent store with data
let model = CoreDataModel(name: modelName, bundle: modelBundle)
let factory = CoreDataStackProvider(model: model)
let stack = try! factory.createStack().get()
let context = stack.mainContext
context.performAndWait {
self.generateCompaniesInContext(context, count: 3)
}
context.saveSync()
let request = Company.fetchRequest
let objectsBefore = try? context.count(for: request)
XCTAssertEqual(objectsBefore, 3)
let expectation = self.expectation(description: #function)
// WHEN: we attempt to reset the stack
stack.reset { result in
if case .failure(let error) = result {
XCTFail("Error while resetting the stack: \(error)")
}
expectation.fulfill()
}
// THEN: the reset succeeds and the stack contains no managed objects
self.waitForExpectations(timeout: defaultTimeout) { error -> Void in
XCTAssertNil(error, "Expectation should not error")
}
let objectsAfter = try? stack.mainContext.count(for: request)
XCTAssertEqual(objectsAfter, 0)
}
}
// swiftlint:enable force_try
| mit |
gaowanli/PinGo | PinGo/PinGo/Home/LeftRefreshView.swift | 1 | 4363 | //
// LeftRefreshView.swift
// PinGo
//
// Created by GaoWanli on 16/1/31.
// Copyright ยฉ 2016ๅนด GWL. All rights reserved.
//
import UIKit
enum LeftRefreshViewState {
case `default`, pulling, refreshing
}
private let kLeftRefreshViewWidth: CGFloat = 65.0
class LeftRefreshView: UIControl {
fileprivate var scrollView: UIScrollView?
fileprivate var beforeState: LeftRefreshViewState = .default
fileprivate var refreshState: LeftRefreshViewState = .default {
didSet {
switch refreshState {
case .default:
imageView.shouldAnimating = false
if beforeState == .refreshing {
UIView.animate(withDuration: 0.25, animations: { () in
var contentInset = self.scrollView!.contentInset
contentInset.left -= kLeftRefreshViewWidth
self.scrollView?.contentInset = contentInset
debugPrint("\(type(of: self)) \(#function) \(#line)")
})
}
case .pulling:
imageView.shouldAnimating = true
debugPrint("\(type(of: self)) \(#function) \(#line)")
case .refreshing:
UIView.animate(withDuration: 0.25, animations: { () in
var contentInset = self.scrollView!.contentInset
contentInset.left += kLeftRefreshViewWidth
self.scrollView?.contentInset = contentInset
debugPrint("\(type(of: self)) \(#function) \(#line)")
})
// ่ฐ็จๅทๆฐ็ๆนๆณ
sendActions(for: .valueChanged)
}
beforeState = refreshState
}
}
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
if let s = newSuperview, s.isKind(of: UIScrollView.self) {
s.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
scrollView = s as? UIScrollView
frame = CGRect(x: -kLeftRefreshViewWidth, y: 0, width: kLeftRefreshViewWidth, height: s.bounds.height)
addSubview(imageView)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let leftInset = scrollView!.contentInset.left
let offsetX = scrollView!.contentOffset.x
let criticalValue = -leftInset - bounds.width
// ๆๅจ
if scrollView!.isDragging {
if refreshState == .default && offsetX < criticalValue {
// ๅฎๅ
จๆพ็คบๅบๆฅ
refreshState = .pulling
}else if refreshState == .pulling && offsetX >= criticalValue {
// ๆฒกๆๅฎๅ
จๆพ็คบๅบๆฅ/ๆฒกๆๆพ็คบๅบๆฅ
refreshState = .default
}
}else {
// ็ปๆๆๅจ
if refreshState == .pulling {
refreshState = .refreshing
}
}
}
func endRefresh() {
refreshState = .default
}
deinit {
if let s = scrollView {
s.removeObserver(self, forKeyPath: "contentOffset")
}
}
// MARK: lazy loading
fileprivate lazy var imageView: LeftImageView = {
let y = (self.bounds.height - kLeftRefreshViewWidth) * 0.5 - self.scrollView!.contentInset.top - kTabBarHeight
let i = LeftImageView(frame: CGRect(x: 0, y: y, width: kLeftRefreshViewWidth, height: kLeftRefreshViewWidth))
i.image = UIImage(named: "loading0")
i.contentMode = .center
return i
}()
}
private class LeftImageView: UIImageView {
var shouldAnimating: Bool = false {
didSet {
if shouldAnimating {
if !isAnimating {
var images = [UIImage]()
for i in 0..<3 {
images.append(UIImage(named: "loading\(i)")!)
}
self.animationImages = images
self.animationDuration = 1.0
startAnimating()
}
}else {
stopAnimating()
}
}
}
}
| mit |
mownier/photostream | Photostream/UI/Shared/PostListCollectionHeader/PostListCollectionHeaderItem.swift | 1 | 1852 | //
// PostListCollectionHeaderItem.swift
// Photostream
//
// Created by Mounir Ybanez on 08/12/2016.
// Copyright ยฉ 2016 Mounir Ybanez. All rights reserved.
//
import Kingfisher
protocol PostListCollectionHeaderItem {
var avatarUrl: String { get }
var displayName: String { get }
}
protocol PostListCollectionHeaderConfig {
func configure(with item: PostListCollectionHeaderItem?, isPrototype: Bool)
func set(avatar url: String, placeholder image: UIImage?)
}
extension PostListCollectionHeader: PostListCollectionHeaderConfig {
func configure(with item: PostListCollectionHeaderItem?, isPrototype: Bool = false) {
guard item != nil else {
return
}
if !isPrototype {
let image = createAvatarPlaceholderImage(with: item!.displayName[0])
set(avatar: item!.avatarUrl, placeholder: image)
}
displayNameLabel.text = item!.displayName
}
func set(avatar url: String, placeholder image: UIImage? = nil) {
guard let downloadUrl = URL(string: url) else {
avatarImageView.image = image
return
}
let resource = ImageResource(downloadURL: downloadUrl)
avatarImageView.kf.setImage(with: resource, placeholder: image, options: nil, progressBlock: nil, completionHandler: nil)
}
private func createAvatarPlaceholderImage(with initial: String) -> UIImage {
let width: CGFloat = avatarDimension
let height: CGFloat = avatarDimension
let frame = CGRect(x: 0, y: 0, width: width, height: height)
let font = UIFont.systemFont(ofSize: 12)
let text: String = initial
let placeholderImage = UILabel.createPlaceholderImageWithFrame(frame, text: text, font: font)
return placeholderImage
}
}
| mit |
yuyedaidao/YQTabBarController | YQTabBarControllerTests/YQTabBarControllerTests.swift | 1 | 922 | //
// YQTabBarControllerTests.swift
// YQTabBarControllerTests
//
// Created by Wang on 14-9-23.
// Copyright (c) 2014ๅนด Wang. All rights reserved.
//
import UIKit
import XCTest
class YQTabBarControllerTests: 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.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
PerfectlySoft/Perfect-Authentication | Sources/OAuth2/OAuth2.swift | 1 | 4942 | //
// OAuth2.swift
// Based on Turnstile's oAuth2
//
// Created by Edward Jiang on 8/7/16.
//
// Modified by Jonathan Guthrie 18 Jan 2017
// Intended to work more independantly of Turnstile
import Foundation
import PerfectHTTP
/**
OAuth 2 represents the base API Client for an OAuth 2 server that implements the
authorization code grant type. This is the typical redirect based login flow.
Since OAuth doesn't define token validation, implementing it is up to a subclass.
*/
open class OAuth2 {
/// The Client ID for the OAuth 2 Server
public let clientID: String
/// The Client Secret for the OAuth 2 Server
public let clientSecret: String
/// The Authorization Endpoint of the OAuth 2 Server
public let authorizationURL: String
/// The Token Endpoint of the OAuth 2 Server
public let tokenURL: String
/// Creates the OAuth 2 client
public init(clientID: String, clientSecret: String, authorizationURL: String, tokenURL: String) {
self.clientID = clientID
self.clientSecret = clientSecret
self.authorizationURL = authorizationURL
self.tokenURL = tokenURL
}
/// Gets the login link for the OAuth 2 server. Redirect the end user to this URL
///
/// - parameter redirectURL: The URL for the server to redirect the user back to after login.
/// You will need to configure this in the admin console for the OAuth provider's site.
/// - parameter state: A randomly generated string to prevent CSRF attacks.
/// Verify this when validating the Authorization Code
/// - parameter scopes: A list of OAuth scopes you'd like the user to grant
open func getLoginLink(redirectURL: String, state: String, scopes: [String] = []) -> String {
var url = "\(authorizationURL)?response_type=code"
url += "&client_id=\(clientID.stringByEncodingURL)"
url += "&redirect_uri=\(redirectURL.stringByEncodingURL)"
url += "&state=\(state.stringByEncodingURL)"
url += "&scope=\((scopes.joined(separator: " ")).stringByEncodingURL)"
return url
}
/// Exchanges an authorization code for an access token
/// - throws: InvalidAuthorizationCodeError() if the Authorization Code could not be validated
/// - throws: APIConnectionError() if we cannot connect to the OAuth server
/// - throws: InvalidAPIResponse() if the server does not respond in a way we expect
open func exchange(authorizationCode: AuthorizationCode) throws -> OAuth2Token {
let postBody = ["grant_type": "authorization_code",
"client_id": clientID,
"client_secret": clientSecret,
"redirect_uri": authorizationCode.redirectURL,
"code": authorizationCode.code]
// let (_, data, _, _) = makeRequest(.post, tokenURL, body: urlencode(dict: postBody), encoding: "form")
let data = makeRequest(.post, tokenURL, body: urlencode(dict: postBody), encoding: "form")
guard let token = OAuth2Token(json: data) else {
if let error = OAuth2Error(json: data) {
throw error
} else {
throw InvalidAPIResponse()
}
}
return token
}
/// Parses a URL and exchanges the OAuth 2 access token and exchanges it for an access token
/// - throws: InvalidAuthorizationCodeError() if the Authorization Code could not be validated
/// - throws: APIConnectionError() if we cannot connect to the OAuth server
/// - throws: InvalidAPIResponse() if the server does not respond in a way we expect
/// - throws: OAuth2Error() if the oauth server calls back with an error
open func exchange(request: HTTPRequest, state: String, redirectURL: String) throws -> OAuth2Token {
//request.param(name: "state") == state
guard let code = request.param(name: "code")
else {
print("Where's the code?")
throw InvalidAPIResponse()
}
return try exchange(authorizationCode: AuthorizationCode(code: code, redirectURL: redirectURL))
}
// TODO: add refresh token support
}
extension URLComponents {
var queryDictionary: [String: String] {
var result = [String: String]()
guard let components = query?.components(separatedBy: "&") else {
return result
}
components.forEach { component in
let queryPair = component.components(separatedBy: "=")
if queryPair.count == 2 {
result[queryPair[0]] = queryPair[1]
} else {
result[queryPair[0]] = ""
}
}
return result
}
}
extension URLComponents {
mutating func setQueryItems(dict: [String: String]) {
query = dict.map { (key, value) in
return key + "=" + value
}.joined(separator: "&")
}
}
| apache-2.0 |
baiIey/prototyping-and-navigation | Dropbox/DropboxTests/DropboxTests.swift | 1 | 902 | //
// DropboxTests.swift
// DropboxTests
//
// Created by Brian Bailey on 2/3/15.
// Copyright (c) 2015 Nevver Design. All rights reserved.
//
import UIKit
import XCTest
class DropboxTests: 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.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
jackmc-xx/firefox-ios | Client/Frontend/Login/PasswordTextField.swift | 3 | 1561 | // 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
private let ImagePathReveal = "visible-text.png"
class PasswordTextField: ImageTextField {
required override init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
didInitView()
}
override init(frame: CGRect) {
super.init(frame: frame)
didInitView()
}
override init() {
// init() calls init(frame) with a 0 rect.
super.init()
}
private func didInitView() {
let image = UIImage(named: ImagePathReveal)!
// TODO: We should resize the raw image instead of programmatically scaling it.
let scale: CGFloat = 0.7
let button = UIButton(frame: CGRectMake(0, 0, image.size.width * scale, image.size.height * scale))
button.setImage(image, forState: UIControlState.Normal)
let padding: CGFloat = 10
let paddingView = UIView(frame: CGRectMake(0, 0, button.bounds.width + padding, button.bounds.height))
button.center = paddingView.center
paddingView.addSubview(button)
rightView = paddingView
rightViewMode = UITextFieldViewMode.Always
button.addTarget(self, action: "didClickPasswordReveal", forControlEvents: UIControlEvents.TouchUpInside)
}
// Referenced as button selector.
func didClickPasswordReveal() {
secureTextEntry = !secureTextEntry
}
}
| mpl-2.0 |
wjk930726/weibo | weiBo/weiBo/iPhone/Modules/Home/Model/WBUser.swift | 1 | 337 | //
// WBUser.swift
// weiBo
//
// Created by ็้ๅฏ on 2016/11/29.
// Copyright ยฉ 2016ๅนด ็้ๅฏ. All rights reserved.
//
import UIKit
import HandyJSON
struct WBUser: HandyJSON {
var id: String?
var screen_name: String?
var verified_type: Int = -1
var avatar_large: String?
var verified_level: Int = 0
}
| mit |
byss/KBAPISupport | KBAPISupport/Core/Internal/UTIdentifier.swift | 1 | 4985 | //
// UTIdentifier.swift
// Copyright ยฉ 2018 Kirill byss Bystrov. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
#if os (iOS) || os (tvOS) || os (watchOS)
import MobileCoreServices
#elseif os (macOS)
import CoreServices
#else
#error ("Unsupported platform")
#endif
internal struct UTIdentifier {
private let rawValue: CFString;
}
internal extension UTIdentifier {
internal static let data = UTIdentifier (rawValue: kUTTypeData);
private static let isDeclared = UTTypeIsDeclared;
private static let isDynamic = UTTypeIsDynamic;
internal var value: String {
return self.rawValue as String;
}
internal var isDeclared: Bool {
return UTIdentifier.isDeclared (self.rawValue);
}
internal var isDynamic: Bool {
return UTIdentifier.isDynamic (self.rawValue);
}
internal var declaration: [String: Any]? {
guard let rawDeclaration = UTTypeCopyDeclaration (self.rawValue) else {
return nil;
}
return rawDeclaration.takeUnretainedValue () as NSDictionary as? [String: Any];
}
internal var bundleURL: URL? {
return UTTypeCopyDeclaringBundleURL (self.rawValue)?.takeUnretainedValue () as URL?;
}
internal static func preferred (forTag tag: Tag, withValue tagValue: String, conformingTo otherIdentifier: UTIdentifier?) -> UTIdentifier? {
return (UTTypeCreatePreferredIdentifierForTag (tag.rawValue, tagValue as CFString, otherIdentifier?.rawValue)?.takeUnretainedValue ()).map (UTIdentifier.init);
}
internal static func allIdentifiers (forTag tag: Tag, withValue tagValue: String, conformingTo otherIdentifier: UTIdentifier?) -> [UTIdentifier]? {
guard let rawIdentifiers = UTTypeCreateAllIdentifiersForTag (tag.rawValue, tagValue as CFString, otherIdentifier?.rawValue) else {
return nil;
}
return CFArrayWrapper (rawIdentifiers.takeUnretainedValue ()).map (UTIdentifier.init);
}
internal static func isDeclared (_ identifierValue: String) -> Bool {
return self.isDeclared (identifierValue as CFString);
}
internal static func isDynamic (_ identifierValue: String) -> Bool {
return self.isDynamic (identifierValue as CFString);
}
internal init? (string: String) {
guard !string.isEmpty else {
return nil;
}
self.init (rawValue: string as CFString);
}
internal func conforms (to identifier: UTIdentifier) -> Bool {
return UTTypeConformsTo (self.rawValue, identifier.rawValue);
}
internal func preferredValue (ofTag tag: Tag) -> String? {
return UTTypeCopyPreferredTagWithClass (self.rawValue, tag.rawValue)?.takeUnretainedValue () as String?;
}
internal func allValues (ofTag tag: Tag) -> [String]? {
return (UTTypeCopyAllTagsWithClass (self.rawValue, tag.rawValue)?.takeUnretainedValue ()).map (CFArrayWrapper <CFString>.init)?.map { $0 as String };
}
}
internal extension UTIdentifier {
internal enum Tag {
case mimeType;
case filenameExtension;
fileprivate var rawValue: CFString {
switch (self) {
case .mimeType:
return kUTTagClassMIMEType;
case .filenameExtension:
return kUTTagClassFilenameExtension;
}
}
}
}
extension UTIdentifier: Equatable {
internal static func == (lhs: UTIdentifier, rhs: UTIdentifier) -> Bool {
return UTTypeEqual (lhs.rawValue, rhs.rawValue);
}
}
extension UTIdentifier: CustomStringConvertible {
internal var description: String {
return (UTTypeCopyDescription (self.rawValue)?.takeUnretainedValue () ?? self.rawValue) as String;
}
}
private struct CFArrayWrapper <Element> {
private let wrapped: CFArray;
fileprivate init (_ array: CFArray) {
self.wrapped = array;
}
}
extension CFArrayWrapper: RandomAccessCollection {
fileprivate var startIndex: CFIndex {
return 0;
}
fileprivate var endIndex: CFIndex {
return CFArrayGetCount (self.wrapped);
}
fileprivate subscript (index: CFIndex) -> Element {
return CFArrayGetValueAtIndex (self.wrapped, index)!.assumingMemoryBound (to: Element.self).pointee;
}
}
| mit |
Constructor-io/constructorio-client-swift | UserApplication/Screens/Cart/ViewModel/Quantity.swift | 1 | 254 | //
// Quantity.swift
// UserApplication
//
// Copyright ยฉ Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
struct Quantity{
var value: Int
var string: String{
return "QTY. \(self.value)"
}
}
| mit |
dfelber/SwiftStringScore | SwiftStringScore/SwiftStringScore.playground/Contents.swift | 1 | 2087 | //
// String+Score.playground
//
// Created by Dominik Felber on 07.04.2016.
// Copyright (c) 2016 Dominik Felber. All rights reserved.
//
// If you have problems importing 'SwiftStringScore' please ensure that you:
// * are using the workspace
// * built the framework target 'SwiftStringScore-iOS' once
@testable import SwiftStringScore
"hello world".scoreAgainst("axl") // => 0
"hello world".scoreAgainst("ow") // => 0.3545455
// Single letter match
"hello world".scoreAgainst("e") // => 0.1090909
// Single letter match plus bonuses for beginning of word and beginning of phrase
"hello world".scoreAgainst("h") // => 0.5863637
"hello world".scoreAgainst("w") // => 0.5454546
"hello world".scoreAgainst("he") // => 0.6227273
"hello world".scoreAgainst("hel") // => 0.6590909
"hello world".scoreAgainst("hell") // => 0.6954546
"hello world".scoreAgainst("hello") // => 0.7318182
"hello world".scoreAgainst("hello ") // => 0.7681818
"hello world".scoreAgainst("hello w") // => 0.8045455
"hello world".scoreAgainst("hello wo") // => 0.8409091
"hello world".scoreAgainst("hello wor") // => 0.8772728
"hello world".scoreAgainst("hello worl") // => 0.9136364
"hello world".scoreAgainst("hello world") // => 1.0
// Using a "1" in place of an "l" is a mismatch unless the score is fuzzy
"hello world".scoreAgainst("hello wor1") // => 0
"hello world".scoreAgainst("hello wor1", fuzziness: 0.5) // => 0.6145455 (fuzzy)
// Finding a match in a shorter string is more significant.
"Hello".scoreAgainst("h") // => 0.5700001
"He".scoreAgainst("h") // => 0.6750001
// Same case matches better than wrong case
"Hello".scoreAgainst("h") // => 0.5700001
"Hello".scoreAgainst("H") // => 0.63
// Acronyms are given a little more weight
"Hillsdale Michigan".scoreAgainst("HiMi") > "Hillsdale Michigan".scoreAgainst("Hills")
"Hillsdale Michigan".scoreAgainst("HiMi") < "Hillsdale Michigan".scoreAgainst("Hillsd")
// Unicode supported
"๐ฑ".scoreAgainst("๐ฑ") // => 1
"๐ฑ".scoreAgainst("๐ผ") // => 0
"๐ฑ๐".scoreAgainst("๐") // => 0.15
"๐ฑ๐".scoreAgainst("๐ฑ") // => 0.75
| mit |
firebase/quickstart-ios | firestore/FirestoreSwiftUIExample/Views/RestaurantItemView.swift | 1 | 2001 | //
// RestaurantView.swift
// FirestoreSwiftUIExample
//
// Copyright (c) 2021 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
struct RestaurantItemView: View {
var restaurant: Restaurant
var body: some View {
NavigationLink(destination: RestaurantDetailView(restaurant: restaurant)) {
HStack {
RestaurantImageView(imageURL: restaurant.photo, isThumbnail: true)
VStack(alignment: .leading) {
HStack {
Text(restaurant.name)
.frame(alignment: .leading)
Spacer()
PriceView(price: restaurant.price, color: Color.gray)
}
StarsView(
rating: Int(restaurant.averageRating.rounded()),
color: Color.yellow,
outlineColor: Color.gray
)
Spacer()
HStack {
Text(restaurant.category)
Text("โข")
Text(restaurant.city)
}
.foregroundColor(Color.gray)
.font(.footnote)
}
}
.padding([.bottom, .trailing])
}
}
}
struct RestaurantItemView_Previews: PreviewProvider {
static var previews: some View {
let restaurant = Restaurant(name: "Pizza Place", category: "Pizza", city: "Austin", price: 2,
ratingCount: 1, averageRating: 4,
photo: Restaurant.imageURL(forName: "Pizza Place"))
RestaurantItemView(restaurant: restaurant)
}
}
| apache-2.0 |
gregomni/swift | test/Interop/SwiftToCxx/functions/swift-primitive-functions-cxx-bridging.swift | 3 | 9686 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -typecheck -module-name Functions -clang-header-expose-public-decls -emit-clang-header-path %t/functions.h
// RUN: %FileCheck %s < %t/functions.h
// RUN: %check-interop-cxx-header-in-clang(%t/functions.h)
// CHECK: inline float passThrougCFloat(float x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions16passThrougCFloatyS2fF(x);
// CHECK-NEXT: }
// CHECK: inline bool passThroughBool(bool x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions15passThroughBoolyS2bF(x);
// CHECK-NEXT: }
// CHECK: inline bool passThroughCBool(bool x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions16passThroughCBoolyS2bF(x);
// CHECK-NEXT: }
// CHECK: inline char passThroughCChar(char x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions16passThroughCCharys4Int8VADF(x);
// CHECK-NEXT: }
// CHECK: inline char16_t passThroughCChar16(char16_t x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions18passThroughCChar16ys6UInt16VADF(x);
// CHECK-NEXT: }
// CHECK: inline char32_t passThroughCChar32(char32_t x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions18passThroughCChar32ys7UnicodeO6ScalarVAFF(x);
// CHECK-NEXT: }
// CHECK: inline double passThroughCDouble(double x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions18passThroughCDoubleyS2dF(x);
// CHECK-NEXT: }
// CHECK: inline int passThroughCInt(int x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions15passThroughCIntys5Int32VADF(x);
// CHECK-NEXT: }
// CHECK: inline long long passThroughCLongLong(long long x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions20passThroughCLongLongys5Int64VADF(x);
// CHECK-NEXT: }
// CHECK: inline short passThroughCShort(short x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions17passThroughCShortys5Int16VADF(x);
// CHECK-NEXT: }
// CHECK: inline signed char passThroughCSignedChar(signed char x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions22passThroughCSignedCharys4Int8VADF(x);
// CHECK-NEXT: }
// CHECK: inline unsigned int passThroughCUnsignedInt(unsigned int x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions23passThroughCUnsignedIntys6UInt32VADF(x);
// CHECK-NEXT: }
// CHECK: inline unsigned long long passThroughCUnsignedLongLong(unsigned long long x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions024passThroughCUnsignedLongE0ys6UInt64VADF(x);
// CHECK-NEXT: }
// CHECK: inline unsigned short passThroughCUnsignedShort(unsigned short x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions25passThroughCUnsignedShortys6UInt16VADF(x);
// CHECK-NEXT: }
// CHECK: inline unsigned char passThroughCUnsignedSignedChar(unsigned char x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions30passThroughCUnsignedSignedCharys5UInt8VADF(x);
// CHECK-NEXT: }
// CHECK: inline wchar_t passThroughCWideChar(wchar_t x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions20passThroughCWideCharys7UnicodeO6ScalarVAFF(x);
// CHECK-NEXT: }
// CHECK: inline double passThroughDouble(double x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions17passThroughDoubleyS2dF(x);
// CHECK-NEXT: }
// CHECK: inline float passThroughFloat(float x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions16passThroughFloatyS2fF(x);
// CHECK-NEXT: }
// CHECK: inline float passThroughFloat32(float x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions18passThroughFloat32yS2fF(x);
// CHECK-NEXT: }
// CHECK: inline double passThroughFloat64(double x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions18passThroughFloat64yS2dF(x);
// CHECK-NEXT: }
// CHECK: inline swift::Int passThroughInt(swift::Int x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions14passThroughIntyS2iF(x);
// CHECK-NEXT: }
// CHECK: inline int16_t passThroughInt16(int16_t x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions16passThroughInt16ys0D0VADF(x);
// CHECK-NEXT: }
// CHECK: inline int32_t passThroughInt32(int32_t x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions16passThroughInt32ys0D0VADF(x);
// CHECK-NEXT: }
// CHECK: inline int64_t passThroughInt64(int64_t x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions16passThroughInt64ys0D0VADF(x);
// CHECK-NEXT: }
// CHECK: inline int8_t passThroughInt8(int8_t x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions15passThroughInt8ys0D0VADF(x);
// CHECK-NEXT: }
// CHECK: inline void * _Nonnull passThroughOpaquePointer(void * _Nonnull x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions24passThroughOpaquePointerys0dE0VADF(x);
// CHECK-NEXT: }
// CHECK: inline swift::UInt passThroughUInt(swift::UInt x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions15passThroughUIntyS2uF(x);
// CHECK-NEXT: }
// CHECK: inline uint16_t passThroughUInt16(uint16_t x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions17passThroughUInt16ys0D0VADF(x);
// CHECK-NEXT: }
// CHECK: inline uint32_t passThroughUInt32(uint32_t x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions17passThroughUInt32ys0D0VADF(x);
// CHECK-NEXT: }
// CHECK: inline uint64_t passThroughUInt64(uint64_t x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions17passThroughUInt64ys0D0VADF(x);
// CHECK-NEXT: }
// CHECK: inline uint8_t passThroughUInt8(uint8_t x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions16passThroughUInt8ys0D0VADF(x);
// CHECK-NEXT: }
// CHECK: inline void * _Nonnull passThroughUnsafeMutableRawPointer(void * _Nonnull x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions34passThroughUnsafeMutableRawPointeryS2vF(x);
// CHECK-NEXT: }
// CHECK: inline void const * _Nonnull passThroughUnsafeRawPointer(void const * _Nonnull x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions27passThroughUnsafeRawPointeryS2VF(x);
// CHECK-NEXT: }
// CHECK: inline void * _Nullable roundTwoPassThroughUnsafeMutableRawPointer(void * _Nullable x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::$s9Functions42roundTwoPassThroughUnsafeMutableRawPointerySvSgACF(x);
// CHECK-NEXT: }
public func passThroughCBool(_ x: CBool) -> CBool { return x }
public func passThroughCChar(_ x: CChar) -> CChar { return x }
public func passThroughCWideChar(_ x: CWideChar) -> CWideChar { return x }
public func passThroughCChar16(_ x: CChar16) -> CChar16 { return x }
public func passThroughCChar32(_ x: CChar32) -> CChar32 { return x }
// Don't test CLong as it's platform specific. See long-lp64 test instead.
public func passThroughCSignedChar(_ x: CSignedChar) -> CSignedChar { return x }
public func passThroughCShort(_ x: CShort) -> CShort { return x }
public func passThroughCInt(_ x: CInt) -> CInt { return x }
public func passThroughCLongLong(_ x: CLongLong) -> CLongLong { return x }
// Don't test CUnsignedLong as it's platform specific. See long-lp64 test instead.
public func passThroughCUnsignedSignedChar(_ x: CUnsignedChar) -> CUnsignedChar { return x }
public func passThroughCUnsignedShort(_ x: CUnsignedShort) -> CUnsignedShort { return x }
public func passThroughCUnsignedInt(_ x: CUnsignedInt) -> CUnsignedInt { return x }
public func passThroughCUnsignedLongLong(_ x: CUnsignedLongLong) -> CUnsignedLongLong { return x }
public func passThrougCFloat(_ x: CFloat) -> CFloat { return x }
public func passThroughCDouble(_ x: CDouble) -> CDouble { return x }
public func passThroughInt8(_ x: Int8) -> Int8 { return x }
public func passThroughInt16(_ x: Int16) -> Int16 { return x }
public func passThroughInt32(_ x: Int32) -> Int32 { return x }
public func passThroughInt64(_ x: Int64) -> Int64 { return x }
public func passThroughUInt8(_ x: UInt8) -> UInt8 { return x }
public func passThroughUInt16(_ x: UInt16) -> UInt16 { return x }
public func passThroughUInt32(_ x: UInt32) -> UInt32 { return x }
public func passThroughUInt64(_ x: UInt64) -> UInt64 { return x }
public func passThroughFloat(_ x: Float) -> Float { return x }
public func passThroughDouble(_ x: Double) -> Double { return x }
public func passThroughFloat32(_ x: Float32) -> Float32 { return x }
public func passThroughFloat64(_ x: Float64) -> Float64 { return x }
public func passThroughInt(_ x: Int) -> Int { return x }
public func passThroughUInt(_ x: UInt) -> UInt { return x }
public func passThroughBool(_ x: Bool) -> Bool { return x }
public func passThroughOpaquePointer(_ x: OpaquePointer) -> OpaquePointer { return x }
public func passThroughUnsafeRawPointer(_ x: UnsafeRawPointer) -> UnsafeRawPointer { return x }
public func passThroughUnsafeMutableRawPointer(_ x: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { return x }
public func roundTwoPassThroughUnsafeMutableRawPointer(_ x: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? { return x }
| apache-2.0 |
ivasic/Fargo | FargoTests/JSONTests.swift | 1 | 6185 | //
// JSONTests.swift
// Fargo
//
// Created by Ivan Vasic on 03/11/15.
// Copyright ยฉ 2015 Ivan Vasic. All rights reserved.
//
import XCTest
#if Debug
@testable import Fargo
#else
import Fargo
#endif
class JSONTests: XCTestCase {
#if Debug
func testObjectType() {
// Given
let json = JSON(object: 0)
// When
let type = json.objectType()
// Then
XCTAssertEqual(type, "__NSCFNumber")
}
func testNextKeyPathKey() {
// Given
let json = JSON(object: 0)
// When
let keyPath = json.nextKeyPath("subpath")
// Then
XCTAssertEqual(keyPath.path.count, 1)
switch keyPath.path.first! {
case .Key(let string): XCTAssertEqual(string, "subpath")
default: XCTFail()
}
}
func testNextKeyPathIndex() {
// Given
let json = JSON(object: 0)
// When
let keyPath = json.nextKeyPath(5)
// Then
XCTAssertEqual(keyPath.path.count, 1)
switch keyPath.path.first! {
case .Index(let index): XCTAssertEqual(index, 5)
default: XCTFail()
}
}
func testJsonForKeyPath() {
// Given
let json = JSON(object: ["0": [0, 1]])
let keyPath = JSON.KeyPath(path: [.Key("0"), .Index(1)])
// When
let result = try? json.jsonForKeyPath(keyPath)
let object = result?.object as? Int
// Then
XCTAssertNotNil(result)
XCTAssertEqual(object ?? -1, 1)
}
func testJsonForKeyPathThrows() {
// Given
let json = JSON(object: ["0": [0, 1]])
let keyPath = JSON.KeyPath(path: [.Key("0"), .Index(3)])
// When
do {
try json.jsonForKeyPath(keyPath)
XCTFail("Expected the method to throw")
} catch {
// Then
XCTAssertTrue(error is JSON.Error)
}
}
func testJsonForKeyString() {
// Given
let json = JSON(object: ["0": "0"])
// When
let result = try? json.jsonForKey("0")
let object = result?.object as? String
// Then
XCTAssertNotNil(result)
XCTAssertEqual(object ?? "", "0")
}
func testJsonForKeyStringMissingKey() {
// Given
let json = JSON(object: ["0": "0"])
// When
do {
let _: JSON = try json.jsonForKey("1")
XCTFail("Expected the method to throw")
} catch {
// Then
XCTAssertTrue(error is JSON.Error)
}
}
func testJsonForKeyStringNonObject() {
// Given
let json = JSON(object: ["0"])
// When
do {
let _: JSON = try json.jsonForKey("0")
XCTFail("Expected the method to throw")
} catch {
// Then
XCTAssertTrue(error is JSON.Error)
}
}
func testJsonForKeyStringOptional() {
// Given
let json = JSON(object: ["0": "0"])
// When
do {
let result: JSON? = try json.jsonForKey("1")
// Then
XCTAssertNil(result)
} catch {
XCTFail("Method should not throw")
}
}
func testJsonForKeyIndex() {
// Given
let json = JSON(object: ["0"])
// When
let result = try? json.jsonAtIndex(0)
let object = result?.object as? String
// Then
XCTAssertNotNil(result)
XCTAssertEqual(object ?? "", "0")
}
func testJsonForKeyIndexNonArray() {
// Given
let json = JSON(object: ["0":"1"])
// When
do {
try json.jsonAtIndex(0)
XCTFail("Expected the method to throw")
} catch {
// Then
XCTAssertTrue(error is JSON.Error)
}
}
func testJsonForKeyIndexArrayOutOfBounds() {
// Given
let json = JSON(object: ["0"])
// When
do {
try json.jsonAtIndex(1)
XCTFail("Expected the method to throw")
} catch {
// Then
XCTAssertTrue(error is JSON.Error)
}
}
func testJsonForKeys() {
// Given
let json = JSON(object: ["0": ["1": 1]])
// When
let result = try? json.jsonForKeys(["0", "1"])
let object = result?.object as? Int
// Then
XCTAssertNotNil(result)
XCTAssertEqual(object ?? 0, 1)
}
func testJsonForKeysOptional() {
// Given
let json = JSON(object: ["0": ["1": 1]])
// When
do {
let result: JSON? = try json.jsonForKeys(["0", "2"])
// Then
XCTAssertNil(result)
} catch {
XCTFail("Method should not throw")
}
}
#endif
}
// MARK: - CustomDebugStringConvertible tests
extension JSONTests {
func testDebugDescriptionPrimitive() {
// Given
let json = JSON(object: 1)
// When
let description = json.debugDescription
// Then
XCTAssertEqual(description, "__NSCFNumber (1)")
}
func testDebugDescriptionArray() {
// Given
let json = JSON(object: [0, 1])
// When
let description = json.debugDescription
// Then
XCTAssertEqual(description, "Array<__NSCFNumber> (2)")
}
func testDebugDescriptionEmptyArray() {
// Given
let json = JSON(object: [])
// When
let description = json.debugDescription
// Then
XCTAssertEqual(description, "Array (empty)")
}
func testDebugDescriptionObject() {
// Given
let json = JSON(object: ["key": "value"])
// When
let description = json.debugDescription
// Then
XCTAssertEqual(description, "Object (1)")
}
}
| mit |
syoung-smallwisdom/BridgeAppSDK | BridgeAppSDK/SBAActiveTask.swift | 1 | 14712 | //
// SBAActiveTaskFactory.swift
// BridgeAppSDK
//
// Copyright ยฉ 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// 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.
//
import ResearchKit
import BridgeSDK
import AVFoundation
public enum SBAActiveTaskType {
case custom(String?)
case memory
case tapping
case voice
case walking
case tremor
case moodSurvey
init(name: String?) {
guard let type = name else { self = .custom(nil); return }
switch(type) {
case "tapping" : self = .tapping
case "memory" : self = .memory
case "voice" : self = .voice
case "walking" : self = .walking
case "tremor" : self = .tremor
case "moodSurvey" : self = .moodSurvey
default : self = .custom(name)
}
}
func isNilType() -> Bool {
if case .custom(let customType) = self {
return (customType == nil)
}
return false
}
}
extension ORKPredefinedTaskHandOption {
init(name: String?) {
let name = name ?? "both"
switch name {
case "right" : self = .right
case "left" : self = .left
default : self = .both
}
}
}
extension ORKTremorActiveTaskOption {
init(excludes: [String]?) {
guard let excludes = excludes else {
self.init(rawValue: 0)
return
}
let rawValue: UInt = excludes.map({ (exclude) -> ORKTremorActiveTaskOption in
switch exclude {
case "inLap" : return .excludeHandInLap
case "shoulderHeight" : return .excludeHandAtShoulderHeight
case "elbowBent" : return .excludeHandAtShoulderHeightElbowBent
case "touchNose" : return .excludeHandToNose
case "queenWave" : return .excludeQueenWave
default : return []
}
}).reduce(0) { (raw, option) -> UInt in
return option.rawValue | raw
}
self.init(rawValue: rawValue)
}
}
extension ORKMoodSurveyFrequency {
init(name: String?) {
let name = name ?? "daily"
switch name {
case "weekly" : self = .weekly
default : self = .daily
}
}
}
public protocol SBAActiveTask: SBABridgeTask, SBAStepTransformer {
var taskType: SBAActiveTaskType { get }
var intendedUseDescription: String? { get }
var taskOptions: [String : AnyObject]? { get }
var predefinedExclusions: ORKPredefinedTaskOption? { get }
var localizedSteps: [SBASurveyItem]? { get }
var optional: Bool { get }
}
extension SBAActiveTask {
func createDefaultORKActiveTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask? {
let predefinedExclusions = self.predefinedExclusions ?? options
// Map known active tasks
var task: ORKOrderedTask!
switch self.taskType {
case .tapping:
task = tappingTask(predefinedExclusions)
case .memory:
task = memoryTask(predefinedExclusions)
case .voice:
task = voiceTask(predefinedExclusions)
case .walking:
task = walkingTask(predefinedExclusions)
case .tremor:
task = tremorTask(predefinedExclusions)
case .moodSurvey:
task = moodSurvey(predefinedExclusions)
default:
// exit early if not supported by base implementation
return nil
}
// Modify the instruction step if this is an optional task
if self.optional {
task = taskWithSkipAction(task)
}
// map the localized steps
mapLocalizedSteps(task)
return task
}
func taskWithSkipAction(_ task: ORKOrderedTask) -> ORKOrderedTask {
guard type(of: task) === ORKOrderedTask.self else {
assertionFailure("Handling of an optional task is not implemented for any class other than ORKOrderedTask")
return task
}
guard let introStep = task.steps.first as? ORKInstructionStep else {
assertionFailure("Handling of an optional task is not implemented for tasks that do not start with ORKIntructionStep")
return task
}
guard let conclusionStep = task.steps.last as? ORKInstructionStep else {
assertionFailure("Handling of an optional task is not implemented for tasks that do not end with ORKIntructionStep")
return task
}
// Replace the intro step with a direct navigation step that has a skip button
// to skip to the conclusion
let replaceStep = SBAInstructionStep(identifier: introStep.identifier)
replaceStep.title = introStep.title
replaceStep.text = introStep.text
let skipExplanation = Localization.localizedString("SBA_SKIP_ACTIVITY_INSTRUCTION")
let detail = introStep.detailText ?? ""
replaceStep.detailText = "\(detail)\n\(skipExplanation)\n"
replaceStep.learnMoreAction = SBASkipAction(identifier: conclusionStep.identifier)
replaceStep.learnMoreAction!.learnMoreButtonText = Localization.localizedString("SBA_SKIP_ACTIVITY")
var steps: [ORKStep] = task.steps
steps.removeFirst()
steps.insert(replaceStep, at: 0)
// Return a navigable ordered task
return SBANavigableOrderedTask(identifier: task.identifier, steps: steps)
}
func mapLocalizedSteps(_ task: ORKOrderedTask) {
// Map the title, text and detail from the localizedSteps to their matching step from the
// base factory method defined
if let items = self.localizedSteps {
for item in items {
if let step = task.steps.find({ return $0.identifier == item.identifier }) {
step.title = item.stepTitle ?? step.title
step.text = item.stepText ?? step.text
if let instructionItem = item as? SBAInstructionStepSurveyItem,
let detail = instructionItem.stepDetail,
let instructionStep = step as? ORKInstructionStep {
instructionStep.detailText = detail
}
if let activeStep = step as? ORKActiveStep,
let activeItem = item as? SBAActiveStepSurveyItem {
if let spokenInstruction = activeItem.stepSpokenInstruction {
activeStep.spokenInstruction = spokenInstruction
}
if let finishedSpokenInstruction = activeItem.stepFinishedSpokenInstruction {
activeStep.finishedSpokenInstruction = finishedSpokenInstruction
}
}
}
}
}
}
func tappingTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask {
let duration: TimeInterval = taskOptions?["duration"] as? TimeInterval ?? 10.0
let handOptions = ORKPredefinedTaskHandOption(name: taskOptions?["handOptions"] as? String)
return ORKOrderedTask.twoFingerTappingIntervalTask(
withIdentifier: self.schemaIdentifier,
intendedUseDescription: self.intendedUseDescription,
duration: duration,
handOptions: handOptions,
options: options)
}
func memoryTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask {
let initialSpan: Int = taskOptions?["initialSpan"] as? Int ?? 3
let minimumSpan: Int = taskOptions?["minimumSpan"] as? Int ?? 2
let maximumSpan: Int = taskOptions?["maximumSpan"] as? Int ?? 15
let playSpeed: TimeInterval = taskOptions?["playSpeed"] as? TimeInterval ?? 1.0
let maxTests: Int = taskOptions?["maxTests"] as? Int ?? 5
let maxConsecutiveFailures: Int = taskOptions?["maxConsecutiveFailures"] as? Int ?? 3
var customTargetImage: UIImage? = nil
if let imageName = taskOptions?["customTargetImageName"] as? String {
customTargetImage = SBAResourceFinder.shared.image(forResource: imageName)
}
let customTargetPluralName: String? = taskOptions?["customTargetPluralName"] as? String
let requireReversal: Bool = taskOptions?["requireReversal"] as? Bool ?? false
return ORKOrderedTask.spatialSpanMemoryTask(withIdentifier: self.schemaIdentifier,
intendedUseDescription: self.intendedUseDescription,
initialSpan: initialSpan,
minimumSpan: minimumSpan,
maximumSpan: maximumSpan,
playSpeed: playSpeed,
maximumTests: maxTests,
maximumConsecutiveFailures: maxConsecutiveFailures,
customTargetImage: customTargetImage,
customTargetPluralName: customTargetPluralName,
requireReversal: requireReversal,
options: options)
}
func voiceTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask {
let speechInstruction: String? = taskOptions?["speechInstruction"] as? String
let shortSpeechInstruction: String? = taskOptions?["shortSpeechInstruction"] as? String
let duration: TimeInterval = taskOptions?["duration"] as? TimeInterval ?? 10.0
let recordingSettings: [String: AnyObject]? = taskOptions?["recordingSettings"] as? [String: AnyObject]
return ORKOrderedTask.audioTask(withIdentifier: self.schemaIdentifier,
intendedUseDescription: self.intendedUseDescription,
speechInstruction: speechInstruction,
shortSpeechInstruction: shortSpeechInstruction,
duration: duration,
recordingSettings: recordingSettings,
checkAudioLevel: true,
options: options)
}
func walkingTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask {
// The walking activity is assumed to be walking back and forth rather than trying to walk down a long hallway.
let walkDuration: TimeInterval = taskOptions?["walkDuration"] as? TimeInterval ?? 30.0
let restDuration: TimeInterval = taskOptions?["restDuration"] as? TimeInterval ?? 30.0
return ORKOrderedTask.walkBackAndForthTask(withIdentifier: self.schemaIdentifier,
intendedUseDescription: self.intendedUseDescription,
walkDuration: walkDuration,
restDuration: restDuration,
options: options)
}
func tremorTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask {
let duration: TimeInterval = taskOptions?["duration"] as? TimeInterval ?? 10.0
let handOptions = ORKPredefinedTaskHandOption(name: taskOptions?["handOptions"] as? String)
let excludeOptions = ORKTremorActiveTaskOption(excludes: taskOptions?["excludePostions"] as? [String])
return ORKOrderedTask.tremorTest(withIdentifier: self.schemaIdentifier,
intendedUseDescription: self.intendedUseDescription,
activeStepDuration: duration,
activeTaskOptions: excludeOptions,
handOptions: handOptions,
options: options)
}
func moodSurvey(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask {
let frequency = ORKMoodSurveyFrequency(name: taskOptions?["frequency"] as? String)
let customQuestionText = taskOptions?["customQuestionText"] as? String
return ORKOrderedTask.moodSurvey(withIdentifier: self.schemaIdentifier,
intendedUseDescription: self.intendedUseDescription,
frequency: frequency,
customQuestionText: customQuestionText,
options: options)
}
}
| bsd-3-clause |
appsquickly/backdrop | source/CommandLine/CommandLine.swift | 2 | 9396 | /*
* CommandLine.swift
* Copyright (c) 2014 Ben Gollmer.
*
* 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.
*/
/* Required for setlocale(3) */
@exported import Darwin
let ShortOptionPrefix = "-"
let LongOptionPrefix = "--"
/* Stop parsing arguments when an ArgumentStopper (--) is detected. This is a GNU getopt
* convention; cf. https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html
*/
let ArgumentStopper = "--"
/* Allow arguments to be attached to flags when separated by this character.
* --flag=argument is equivalent to --flag argument
*/
let ArgumentAttacher: Character = "="
/* An output stream to stderr; used by CommandLine.printUsage(). */
private struct StderrOutputStream: OutputStreamType {
static let stream = StderrOutputStream()
func write(s: String) {
fputs(s, stderr)
}
}
/**
* The CommandLine class implements a command-line interface for your app.
*
* To use it, define one or more Options (see Option.swift) and add them to your
* CommandLine object, then invoke `parse()`. Each Option object will be populated with
* the value given by the user.
*
* If any required options are missing or if an invalid value is found, `parse()` will throw
* a `ParseError`. You can then call `printUsage()` to output an automatically-generated usage
* message.
*/
public class CommandLine {
private var _arguments: [String]
private var _options: [Option] = [Option]()
/** A ParseError is thrown if the `parse()` method fails. */
public enum ParseError: ErrorType, CustomStringConvertible {
/** Thrown if an unrecognized argument is passed to `parse()` in strict mode */
case InvalidArgument(String)
/** Thrown if the value for an Option is invalid (e.g. a string is passed to an IntOption) */
case InvalidValueForOption(Option, [String])
/** Thrown if an Option with required: true is missing */
case MissingRequiredOptions([Option])
public var description: String {
switch self {
case let .InvalidArgument(arg):
return "Invalid argument: \(arg)"
case let .InvalidValueForOption(opt, vals):
let vs = vals.joinWithSeparator(", ")
return "Invalid value(s) for option \(opt.flagDescription): \(vs)"
case let .MissingRequiredOptions(opts):
return "Missing required options: \(opts.map { return $0.flagDescription })"
}
}
}
/**
* Initializes a CommandLine object.
*
* - parameter arguments: Arguments to parse. If omitted, the arguments passed to the app
* on the command line will automatically be used.
*
* - returns: An initalized CommandLine object.
*/
public init(arguments: [String] = Process.arguments) {
self._arguments = arguments
/* Initialize locale settings from the environment */
setlocale(LC_ALL, "")
}
/* Returns all argument values from flagIndex to the next flag or the end of the argument array. */
private func _getFlagValues(flagIndex: Int) -> [String] {
var args: [String] = [String]()
var skipFlagChecks = false
/* Grab attached arg, if any */
var attachedArg = _arguments[flagIndex].splitByCharacter(ArgumentAttacher, maxSplits: 1)
if attachedArg.count > 1 {
args.append(attachedArg[1])
}
for var i = flagIndex + 1; i < _arguments.count; i++ {
if !skipFlagChecks {
if _arguments[i] == ArgumentStopper {
skipFlagChecks = true
continue
}
if _arguments[i].hasPrefix(ShortOptionPrefix) && Int(_arguments[i]) == nil &&
_arguments[i].toDouble() == nil {
break
}
}
args.append(_arguments[i])
}
return args
}
/**
* Adds an Option to the command line.
*
* - parameter option: The option to add.
*/
public func addOption(option: Option) {
_options.append(option)
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: An array containing the options to add.
*/
public func addOptions(options: [Option]) {
_options += options
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: The options to add.
*/
public func addOptions(options: Option...) {
_options += options
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: An array containing the options to set.
*/
public func setOptions(options: [Option]) {
_options = options
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: The options to set.
*/
public func setOptions(options: Option...) {
_options = options
}
/**
* Parses command-line arguments into their matching Option values. Throws `ParseError` if
* argument parsing fails.
*
* - parameter strict: Fail if any unrecognized arguments are present (default: false).
*/
public func parse(strict: Bool = false) throws {
for (idx, arg) in _arguments.enumerate() {
if arg == ArgumentStopper {
break
}
if !arg.hasPrefix(ShortOptionPrefix) {
continue
}
let skipChars = arg.hasPrefix(LongOptionPrefix) ?
LongOptionPrefix.characters.count : ShortOptionPrefix.characters.count
let flagWithArg = arg[Range(start: arg.startIndex.advancedBy(skipChars), end: arg.endIndex)]
/* The argument contained nothing but ShortOptionPrefix or LongOptionPrefix */
if flagWithArg.isEmpty {
continue
}
/* Remove attached argument from flag */
let flag = flagWithArg.splitByCharacter(ArgumentAttacher, maxSplits: 1)[0]
var flagMatched = false
for option in _options where option.flagMatch(flag) {
let vals = self._getFlagValues(idx)
guard option.setValue(vals) else {
throw ParseError.InvalidValueForOption(option, vals)
}
flagMatched = true
break
}
/* Flags that do not take any arguments can be concatenated */
let flagLength = flag.characters.count
if !flagMatched && !arg.hasPrefix(LongOptionPrefix) {
for (i, c) in flag.characters.enumerate() {
for option in _options where option.flagMatch(String(c)) {
/* Values are allowed at the end of the concatenated flags, e.g.
* -xvf <file1> <file2>
*/
let vals = (i == flagLength - 1) ? self._getFlagValues(idx) : [String]()
guard option.setValue(vals) else {
throw ParseError.InvalidValueForOption(option, vals)
}
flagMatched = true
break
}
}
}
/* Invalid flag */
guard !strict || flagMatched else {
throw ParseError.InvalidArgument(arg)
}
}
/* Check to see if any required options were not matched */
let missingOptions = _options.filter { $0.required && !$0.wasSet }
guard missingOptions.count == 0 else {
throw ParseError.MissingRequiredOptions(missingOptions)
}
}
/* printUsage() is generic for OutputStreamType because the Swift compiler crashes
* on inout protocol function parameters in Xcode 7 beta 1 (rdar://21372694).
*/
/**
* Prints a usage message.
*
* - parameter to: An OutputStreamType to write the error message to.
*/
public func printUsage<TargetStream: OutputStreamType>(inout to: TargetStream) {
let name = _arguments[0]
var flagWidth = 0
for opt in _options {
flagWidth = max(flagWidth, " \(opt.flagDescription):".characters.count)
}
print("Usage: \(name) [options]", toStream: &to)
for opt in _options {
let flags = " \(opt.flagDescription):".paddedToWidth(flagWidth)
print("\(flags)\n \(opt.helpMessage)", toStream: &to)
}
}
/**
* Prints a usage message.
*
* - parameter error: An error thrown from `parse()`. A description of the error
* (e.g. "Missing required option --extract") will be printed before the usage message.
* - parameter to: An OutputStreamType to write the error message to.
*/
public func printUsage<TargetStream: OutputStreamType>(error: ErrorType, inout to: TargetStream) {
print("\(error)\n", toStream: &to)
printUsage(&to)
}
/**
* Prints a usage message.
*
* - parameter error: An error thrown from `parse()`. A description of the error
* (e.g. "Missing required option --extract") will be printed before the usage message.
*/
public func printUsage(error: ErrorType) {
var out = StderrOutputStream.stream
printUsage(error, to: &out)
}
/**
* Prints a usage message.
*/
public func printUsage() {
var out = StderrOutputStream.stream
printUsage(&out)
}
}
| apache-2.0 |
ken0nek/swift | validation-test/Reflection/reflect_Int32.swift | 1 | 2123 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Int32
// RUN: %target-run %target-swift-reflection-test %t/reflect_Int32 2>&1 | FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
import SwiftReflectionTest
class TestClass {
var t: Int32
init(t: Int32) {
self.t = t
}
}
var obj = TestClass(t: 123)
reflect(object: obj)
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Int32.TestClass)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=20 alignment=16 stride=32 num_extra_inhabitants=0
// CHECK-64: (field name=t offset=16
// CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Int32.TestClass)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=16 alignment=16 stride=16 num_extra_inhabitants=0
// CHECK-32: (field name=t offset=12
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
reflect(any: obj)
// CHECK-64: Reflecting an existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Int32.TestClass)
// CHECK-64: Type info:
// CHECK-64: (reference kind=strong refcounting=native)
// CHECK-32: Reflecting an existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Int32.TestClass)
// CHECK-32: Type info:
// CHECK-32: (reference kind=strong refcounting=native)
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| apache-2.0 |
esttorhe/SlackTeamExplorer | SlackTeamExplorer/Pods/Nimble/Nimble/DSL.swift | 28 | 1377 | /// Make an expectation on a given actual value. The value given is lazily evaluated.
public func expect<T>(@autoclosure(escaping) expression: () -> T?, file: String = __FILE__, line: UInt = __LINE__) -> Expectation<T> {
return Expectation(
expression: Expression(
expression: expression,
location: SourceLocation(file: file, line: line),
isClosure: true))
}
/// Make an expectation on a given actual value. The closure is lazily invoked.
public func expect<T>(file: String = __FILE__, line: UInt = __LINE__, expression: () -> T?) -> Expectation<T> {
return Expectation(
expression: Expression(
expression: expression,
location: SourceLocation(file: file, line: line),
isClosure: true))
}
/// Always fails the test with a message and a specified location.
public func fail(message: String, #location: SourceLocation) {
NimbleAssertionHandler.assert(false, message: FailureMessage(stringValue: message), location: location)
}
/// Always fails the test with a message.
public func fail(message: String, file: String = __FILE__, line: UInt = __LINE__) {
fail(message, location: SourceLocation(file: file, line: line))
}
/// Always fails the test.
public func fail(file: String = __FILE__, line: UInt = __LINE__) {
fail("fail() always fails", file: file, line: line)
}
| mit |
leannenorthrop/markdown-swift | Markdown/Uchen.swift | 1 | 13821 | //
// Uchen.swift
// Markdown
//
// Created by Leanne Northrop on 13/06/2015.
// Copyright (c) 2015 Leanne Northrop. All rights reserved.
//
import Foundation
public struct UChen {
let WylieMap = [
// Consonants
"k" : "\u{0F40}",
"kh" : "\u{0F41}",
"g" : "\u{0F42}",
"ng" : "\u{0F44}",
"c" : "\u{0F45}",
"ch" : "\u{0F46}",
"j" : "\u{0F47}",
"ny" : "\u{0F49}",
"t" : "\u{0F4F}",
"th" : "\u{0F50}",
"d" : "\u{0F51}",
"n" : "\u{0F53}",
"p" : "\u{0F54}",
"ph" : "\u{0F55}",
"b" : "\u{0F56}",
"m" : "\u{0F58}",
"ts" : "\u{0F59}",
"tsh" : "\u{0F5A}",
"dz" : "\u{0F5B}",
"w" : "\u{0F5D}",
"zh" : "\u{0F5E}",
"z" : "\u{0F5F}",
"'" : "\u{0F60}",
"y" : "\u{0F61}",
"r" : "\u{0F62}",
"l" : "\u{0F63}",
"sh" : "\u{0F64}",
"s" : "\u{0F66}",
"h" : "\u{0F67}",
"a" : "\u{0F68}",
".k" : "\u{0F40}",
".kh" : "\u{0F41}",
".g" : "\u{0F42}",
".ng" : "\u{0F44}",
".c" : "\u{0F45}",
".ch" : "\u{0F46}",
".j" : "\u{0F47}",
".ny" : "\u{0F49}",
".t" : "\u{0F4F}",
".th" : "\u{0F50}",
".d" : "\u{0F51}",
".n" : "\u{0F53}",
".p" : "\u{0F54}",
".ph" : "\u{0F55}",
".b" : "\u{0F56}",
".m" : "\u{0F58}",
".ts" : "\u{0F59}",
".tsh" : "\u{0F5A}",
".dz" : "\u{0F5B}",
".w" : "\u{0F5D}",
".zh" : "\u{0F5E}",
".z" : "\u{0F5F}",
".'" : "\u{0F60}",
".y" : "\u{0F61}",
".r" : "\u{0F62}",
".l" : "\u{0F63}",
".sh" : "\u{0F64}",
".s" : "\u{0F66}",
".h" : "\u{0F67}",
".a" : "\u{0F68}",
"ka" : "\u{0F40}",
"kha" : "\u{0F41}",
"ga" : "\u{0F42}",
"nga" : "\u{0F44}",
"ca" : "\u{0F45}",
"cha" : "\u{0F46}",
"ja" : "\u{0F47}",
"nya" : "\u{0F49}",
"ta" : "\u{0F4F}",
"tha" : "\u{0F50}",
"da" : "\u{0F51}",
"na" : "\u{0F53}",
"pa" : "\u{0F54}",
"pha" : "\u{0F55}",
"ba" : "\u{0F56}",
"ma" : "\u{0F58}",
"tsa" : "\u{0F59}",
"tsha" : "\u{0F5A}",
"dza" : "\u{0F5B}",
"wa" : "\u{0F5D}",
"zha" : "\u{0F5E}",
"za" : "\u{0F5F}",
"ya" : "\u{0F61}",
"ra" : "\u{0F62}",
"la" : "\u{0F63}",
"sha" : "\u{0F64}",
"sa" : "\u{0F66}",
"ha" : "\u{0F67}",
".ka" : "\u{0F40}",
".kha" : "\u{0F41}",
".ga" : "\u{0F42}",
".nga" : "\u{0F44}",
".ca" : "\u{0F45}",
".cha" : "\u{0F46}",
".ja" : "\u{0F47}",
".nya" : "\u{0F49}",
".ta" : "\u{0F4F}",
".tha" : "\u{0F50}",
".da" : "\u{0F51}",
".na" : "\u{0F53}",
".pa" : "\u{0F54}",
".pha" : "\u{0F55}",
".ba" : "\u{0F56}",
".ma" : "\u{0F58}",
".tsa" : "\u{0F59}",
".tsha" : "\u{0F5A}",
".dza" : "\u{0F5B}",
".wa" : "\u{0F5D}",
".zha" : "\u{0F5E}",
".za" : "\u{0F5F}",
".ya" : "\u{0F61}",
".ra" : "\u{0F62}",
".la" : "\u{0F63}",
".sha" : "\u{0F64}",
".sa" : "\u{0F66}",
".ha" : "\u{0F67}",
// Sanskrit & Subjoined Sanskrit
"gh" : "\u{0F43}",
"g+h" : "\u{0F43}",
"dh" : "\u{0F52}",
"d+h" : "\u{0F52}",
"bh" : "\u{0F57}",
"b+h" : "\u{0F57}",
"dzh" : "\u{0F5C}",
"dz+h" : "\u{0F5C}",
"kSh" : "\u{0F69}",
"k+Sh" : "\u{0F69}",
"T" : "\u{0F4A}",
"Th" : "\u{0F4B}",
"D" : "\u{0F4C}",
"Dh" : "\u{0F4D}",
"D+h" : "\u{0F4D}",
"N" : "\u{0F4E}",
"Sh" : "\u{0F65}",
"oM" : "\u{0F00}",
"+W" : "\u{0FBA}",
"+Y" : "\u{0FBB}",
"+R" : "\u{0FBC}",
"H" : "\u{0F7F}",
"M" : "\u{0F7E}",
"~M" : "\u{0F83}",
"~M'" : "\u{0F82}",
"~?" : "\u{0F84}",
"&" : "\u{0F85}",
// Subjoined Consonants
"+k" : "\u{0F90}",
"+kh" : "\u{0F91}",
"+g" : "\u{0F92}",
"+gh" : "\u{0F93}",
"+ng" : "\u{0F94}",
"+c" : "\u{0F95}",
"+ch" : "\u{0F96}",
"+j" : "\u{0F97}",
"+ny" : "\u{0F99}",
"+th" : "\u{0FA0}",
"+n" : "\u{0F9E}",
"+t" : "\u{0F9F}",
"+d" : "\u{0FA1}",
"+dh" : "\u{0FA2}",
//"+n" : "\u{0FA3}",
"+p" : "\u{0FA4}",
"+ph" : "\u{0FA5}",
"+b" : "\u{0FA6}",
"+bh" : "\u{0FA7}",
"+m" : "\u{0FA8}",
"+ts" : "\u{0FA9}",
"+tsh" : "\u{0FAA}",
"+dz" : "\u{0FAB}",
"+dzh" : "\u{0FAC}",
"+w" : "\u{0FAD}",
"+zh" : "\u{0FAE}",
"+z" : "\u{0FAF}",
"+a" : "\u{0FB0}",
"+'" : "\u{0FB0}",
"+y" : "\u{0FB1}",
"+r" : "\u{0FB2}",
"+l" : "\u{0FB3}",
"+sh" : "\u{0FB4}",
"+s" : "\u{0FB6}",
"+h" : "\u{0FB7}",
"+A" : "\u{0FB8}",
"+ksh" : "\u{0FB9}",
"+.w" : "\u{0FBA}",
"+.y" : "\u{0FBB}",
"+.r" : "\u{0FBC}",
"+ka" : "\u{0F90}",
"+kha" : "\u{0F91}",
"+ga" : "\u{0F92}",
"+gha" : "\u{0F93}",
"+nga" : "\u{0F94}",
"+ca" : "\u{0F95}",
"+cha" : "\u{0F96}",
"+ja" : "\u{0F97}",
"+nya" : "\u{0F99}",
"+tha" : "\u{0FA0}",
"+na" : "\u{0F9E}",
"+ta" : "\u{0F9F}",
"+da" : "\u{0FA1}",
"+dha" : "\u{0FA2}",
//"+na" : "\u{0FA3}",
"+pa" : "\u{0FA4}",
"+pha" : "\u{0FA5}",
"+ba" : "\u{0FA6}",
"+bha" : "\u{0FA7}",
"+ma" : "\u{0FA8}",
"+tsa" : "\u{0FA9}",
"+tsha" : "\u{0FAA}",
"+dza" : "\u{0FAB}",
"+dzha" : "\u{0FAC}",
"+wa" : "\u{0FAD}",
"+zha" : "\u{0FAE}",
"+za" : "\u{0FAF}",
"+ya" : "\u{0FB1}",
"+ra" : "\u{0FB2}",
"+la" : "\u{0FB3}",
"+sha" : "\u{0FB4}",
"+sa" : "\u{0FB6}",
"+ha" : "\u{0FB7}",
"+.wa" : "\u{0FBA}",
"+.ya" : "\u{0FBB}",
"+.ra" : "\u{0FBC}",
// Vowels
"i" : "\u{0F72}",
"u" : "\u{0F74}",
"e" : "\u{0F7A}",
"o" : "\u{0F7C}",
"A" : "\u{0F71}",
"I" : "\u{0F73}",
"U" : "\u{0F75}",
"r-i" : "\u{0F76}",
"l-i" : "\u{0F78}",
"-i" : "\u{0F80}",
"ai" : "\u{0F7B}",
"au" : "\u{0F7D}",
"r-I" : "\u{0F77}",
"l-I" : "\u{0F79}",
"-I" : "\u{0F81}",
// Numbers
"0" : "\u{0F20}",
"1" : "\u{0F21}",
"2" : "\u{0F22}",
"3" : "\u{0F23}",
"4" : "\u{0F24}",
"5" : "\u{0F25}",
"6" : "\u{0F26}",
"7" : "\u{0F27}",
"8" : "\u{0F28}",
"9" : "\u{0F29}",
//Punctuation
"_" : " }",
" " : "\u{0F0B}",
"*" : "\u{0F0C}",
"/" : "\u{0F0D}",
"//" : "\u{0F0E}",
"," : "\u{0F0F}",
"|" : "\u{0F11}",
"!" : "\u{0F08}",
":" : "\u{0F14}",
"ยฃ" : "\u{0F10}",
"ยฌ" : "\u{0F12}",
"=" : "\u{0F34}",
"x" : "\u{0FBE}",
"x." : "\u{0FBF}",
"...." : "\u{0F36}",
"o...." : "\u{0F13}",
"H1" : "\u{0F01}",
"H2" : "\u{0F02}",
"H3" : "\u{0F03}",
"@" : "\u{0F04}",
"#" : "\u{0F05}",
"$" : "\u{0F06}",
"%" : "\u{0F07}",
"H4" : "\u{0F09}",
"H5" : "\u{0F0A}",
"H6" : "\u{0FD0}",
"H7" : "\u{0FD1}",
"<" : "\u{0F3A}",
">" : "\u{0F3B}",
"(" : "\u{0F3C}",
")" : "\u{0F3D}",
]
let WylieLigatures = [
// Ligatures & Special Character or Character Combinations
"rk" : "r+k",
"rg" : "r+g",
"rng" : "r+ng",
"rj" : "r+j",
"rny" : "r+ny",
"rt" : "r+t",
"rd" : "r+d",
"rn" : "r+n",
"rb" : "r+b",
"rm" : "r+m",
"rts" : "r+ts",
"rdz" : "r+dz",
"lk" : "l+k",
"lg" : "l+g",
"lng" : "l+ng",
"lc" : "l+c",
"lj" : "l+j",
"lt" : "l+t",
"ld" : "l+d",
"lp" : "l+p",
"lb" : "l+b",
"lh" : "l+h",
"sk" : "s+k",
"sg" : "s+g",
"sng" : "s+ng",
"sny" : "s+ny",
"st" : "s+t",
"sd" : "s+d",
"sn" : "s+n",
"sp" : "s+p",
"sb" : "s+b",
"sm" : "s+m",
"sts" : "s+ts",
"kw" : "k+w",
"khw" : "kh+w",
"gw" : "g+w",
"cw" : "c+w",
"nyw" : "ny+w",
"tw" : "t+w",
"dw" : "d+w",
"tsw" : "ts+w",
"tshw" : "tsh+w",
"zhw" : "zh+w",
"zw" : "z+w",
"rw" : "r+w",
"shw" : "sh+w",
"sw" : "s+w",
"hw" : "h+w",
"ky" : "k+y",
"khy" : "kh+y",
"gy" : "g+y",
"py" : "p+y",
"phy" : "ph+y",
"by" : "b+y",
"my" : "m+y",
"kr" : "k+r",
"khr" : "kh+r",
"gr" : "g+r",
"tr" : "t+r",
"thr" : "th+r",
"dr" : "d+r",
"pr" : "p+r",
"phr" : "ph+r",
"br" : "b+r",
"mr" : "m+r",
"shr" : "sh+r",
"sr" : "s+r",
"hr" : "h+r",
"kl" : "k+l",
"gl" : "g+l",
"bl" : "b+l",
"zl" : "z+l",
"rl" : "r+l",
"sl" : "s+l",
"rky" : "r+k+y",
"rgy" : "r+g+y",
"rmy" : "r+m+y",
"rgw" : "r+g+w",
"rtsw" : "r+ts+w",
"sky" : "s+k+y",
"sgy" : "s+g+y",
"spy" : "s+p+y",
"sby" : "s+b+y",
"smy" : "s+m+y",
"skr" : "s+k+r",
"sgr" : "s+g+r",
"snr" : "s+n+r",
"spr" : "s+p+r",
"sbr" : "s+b+r",
"smr" : "s+m+r",
"grw" : "g+r+w",
"drw" : "d+r+w",
"phyw" : "ph+y+w",
"~om" : "\u{0F00}",
"~athung" : "\u{0F01}",
"~namcheyma" : "\u{0F02}",
"~tertsekma" : "\u{0F03}",
"~dunma" : "\u{0F04}",
"~kabma" : "\u{0F05}",
"~pursheyma" : "\u{0F06}",
"~tseksheyma" : "\u{0F07}",
"~drulshey" : "\u{0F08}",
"~kuryikgo" : "\u{0F09}",
"~kashoyikgo" : "\u{0F0A}",
"~tsek" : "\u{0F0B}",
"~tsektar" : "\u{0F0C}",
"~shey" : "\u{0F0D}",
"~nyishey" : "\u{0F0E}",
"~tsekshey" : "\u{0F0F}",
"~nyitsekshey" : "\u{0F10}",
"~rinchenpungshey" : "\u{0F11}",
"~gyatramshey" : "\u{0F12}",
"~dzutamelongchen" : "\u{0F13}",
"~tertsek" : "\u{0F14}",
"~cheta" : "\u{0F15}",
"~lakta" : "\u{0F16}",
"~trachencharta" : "\u{0F17}",
"~kyupa" : "\u{0F18}",
"~dongtsu" : "\u{0F19}",
"~dekachig" : "\u{0F1A}",
"~dekanyi" : "\u{0F1B}",
"~dekasum" : "\u{0F1C}",
"~denachig" : "\u{0F1D}",
"~denanyi" : "\u{0F1E}",
"~dekadena" : "\u{0F1F}",
"~duta" : "\u{0F34}",
"~ngezungnyida" : "\u{0F35}",
"~dzutashimigchen" : "\u{0F36}",
"~ngezunggorta" : "\u{0F37}",
"~chego" : "\u{0F38}",
"~tsatru" : "\u{0F39}",
"~gugtayun" : "\u{0F3A}",
"~gugtaye" : "\u{0F3B}",
"~angkangyun" : "\u{0F3C}",
"~angkangye" : "\u{0F3D}",
"~yartse" : "\u{0F3E}",
"~martse" : "\u{0F3F}",
"~kuruka" : "\u{0FBE}",
"~kurukashimikchen" : "\u{0FBF}",
"~HEAVY" : "\u{0FC0}",
"~LIGHT" : "\u{0FC1}",
"~CANGTE" : "\u{0FC2}",
"~SBUB" : "\u{0FC3}",
"~drilbu" : "\u{0FC4}",
"~dorje" : "\u{0FC5}",
"~pemaden" : "\u{0FC6}",
"~dorjegyadram" : "\u{0FC7}",
"~phurba" : "\u{0FC8}",
"~norbu" : "\u{0FC9}",
"~norbunyikhyi" : "\u{0FCA}",
"~norbusumkhyi" : "\u{0FCB}",
"~norbushikhyi" : "\u{0FCC}",
"~denasum" : "\u{0FCF}",
]
var _sortedLigatureKeys = [String]()
var _sortedKeys = [String]()
public init() {
var keys = self.WylieLigatures.keys.array
keys.sort { count($0) > count($1) }
_sortedLigatureKeys = keys
keys = self.WylieMap.keys.array
keys.sort { count($0) > count($1) }
_sortedKeys = keys
}
public func translate(text:String) -> String {
func apply(str : String, substitutions : [String], map : [String:String]) -> String {
var result = str;
for (var i = 0; i < substitutions.count; i++) {
let key = substitutions[i]
let match = result.rangeOfString(key, options: .LiteralSearch)
if match != nil {
result = result.stringByReplacingOccurrencesOfString(key,
withString: map[key]!,
options: NSStringCompareOptions.LiteralSearch,
range: nil)
}
}
return result;
}
var result = "";
result = text.stringByReplacingOccurrencesOfString(" ",
withString: self.WylieMap[" "]!,
options: NSStringCompareOptions.LiteralSearch,
range: nil)
result = apply(apply(result, _sortedLigatureKeys, WylieLigatures), _sortedKeys, WylieMap)
return result;
}
}
| gpl-2.0 |
ByteriX/BxInputController | BxInputController/Sources/Common/View/StandartText/BxInputStandartTextRowBinder.swift | 1 | 3427 | /**
* @file BxInputStandartTextRowBinder.swift
* @namespace BxInputController
*
* @details Binder for a standart text row
* @date 06.03.2017
* @author Sergey Balalaev
*
* @version last in https://github.com/ByteriX/BxInputController.git
* @copyright The MIT License (MIT) https://opensource.org/licenses/MIT
* Copyright (c) 2017 ByteriX. See http://byterix.com
*/
import UIKit
/// Binder for a standart text row
open class BxInputStandartTextRowBinder<Row: BxInputRow, Cell> : BxInputBaseFieldRowBinder<Row, Cell>, UITextFieldDelegate
where Cell : UITableViewCell, Cell : BxInputFieldCell
{
/// call when user selected this cell
override open func didSelected()
{
super.didSelected()
cell?.valueTextField.becomeFirstResponder()
}
/// this call after common update for text attributes updating
open func updateCell() {
cell?.valueTextField.isEnabled = true
cell?.accessoryType = .none
cell?.selectionStyle = .none
}
/// Update text input settings. If you want to specialize you can override this
open func updateTextSettings() {
cell?.valueTextField.update(from: BxInputTextSettings.standart)
}
/// update cell from model data
override open func update()
{
super.update()
//
cell?.valueTextField.changeTarget(self, action: #selector(valueChanged(valueTextField:)), for: .editingChanged)
cell?.valueTextField.delegate = self
//
updateTextSettings()
updateCell()
}
/// resign value editing
@discardableResult
override open func resignFirstResponder() -> Bool {
return cell?.valueTextField.resignFirstResponder() ?? false
}
/// event when value is changed. Need reload this in inherited classes
@objc open func valueChanged(valueTextField: UITextField) {
// empty
}
// MARK - UITextFieldDelegate delegates
/// start editing
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool
{
if !isEnabled {
return false
}
if let owner = owner, owner.settings.isAutodissmissSelector {
owner.dissmissSelectors()
}
owner?.activeRow = row
owner?.activeControl = textField
return true
}
/// end editing
open func textFieldDidEndEditing(_ textField: UITextField)
{
if owner?.activeControl === textField {
owner?.activeControl = nil
}
if owner?.activeRow === row {
owner?.activeRow = nil
}
}
/// changing value event for correct showing
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if let text = textField.text,
range.location == text.chars.count && string == " "
{
textField.text = text + "\u{00a0}"
return false
}
return true
}
/// clear event, when user click clear button
open func textFieldShouldClear(_ textField: UITextField) -> Bool
{
textField.text = ""
return true
}
/// user click Done
open func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true
}
}
| mit |
nikHowlett/SurveySessions | SurveySession WatchKit 1 Extension/pickerFaceController.swift | 1 | 245 | //
// pickerFaceController.swift
// SurveySession
//
// Created by MAC-ATL019922 on 7/17/15.
// Copyright ยฉ 2015 nikhowlett. All rights reserved.
//
import WatchKit
import Foundation
class pickerFaceController: WKInterfaceController {
}
| mit |
nguyenantinhbk77/practice-swift | Views/TableViews/UITableViewCell Customization/UITableViewCell Customization/ViewController.swift | 3 | 522 | //
// ViewController.swift
// UITableViewCell Customization
//
// Created by Domenico on 07/06/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/08046-getselftypeforcontainer.swift | 11 | 281 | // 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 < {
struct A {
{
}
protocol A {
protocol A {
typealias e : a
func a
}
}
let f = 0.B : A : d: ( ( ( (f: A.c
| mit |
ryuichis/swift-ast | Tests/LexerTests/LexerTests.swift | 2 | 9964 | /*
Copyright 2015-2018 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
@testable import Lexer
@testable import Source
class LexerTests: XCTestCase {
func testEmptyContent() {
lexAndTest("") {
XCTAssertEqual($0, .eof)
}
}
func testArrow() {
lexAndTest("->") {
XCTAssertEqual($0, .arrow)
}
lexAndTest("->", index: 1, expectedColumn: 3) {
XCTAssertEqual($0, .eof)
}
}
func testAssignmentOperator() {
lexAndTest("=") {
XCTAssertEqual($0, .assignmentOperator)
}
lexAndTest("==") {
XCTAssertEqual($0, .prefixOperator("=="))
}
}
func testAt() {
lexAndTest("@") {
XCTAssertEqual($0, .at)
}
lexAndTest("@@") {
XCTAssertEqual($0, .at)
}
}
func testHash() {
lexAndTest("#") {
XCTAssertEqual($0, .hash)
}
lexAndTest("##") {
XCTAssertEqual($0, .hash)
}
}
func testBackslash() {
lexAndTest("\\") {
XCTAssertEqual($0, .backslash)
}
lexAndTest("\\.") {
XCTAssertEqual($0, .backslash)
}
}
func testColon() {
lexAndTest(":") {
XCTAssertEqual($0, .colon)
}
lexAndTest("::") {
XCTAssertEqual($0, .colon)
}
}
func testComma() {
lexAndTest(",") {
XCTAssertEqual($0, .comma)
}
lexAndTest(",,") {
XCTAssertEqual($0, .comma)
}
}
func testDot() {
lexAndTest(".") {
XCTAssertEqual($0, .dot)
}
lexAndTest("..") {
XCTAssertEqual($0, .prefixOperator(".."))
}
}
func testSemicolon() {
lexAndTest(";") {
XCTAssertEqual($0, .semicolon)
}
lexAndTest(";;") {
XCTAssertEqual($0, .semicolon)
}
}
func testUnderscore() {
lexAndTest("_") {
XCTAssertEqual($0, .underscore)
}
lexAndTest("_a") {
XCTAssertEqual($0, .identifier("_a", false))
}
}
func testLeftParen() {
lexAndTest("(") {
XCTAssertEqual($0, .leftParen)
}
lexAndTest("((") {
XCTAssertEqual($0, .leftParen)
}
}
func testRightParen() {
lexAndTest(")") {
XCTAssertEqual($0, .rightParen)
}
lexAndTest("))") {
XCTAssertEqual($0, .rightParen)
}
}
func testLeftBrace() {
lexAndTest("{") {
XCTAssertEqual($0, .leftBrace)
}
lexAndTest("{{") {
XCTAssertEqual($0, .leftBrace)
}
}
func testRightBrace() {
lexAndTest("}") {
XCTAssertEqual($0, .rightBrace)
}
lexAndTest("}}") {
XCTAssertEqual($0, .rightBrace)
}
}
func testLeftSquare() {
lexAndTest("[") {
XCTAssertEqual($0, .leftSquare)
}
lexAndTest("[[") {
XCTAssertEqual($0, .leftSquare)
}
}
func testRightSquare() {
lexAndTest("]") {
XCTAssertEqual($0, .rightSquare)
}
lexAndTest("]]") {
XCTAssertEqual($0, .rightSquare)
}
}
// TODO: have to come back to the tests for cr, lf, spaces, and eof
func testAllSpacesAreSkipped() {
lexAndTest(" ", expectedColumn: 10) {
XCTAssertEqual($0, .eof)
}
}
func testLineFeed() {
lexAndTest("a\n", index: 1, skipLineFeed: false, expectedColumn: 2) {
XCTAssertEqual($0, .lineFeed)
}
}
// TODO: Error cases
func testSegmentShowUpAtInvalidLocation() {
[
"\u{1}", // unsegmented
"\u{1DC7}", // identifier body
"\u{E01EE}" // operator body
].forEach { e in
lexAndTest(e) { t in
XCTAssertEqual(t, .invalid(.badChar))
}
}
}
func testEqutables() { // swift-lint:suppress(high_ncss)
XCTAssertTrue(Token.Kind.eof.isEqual(toKindOf: .eof))
XCTAssertTrue(Token.Kind.eof.isEqual(to: .eof))
XCTAssertTrue(Token.Kind.hash.isEqual(toKindOf: .hash))
XCTAssertTrue(Token.Kind.hash.isEqual(to: .hash))
XCTAssertTrue(Token.Kind.backslash.isEqual(toKindOf: .backslash))
XCTAssertTrue(Token.Kind.backslash.isEqual(to: .backslash))
XCTAssertTrue(Token.Kind.invalid(.unicodeLiteralExpected).isEqual(toKindOf: .invalid(.unicodeLiteralExpected)))
XCTAssertTrue(Token.Kind.invalid(.digitCharExpected).isEqual(toKindOf: .invalid(.closingBacktickExpected)))
XCTAssertTrue(Token.Kind.invalid(.badNumber).isEqual(to: .invalid(.badNumber)))
XCTAssertFalse(Token.Kind.invalid(.dotOperatorRequiresTwoDots).isEqual(to: .invalid(.identifierHeadExpected)))
XCTAssertTrue(Token.Kind.prefixOperator("๐").isEqual(toKindOf: .prefixOperator("๐")))
XCTAssertTrue(Token.Kind.prefixOperator("๐").isEqual(toKindOf: .prefixOperator("๐")))
XCTAssertTrue(Token.Kind.prefixOperator("๐").isEqual(to: .prefixOperator("๐")))
XCTAssertFalse(Token.Kind.prefixOperator("๐").isEqual(to: .prefixOperator("๐")))
XCTAssertTrue(Token.Kind.binaryOperator("๐").isEqual(toKindOf: .binaryOperator("๐")))
XCTAssertTrue(Token.Kind.binaryOperator("๐").isEqual(toKindOf: .binaryOperator("๐")))
XCTAssertTrue(Token.Kind.binaryOperator("๐").isEqual(to: .binaryOperator("๐")))
XCTAssertFalse(Token.Kind.binaryOperator("๐").isEqual(to: .binaryOperator("๐")))
XCTAssertTrue(Token.Kind.postfixOperator("๐").isEqual(toKindOf: .postfixOperator("๐")))
XCTAssertTrue(Token.Kind.postfixOperator("๐").isEqual(toKindOf: .postfixOperator("๐")))
XCTAssertTrue(Token.Kind.postfixOperator("๐").isEqual(to: .postfixOperator("๐")))
XCTAssertFalse(Token.Kind.postfixOperator("๐").isEqual(to: .postfixOperator("๐")))
XCTAssertTrue(Token.Kind.identifier("๐", false).isEqual(toKindOf: .identifier("๐", false)))
XCTAssertTrue(Token.Kind.identifier("๐", true).isEqual(toKindOf: .identifier("๐", true)))
XCTAssertTrue(Token.Kind.identifier("๐", false).isEqual(to: .identifier("๐", false)))
XCTAssertFalse(Token.Kind.identifier("๐", false).isEqual(to: .identifier("๐", false)))
XCTAssertTrue(Token.Kind.implicitParameterName(1).isEqual(toKindOf: .implicitParameterName(1)))
XCTAssertTrue(Token.Kind.implicitParameterName(2).isEqual(toKindOf: .implicitParameterName(3)))
XCTAssertTrue(Token.Kind.implicitParameterName(4).isEqual(to: .implicitParameterName(4)))
XCTAssertFalse(Token.Kind.implicitParameterName(5).isEqual(to: .implicitParameterName(6)))
XCTAssertTrue(
Token.Kind.integerLiteral(1, rawRepresentation: "2").isEqual(to:
.integerLiteral(1, rawRepresentation: "2")))
XCTAssertFalse(
Token.Kind.integerLiteral(1, rawRepresentation: "2").isEqual(to:
.integerLiteral(2, rawRepresentation: "2")))
XCTAssertFalse(
Token.Kind.integerLiteral(1, rawRepresentation: "1").isEqual(to:
.integerLiteral(1, rawRepresentation: "2")))
XCTAssertTrue(
Token.Kind.floatingPointLiteral(1, rawRepresentation: "2").isEqual(to:
.floatingPointLiteral(1, rawRepresentation: "2")))
XCTAssertFalse(
Token.Kind.floatingPointLiteral(1, rawRepresentation: "2").isEqual(to:
.floatingPointLiteral(2, rawRepresentation: "2")))
XCTAssertFalse(
Token.Kind.floatingPointLiteral(1, rawRepresentation: "1").isEqual(to:
.floatingPointLiteral(1, rawRepresentation: "2")))
XCTAssertTrue(
Token.Kind.staticStringLiteral("1", rawRepresentation: "2").isEqual(to:
.staticStringLiteral("1", rawRepresentation: "2")))
XCTAssertFalse(
Token.Kind.staticStringLiteral("1", rawRepresentation: "2").isEqual(to:
.staticStringLiteral("2", rawRepresentation: "2")))
XCTAssertFalse(
Token.Kind.staticStringLiteral("1", rawRepresentation: "1").isEqual(to:
.staticStringLiteral("1", rawRepresentation: "2")))
XCTAssertTrue(
Token.Kind.interpolatedStringLiteralHead("1", rawRepresentation: "2").isEqual(to:
.interpolatedStringLiteralHead("1", rawRepresentation: "2")))
XCTAssertFalse(
Token.Kind.interpolatedStringLiteralHead("1", rawRepresentation: "2").isEqual(to:
.interpolatedStringLiteralHead("2", rawRepresentation: "2")))
XCTAssertFalse(
Token.Kind.interpolatedStringLiteralHead("1", rawRepresentation: "1").isEqual(to:
.interpolatedStringLiteralHead("1", rawRepresentation: "2")))
XCTAssertTrue(Token.Kind.booleanLiteral(true).isEqual(toKindOf: .booleanLiteral(true)))
XCTAssertTrue(Token.Kind.booleanLiteral(true).isEqual(toKindOf: .booleanLiteral(false)))
XCTAssertTrue(Token.Kind.booleanLiteral(false).isEqual(to: .booleanLiteral(false)))
XCTAssertFalse(Token.Kind.booleanLiteral(false).isEqual(to: .booleanLiteral(true)))
}
static var allTests = [
("testEmptyContent", testEmptyContent),
("testArrow", testArrow),
("testAssignmentOperator", testAssignmentOperator),
("testAt", testAt),
("testHash", testHash),
("testBackslash", testBackslash),
("testColon", testColon),
("testComma", testComma),
("testDot", testDot),
("testSemicolon", testSemicolon),
("testUnderscore", testUnderscore),
("testLeftParen", testLeftParen),
("testRightParen", testRightParen),
("testLeftBrace", testLeftBrace),
("testRightBrace", testRightBrace),
("testLeftSquare", testLeftSquare),
("testRightSquare", testRightSquare),
("testAllSpacesAreSkipped", testAllSpacesAreSkipped),
("testLineFeed", testLineFeed),
("testSegmentShowUpAtInvalidLocation", testSegmentShowUpAtInvalidLocation),
("testEqutables", testEqutables),
]
}
| apache-2.0 |
tbajis/Bop | Bop/SegueHandlerType.swift | 1 | 952 | //
// SegueHandlerType.swift
// Bop
//
// Created by Thomas Manos Bajis on 5/19/17.
// Copyright ยฉ 2017 Thomas Manos Bajis. All rights reserved.
//
import Foundation
import UIKit
// MARK: SegueHandlerType (Protocol)
protocol SegueHandlerType {
associatedtype SegueIdentifier: RawRepresentable
}
// MARK: - SegueHandlerType (Protocol Extension)
extension SegueHandlerType where Self: UIViewController, SegueIdentifier.RawValue == String {
func performSegue(withIdentifier identifier: SegueIdentifier, sender: Any?) {
performSegue(withIdentifier: identifier.rawValue, sender: sender)
}
func segueIdentifierForSegue(segue: UIStoryboardSegue) -> SegueIdentifier {
guard let identifier = segue.identifier, let segueIdentifier = SegueIdentifier(rawValue: identifier) else {
fatalError("Invalid segue identifier: \(segue.identifier).")
}
return segueIdentifier
}
}
| apache-2.0 |
AlexMcArdle/LooseFoot | LooseFoot/AppDelegate.swift | 1 | 10416 | //
// AppDelegate.swift
// LooseFoot
//
// Created by Alexander McArdle on 1/22/17.
// Copyright ยฉ 2017 Alexander McArdle. All rights reserved.
//
import UserNotifications
import UIKit
import reddift
import ChameleonFramework
import FPSCounter
import Firebase
/// Posted when the OAuth2TokenRepository object succeed in saving a token successfully into Keychain.
public let OAuth2TokenRepositoryDidSaveToken = "OAuth2TokenRepositoryDidSaveToken"
/// Posted when the OAuth2TokenRepository object failed to save a token successfully into Keychain.
public let OAuth2TokenRepositoryDidFailToSaveToken = "OAuth2TokenRepositoryDidFailToSaveToken"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//FPSCounter.showInStatusBar(UIApplication.shared)
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.black
registerForPushNotifications(application: application)
FIRApp.configure()
Chameleon.setGlobalThemeUsingPrimaryColor(UIColor.flatBlackDark, with: .contrast)
let nav = CustomNavigationController(navigationBarClass: AMNavigationBar.self, toolbarClass: AMToolbar.self)
//let nav = CustomNavigationController(navigationBarClass: CustomNavigationBar.self, toolbarClass: nil)
//nav.pushViewController(AMSubredditViewController(subreddit: "powerlanguagetest", firstRun: true), animated: true)
nav.pushViewController(AMSubredditViewController(firstRun: true), animated: true)
//window?.rootViewController = AMHomeViewController()
window?.rootViewController = nav
window?.makeKeyAndVisible()
// [START add_token_refresh_observer]
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: .firInstanceIDTokenRefresh,
object: nil)
// [END add_token_refresh_observer]
return true
}
func registerForPushNotifications(application: UIApplication) {
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
// [START register_for_notifications]
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// [END register_for_notifications]
}
func application(_ app: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
print("url: \(url)")
return OAuth2Authorizer.sharedInstance.receiveRedirect(url, completion: {(result) -> Void in
switch result {
case .failure(let error):
print(error)
case .success(let token):
DispatchQueue.main.async(execute: { () -> Void in
do {
try OAuth2TokenRepository.save(token: token, of: token.name)
NotificationCenter.default.post(name: Notification.Name(rawValue: OAuth2TokenRepositoryDidSaveToken), object: nil, userInfo: nil)
debugPrint(token)
} catch {
NotificationCenter.default.post(name: Notification.Name(rawValue: OAuth2TokenRepositoryDidFailToSaveToken), object: nil, userInfo: nil)
print(error)
}
})
}
})
}
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
// [START refresh_token]
func tokenRefreshNotification(_ notification: Notification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
// [END refresh_token]
// [START connect_to_fcm]
func connectToFcm() {
// Won't connect since there is no token
guard FIRInstanceID.instanceID().token() != nil else {
return;
}
// Disconnect previous FCM connection if it exists.
FIRMessaging.messaging().disconnect()
FIRMessaging.messaging().connect { (error) in
if error != nil {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
// [END connect_to_fcm]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
// [START connect_on_active]
func applicationDidBecomeActive(_ application: UIApplication) {
connectToFcm()
}
// [END connect_on_active]
// [START disconnect_from_fcm]
func applicationDidEnterBackground(_ application: UIApplication) {
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
// [END disconnect_from_fcm]
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 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 applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
}
// [END ios_10_message_handling]
// [START ios_10_data_message_handling]
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices while app is in the foreground.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print(remoteMessage.appData)
}
}
// [END ios_10_data_message_handling]
| gpl-3.0 |
gottesmm/swift | test/DebugInfo/generic_args.swift | 3 | 2220 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -primary-file %s -emit-ir -verify -g -o - | %FileCheck %s
func markUsed<T>(_ t: T) {}
protocol AProtocol {
func f() -> String
}
class AClass : AProtocol {
func f() -> String { return "A" }
}
class AnotherClass : AProtocol {
func f() -> String { return "B" }
}
// CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_T012generic_args9aFunction{{.*}}D",{{.*}} elements: ![[PROTOS:[0-9]+]]
// CHECK-DAG: ![[PROTOS]] = !{![[INHERIT:.*]]}
// CHECK-DAG: ![[INHERIT]] = !DIDerivedType(tag: DW_TAG_inheritance,{{.*}} baseType: ![[PROTOCOL:[0-9]+]]
// CHECK-DAG: ![[PROTOCOL]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_T012generic_args9AProtocol_pmD",
// CHECK-DAG: !DILocalVariable(name: "x", arg: 1,{{.*}} type: ![[T:.*]])
// CHECK-DAG: ![[T]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_T012generic_args9aFunction
// CHECK-DAG: !DILocalVariable(name: "y", arg: 2,{{.*}} type: ![[Q:.*]])
// CHECK-DAG: ![[Q]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_T012generic_args9aFunction
func aFunction<T : AProtocol, Q : AProtocol>(_ x: T, _ y: Q, _ z: String) {
markUsed("I am in \(z): \(x.f()) \(y.f())")
}
aFunction(AClass(),AnotherClass(),"aFunction")
struct Wrapper<T: AProtocol> {
init<U: AProtocol>(from : Wrapper<U>) {
// CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "Wrapper",{{.*}} identifier: "_T012generic_args7WrapperVyAcCyxGACyqd__G4from_tcAA9AProtocolRd__lufcQq_GD")
var wrapped = from
wrapped = from
_ = wrapped
}
func passthrough(_ t: T) -> T {
// The type of local should have the context Wrapper<T>.
// CHECK-DAG: ![[WRAPPER:.*]] = !DICompositeType({{.*}}identifier: "_T012generic_args7WrapperVQq_D")
// CHECK-DAG: !DILocalVariable(name: "local",{{.*}} line: [[@LINE+1]],{{.*}} type: ![[WRAPPER]]
var local = t
local = t
return local
}
}
// CHECK-DAG: ![[FNTY:.*]] = !DICompositeType({{.*}}identifier: "_T012generic_args5applyq_x_q_xc1ftr0_lFQq_AaBq_x_q_xcACtr0_lFQq0_Ixir_D"
// CHECK-DAG: !DILocalVariable(name: "f", {{.*}}, line: [[@LINE+1]], type: ![[FNTY]])
func apply<T, U> (_ x: T, f: (T) -> (U)) -> U {
return f(x)
}
| apache-2.0 |
Superkazuya/zimcher2015 | Zimcher/Constants/Palette.swift | 1 | 647 | import UIKit
extension UIColor
{
convenience init(r: UInt8, g: UInt8, b: UInt8) {
self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: 1)
}
}
struct PALETTE {
static let BLUE = UIColor(red: 96/256.0, green: 111/256.0, blue: 214/256.0, alpha: 1)
static let DARK_BLUE = UIColor(red: 22/256.0, green: 24/256.0, blue: 45/256.0, alpha: 1)
static let SLATE_BLUE = UIColor(red: 95/256.0, green: 108/256.0, blue: 217/256.0, alpha: 1)
static let CORN_FLOWER_BLUE = UIColor(red: 95/256.0, green: 108/256.0, blue: 217/256.0, alpha: 1)
static let WARM_GARY = UIColor(r: 145, g: 145, b: 145)
} | apache-2.0 |
gaoleegin/SwiftLianxi | Newfeatureๆฐ็นๆง็้ข็่ฎพ่ฎก/Newfeatureๆฐ็นๆง็้ข็่ฎพ่ฎก/AppDelegate.swift | 1 | 2168 | //
// AppDelegate.swift
// Newfeatureๆฐ็นๆง็้ข็่ฎพ่ฎก
//
// Created by ้ซๆๅ on 15/10/22.
// Copyright ยฉ 2015ๅนด LJLianXi. 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:.
}
}
| apache-2.0 |
AzAli71/AZGradientView | AZGradientViewSample/AZGradientViewSample/classes/AZVerticalGradientView.swift | 1 | 814 | //
// AZVerticalGradientView.swift
// AZGradientViewSample
//
// Created by Ali on 8/28/17.
// Copyright ยฉ 2017 Ali Azadeh. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable final class AZVerticalGradientView: AZGradientView {
@IBInspectable var topColor: UIColor = UIColor.clear
@IBInspectable var bottomColor: UIColor = UIColor.clear
override func draw(_ rect: CGRect) {
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = CGRect(x: CGFloat(0),
y: CGFloat(0),
width: self.frame.size.width,
height: self.frame.size.height)
gradient.colors = [topColor.cgColor, bottomColor.cgColor]
layer.addSublayer(gradient)
}
}
| mit |
baiIey/events-and-states | Carousel/Carousel/GetStartedViewController.swift | 1 | 1552 | //
// GetStartedViewController.swift
// Carousel
//
// Created by Brian Bailey on 2/15/15.
// Copyright (c) 2015 i had that dream again. All rights reserved.
//
import UIKit
class GetStartedViewController: UIViewController {
@IBOutlet weak var viewButton: UIButton!
@IBOutlet weak var timeWheelButton: UIButton!
@IBOutlet weak var shareButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func xButtonDidPress(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func viewButtonDidPress(sender: AnyObject) {
viewButton.selected = !viewButton.selected
}
@IBAction func timeWheelButtonDidPress(sender: AnyObject) {
timeWheelButton.selected = !timeWheelButton.selected
}
@IBAction func shareButtonDidPress(sender: AnyObject) {
shareButton.selected = !shareButton.selected
}
}
| mit |
Eonil/ClangWrapper.Swift | ClangWrapper/TranslationUnit.swift | 2 | 1210 | //
// TranslationUnit.swift
// ClangWrapper
//
// Created by Hoon H. on 2015/01/21.
// Copyright (c) 2015 Eonil. All rights reserved.
//
public struct TranslationUnit: TrackableRemoteObjectProxy {
public func dispose() {
index.allTranslationUnits.untrack(self)
clang_disposeTranslationUnit(raw)
debugLog("clang_disposeTranslationUnit")
}
/// Eonil:
/// `TranslationUnit.cursor.spelling` returns file path of the unit.
public var cursor:Cursor {
get {
return Cursor(index: index, raw: clang_getTranslationUnitCursor(raw))
}
}
////
public var numberOfDiagnostics:UInt32 {
get {
return clang_getNumDiagnostics(raw)
}
}
public func diagnosticAtIndex(index:UInt32) -> Diagnostic {
let dptr = clang_getDiagnostic(raw, index)
return Diagnostic(index: self.index, raw: dptr)
}
////
let index:UnmanagedIndexRef
let raw:CXTranslationUnit
init(index:UnmanagedIndexRef, raw:CXTranslationUnit) {
self.index = index
self.raw = raw
index.allTranslationUnits.track(self)
}
}
extension TranslationUnit {
public var diagnostics:[Diagnostic] {
get {
return (0..<numberOfDiagnostics).map { i in
return self.diagnosticAtIndex(i)
}
}
}
}
| mit |
cherrywoods/swift-meta-serialization | Tests/General Tests/StandardBehavior.swift | 1 | 7056 | //
// StandardBehavior.swift
// MetaSerialization
//
// Copyright 2018 cherrywoods
//
// 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.
//
// the test cases in this file are the same as the JSONEncoder tests in the file TestJSONEncoder from swift (see README).
// Those tests are licensed under the Apache License v2.0 with Runtime Library Exception (Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors)
import XCTest
import Quick
import Nimble
@testable import MetaSerialization
struct StandardBehavior<S: Serialization> where S.Raw: Equatable {
let serialization: S
// keys for expected:
// empty, empty unkeyed,
// Switch.on, Switch.off, Timestamp, Counter, EnhancedBool.true, EnhancedBool.false, EnhancedBool.fileNotFound
// wrapped(_one_of_the_above_),
// Address, Person,
// Numbers, Mapping,
// Company,
// Button,
// Employee,
// CoffeeDrinker,
func test(expected: [String : S.Raw], allowTopLevelSingleValues allowTLSV: Bool, allowNestedContainers allowNC: Bool, allowNils: Bool) {
describe("emptys") {
testSingle("empty struct", value: EmptyStruct(), expected: expected["empty"])
testSingle("empty class", value: EmptyClass(), expected: expected["empty"])
}
describe("top level singles") {
failOrSucceed(succeed: allowTLSV, "Switch.on", value: Switch.on, expected: expected["Switch.on"])
failOrSucceed(succeed: allowTLSV, "Switch.off", value: Switch.off, expected: expected["Switch.off"])
failOrSucceed(succeed: allowTLSV, "Timestamp", value: Timestamp(3141592653), expected: expected["Timestamp"])
failOrSucceed(succeed: allowTLSV, "Counter", value: Counter(), expected: expected["Counter"])
failOrSucceed(succeed: allowTLSV, "EnhancedBool.true", value: EnhancedBool.true, expected: expected["EnhancedBool.true"])
failOrSucceed(succeed: allowTLSV, "EnhancedBool.false", value: EnhancedBool.false, expected: expected["EnhancedBool.false"])
failOrSucceed(succeed: allowTLSV && allowNils, "EnhancedBool.fileNotFound", value: EnhancedBool.fileNotFound, expected: expected["EnhancedBool.fileNotFound"])
}
describe("wrapped top level singles") {
testSingle("wrapped Switch.on", value: TopLevelWrapper(Switch.on), expected: expected["wrapped(Switch.on)"])
testSingle("wrapped Switch.off", value: TopLevelWrapper(Switch.off), expected: expected["wrapped(Switch.off)"])
testSingle("wrapped Timestamp", value: TopLevelWrapper(Timestamp(3141592653)), expected: expected["wrapped(Timestamp)"])
testSingle("wrapped Counter", value: TopLevelWrapper(Counter()), expected: expected["wrapped(Counter)"])
testSingle("wrapped EnhancedBool.true", value: TopLevelWrapper(EnhancedBool.true), expected: expected["wrapped(EnhancedBool.true)"])
testSingle("wrapped EnhancedBool.false", value: TopLevelWrapper(EnhancedBool.false), expected: expected["wrapped(EnhancedBool.false)"])
failOrSucceed(succeed: allowNils, "wrapped EnhancedBool.fileNotFound", value: TopLevelWrapper(EnhancedBool.fileNotFound), expected: expected["wrapped(EnhancedBool.fileNotFound)"])
}
describe("top level structured types") {
testSingle("Address", value: Address.testValue, expected: expected["Address"])
testSingle("Person", value: Person.testValue, expected: expected["Person"])
}
describe("structures type though single value container") {
testSingle("Number", value: Numbers.testValue, expected: expected["Numbers"])
failOrSucceed(succeed: allowNils, "Mapping", value: Mapping.testValue, expected: expected["Mapping"])
}
describe("deep structured class") {
failOrSucceed(succeed: allowNC, "company", value: Company.testValue, expected: expected["Company"])
}
describe("deep nested class") {
failOrSucceed(succeed: allowNC, "button", value: Button.testValue, expected: expected["Button"])
}
describe("class sharing encoder with super") {
testSingle("employee", value: Employee.testValue, expected: expected["Employee"])
}
describe("class using super encoder") {
failOrSucceed(succeed: allowNC, "coffee drinker", value: CoffeeDrinker.testValue, expected: expected["CoffeeDrinker"])
}
describe("encoder features") {
// these tests can't work if nested containers aren't allowed
if allowNC {
it("does nested container coding paths right") {
_ = TestUtilities.encode(NestedContainersTestType(), using: self.serialization)
}
it("does super encoder coding paths right") {
_ = TestUtilities.encode(NestedContainersTestType(testSuperEncoder: true), using: self.serialization)
}
}
}
it("allows requesting equal containers multiple times") {
_ = TestUtilities.encode(MultipleContainerRequestsType(), using: self.serialization, expected: expected["empty unkeyed"])
}
}
func failOrSucceed<T: Codable&Equatable>(succeed allowed: Bool, _ description: String, value: T, expected: S.Raw?) {
if allowed {
testSingle(description, value: value, expected: expected)
} else {
// expect encoding failure
it("encoding " + description + " fails") {
TestUtilities.encodeFails(value, using: self.serialization)
}
}
}
func testSingle<T: Codable&Equatable>(_ description: String, value: T, expected: S.Raw?) {
it("round trips " + description) {
TestUtilities.roundTrip(value, using: self.serialization, expected: expected)
}
}
}
| apache-2.0 |
gribozavr/swift | test/Sanitizers/asan_recover.swift | 1 | 4908 | // REQUIRES: executable_test
// REQUIRES: asan_runtime
// UNSUPPORTED: windows
// Check with recovery instrumentation and runtime option to continue execution.
// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=address -sanitize-recover=address -import-objc-header %S/asan_interface.h -emit-ir -o %t.asan_recover.ll
// RUN: %FileCheck -check-prefix=CHECK-IR -input-file=%t.asan_recover.ll %s
// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=address -sanitize-recover=address -import-objc-header %S/asan_interface.h -o %t_asan_recover
// RUN: %target-codesign %t_asan_recover
// RUN: env %env-ASAN_OPTIONS=halt_on_error=0 %target-run %t_asan_recover > %t_asan_recover.stdout 2> %t_asan_recover.stderr
// RUN: %FileCheck --check-prefixes=CHECK-COMMON-STDERR,CHECK-RECOVER-STDERR -input-file=%t_asan_recover.stderr %s
// RUN: %FileCheck --check-prefixes=CHECK-COMMON-STDOUT,CHECK-RECOVER-STDOUT -input-file=%t_asan_recover.stdout %s
// Check with recovery instrumentation but without runtime option to continue execution.
// RUN: env %env-ASAN_OPTIONS=abort_on_error=0,halt_on_error=1 not %target-run %t_asan_recover > %t_asan_no_runtime_recover.stdout 2> %t_asan_no_runtime_recover.stderr
// RUN: %FileCheck --check-prefixes=CHECK-COMMON-STDERR -input-file=%t_asan_no_runtime_recover.stderr %s
// RUN: %FileCheck --check-prefixes=CHECK-COMMON-STDOUT,CHECK-NO-RECOVER-STDOUT -input-file=%t_asan_no_runtime_recover.stdout %s
// Check that without recovery instrumentation and runtime option to continue execution that error recovery does not happen.
// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=address -import-objc-header %S/asan_interface.h -o %t_asan_no_recover
// RUN: %target-codesign %t_asan_no_recover
// RUN: env %env-ASAN_OPTIONS=abort_on_error=0,halt_on_error=0 not %target-run %t_asan_no_recover > %t_asan_no_recover.stdout 2> %t_asan_no_recover.stderr
// RUN: %FileCheck --check-prefixes=CHECK-COMMON-STDERR -input-file=%t_asan_no_recover.stderr %s
// RUN: %FileCheck --check-prefixes=CHECK-COMMON-STDOUT,CHECK-NO-RECOVER-STDOUT -input-file=%t_asan_no_recover.stdout %s
// We need to test reads via instrumentation not via runtime so try to check
// for calls to unwanted interceptor/runtime functions.
// CHECK-IR-NOT: call {{.+}} @__asan_memcpy
// CHECK-IR-NOT: call {{.+}} @memcpy
// FIXME: We need this so we can flush stdout but this won't
// work on other Platforms (e.g. Windows).
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
// CHECK-COMMON-STDOUT: START
print("START")
fflush(stdout)
let size:Int = 128;
func foo(_ rawptr:UnsafeMutablePointer<UInt8>) {
print("Read second element:\(rawptr.advanced(by: 1).pointee)")
fflush(stdout)
}
// In this test we need multiple issues to occur that ASan can detect.
// Allocating a buffer and artificially poisoning it seems like the best way to
// test this because there's no undefined behavior happening. Hopefully this
// means that the program behaviour after ASan catches an issue should be
// consistent. If we did something different like two use-after-free issues the
// behaviour could be very unpredicatable resulting in a flakey test.
var x = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
x.initialize(repeating: 0, count: size)
__asan_poison_memory_region(UnsafeMutableRawPointer(x), size)
// Perform accesses that ASan will catch. Note it is important here that
// the reads are performed **in** the instrumented code so that the
// instrumentation catches the access to poisoned memory. I tried doing:
//
// ```
// var x = x.advanced(by: 0).pointee
// print(x)
// ```
//
// However, this generated code that called into memcpy rather than performing
// a direct read which meant that ASan caught an issue via its interceptors
// rather than from instrumentation, which does not test the right thing here.
//
// Doing:
//
// ```
// print("Read first element:\(x.advanced(by: 0).pointee)")
// ```
//
// seems to do the right thing right now but this seems really fragile.
// First error
// NOTE: Testing for stackframe `#0` should ensure that the poison read
// happened in instrumentation and not in an interceptor.
// CHECK-COMMON-STDERR: AddressSanitizer: use-after-poison
// CHECK-COMMON-STDERR: #0 0x{{.+}} in main{{.*}}
print("Read first element:\(x.advanced(by: 0).pointee)")
fflush(stdout)
// CHECK-RECOVER-STDOUT: Read first element:0
// Second error
// NOTE: Very loose regex is to accomodate if name demangling
// fails. rdar://problem/57235673
// CHECK-RECOVER-STDERR: AddressSanitizer: use-after-poison
// CHECK-RECOVER-STDERR: #0 0x{{.+}} in {{.*}}foo{{.*}}
// CHECK-RECOVER-STDOUT: Read second element:0
foo(x)
__asan_unpoison_memory_region(UnsafeMutableRawPointer(x), size)
x.deallocate();
// CHECK-NO-RECOVER-STDOUT-NOT: DONE
// CHECK-RECOVER-STDOUT: DONE
print("DONE")
fflush(stdout)
| apache-2.0 |
rmirabelli/UofD-Fall2017 | RecipieReader/RecipieReader/TableViewController.swift | 1 | 1991 | //
// ViewController.swift
// RecipieReader
//
// Created by Russell Mirabelli on 9/26/17.
// Copyright ยฉ 2017 Russell Mirabelli. All rights reserved.
//
import UIKit
class TableViewController: UIViewController {
var recipies: [Recipie] = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.dataSource = self
fetchData()
}
func fetchData() {
let url = URL(string: "https://git.io/vdtMM")!
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, err) in
let data = data!
let json = try! JSONSerialization.jsonObject(with: data, options: [])
let array = json as! [[String: Any]]
self.recipies = array.map { Recipie(dictionary: $0) }
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
task.resume()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let destination = segue.destination as? RecipieViewController else { return }
guard let source = sender as? RecipieCell else { return }
destination.recipie = source.recipie
}
}
extension TableViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let recipie = recipies[indexPath.item]
let cell = tableView.dequeueReusableCell(withIdentifier: "RecipieCell", for: indexPath) as! RecipieCell
cell.recipie = recipie
return cell
}
}
| mit |
i-schuetz/clojushop_client_ios_swift | clojushop_client_ios/BaseViewController.swift | 1 | 1909 | //
// BaseViewController.swift
//
// Created by ischuetz on 07/06/2014.
// Copyright (c) 2014 ivanschuetz. All rights reserved.
//
import Foundation
class BaseViewController: UIViewController {
var opaqueIndicator: ProgressIndicator!
var transparentIndicator: ProgressIndicator!
init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
func getProgressBarBounds() -> CGRect {
var bounds:CGRect = UIScreen.mainScreen().bounds
let viewSize = self.tabBarController.view.frame.size
let tabBarSize = self.tabBarController.tabBar.frame.size
bounds.size.height = viewSize.height - tabBarSize.height
return bounds
}
func initProgressIndicator() {
self.opaqueIndicator = ProgressIndicator(frame: getProgressBarBounds(), backgroundColor: UIColor.whiteColor())
self.transparentIndicator = ProgressIndicator(frame: getProgressBarBounds(), backgroundColor: UIColor.clearColor())
self.view.addSubview(opaqueIndicator)
self.view.addSubview(transparentIndicator)
self.setProgressHidden(true, transparent: true)
self.setProgressHidden(true, transparent: false)
}
override func viewDidLoad() {
self.initProgressIndicator()
}
override func shouldAutorotate() -> Bool {
return true //iOS 5- compatibility
}
override func viewWillUnload() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func setProgressHidden(hidden: Bool, transparent: Bool) {
let indicator = transparent ? transparentIndicator : opaqueIndicator
indicator.hidden = hidden
}
func setProgressHidden(hidden: Bool) {
self.setProgressHidden(hidden, transparent: false)
}
} | apache-2.0 |
ReSwift/ReSwift-Todo-Example | ReSwift-Todo/ToDo.swift | 1 | 1987 | //
// ToDo.swift
// ReSwift-Todo
//
// Created by Christian Tietze on 30/01/16.
// Copyright ยฉ 2016 ReSwift. All rights reserved.
//
import Foundation
enum Completion {
case unfinished
case finished(when: Date?)
var isFinished: Bool {
switch self {
case .unfinished: return false
case .finished: return true
}
}
var date: Date? {
switch self {
case .unfinished: return nil
case .finished(when: let date): return date
}
}
}
struct ToDo {
static var empty: ToDo { return ToDo(title: "New Task") }
let toDoID: ToDoID
var title: String
var completion: Completion
var tags: Set<String>
var isFinished: Bool { return completion.isFinished }
var finishedAt: Date? { return completion.date }
init(toDoID: ToDoID = ToDoID(), title: String, tags: Set<String> = Set(), completion: Completion = .unfinished) {
self.toDoID = toDoID
self.title = title
self.completion = completion
self.tags = tags
}
}
// MARK: ToDo (sub)type equatability
extension ToDo: Equatable {
/// Equality check ignoring the `ToDoID`.
func hasEqualContent(_ other: ToDo) -> Bool {
return title == other.title && completion == other.completion && tags == other.tags
}
}
func ==(lhs: ToDo, rhs: ToDo) -> Bool {
return lhs.toDoID == rhs.toDoID && lhs.title == rhs.title && lhs.completion == rhs.completion && lhs.tags == rhs.tags
}
extension Completion: Equatable { }
func ==(lhs: Completion, rhs: Completion) -> Bool {
switch (lhs, rhs) {
case (.unfinished, .unfinished): return true
case let (.finished(when: lDate), .finished(when: rDate)):
return {
switch (lDate, rDate) {
case (.none, .none): return true
case let (.some(lhs), .some(rhs)): return (lhs == rhs)
default: return false
}
}()
default: return false
}
}
| mit |
VivaReal/Compose | Compose/Classes/Extensions/UIKit/UIEdgeInsets+Insets.swift | 1 | 1759 | //
// UIEdgeInsets+Insets.swift
// Compose
//
// Created by Bruno Bilescky on 04/10/16.
// Copyright ยฉ 2016 VivaReal. All rights reserved.
//
import UIKit
/**
Adding simple inits to help create insets
*/
public extension UIEdgeInsets {
/// Init with optional values. If any value is not provided, it will be treated as `0`
///
/// - parameter top: top inset
/// - parameter leading: left inset
/// - parameter bottom: bottom inset
/// - parameter trailing: right inset
public init(top: CGFloat = 0, leading: CGFloat = 0, bottom: CGFloat = 0, trailing: CGFloat = 0) {
self = UIEdgeInsets(top: top, left: leading, bottom: bottom, right: trailing)
}
/// Init with same value for Left/Right and also 0 for Top/Bottom
///
/// - parameter horizontal: value to use for `left` and `right`
public init(horizontal: CGFloat) {
self = UIEdgeInsets(top: 0, left: horizontal, bottom: 0, right: horizontal)
}
/// Init with same value for Top/Bottom and also 0 for Left/Right
///
/// - parameter vertical: value to use for `Top` and `Bottom`
public init(vertical: CGFloat) {
self = UIEdgeInsets(top: vertical, left: 0, bottom: vertical, right: 0)
}
/// Init with same value for all insets
///
/// - parameter all: value to use for all insets
public init(_ all: CGFloat) {
self = UIEdgeInsets(top: all, left: all, bottom: all, right: all)
}
/// Sum for `Left` and 'Right` insets
public var horizontalInsets: CGFloat {
return self.left + self.right
}
/// Sum for `Top` and 'Bottom` insets
public var verticalInsets: CGFloat {
return self.top + self.bottom
}
}
| mit |
icelemon1989/Tipper | SettingsViewController.swift | 1 | 2883 | //
// SettingsViewController.swift
// Tipper
//
// Created by Yang Ruan on 9/29/15.
// Copyright ยฉ 2015 Yang Ji. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var defaultTipControl: UISegmentedControl!
@IBOutlet weak var switchValue: UISwitch!
//Set dark color theme
@IBAction func turnSwitch(sender: UISwitch) {
updateDefaultColor()
}
func updateDefaultColor() {
//save the default color
let defaultDarkSetting = NSUserDefaults.standardUserDefaults()
if switchValue.on {
defaultDarkSetting.setBool(true, forKey: "Default_Dark_Setting")
} else {
defaultDarkSetting.setBool(false, forKey: "Default_Dark_Setting")
}
}
func updateDefaulTip() {
// Save the default tip percentage
let tipDefault = NSUserDefaults.standardUserDefaults()
tipDefault.setInteger(defaultTipControl.selectedSegmentIndex, forKey: "default_tip_segment_index")
tipDefault.synchronize()
}
override func viewDidLoad() {
super.viewDidLoad()
//change the navigationbar tint color
self.navigationController?.navigationBar.tintColor = UIColor(red: 247/255, green: 0, blue: 148/255, alpha: 1)
// Initialize the view with the current default tip percentage
let tipDefault = NSUserDefaults.standardUserDefaults()
let defaultTipSegmentIndex = tipDefault.integerForKey("default_tip_segment_index")
defaultTipControl.selectedSegmentIndex = defaultTipSegmentIndex
//Initialize the swtich with current default switch
let colorDefault = NSUserDefaults.standardUserDefaults()
if colorDefault.boolForKey("Default_Dark_Setting") {
switchValue.setOn(true, animated: false)
} else {
switchValue.setOn(false, animated: false)
}
}
override func viewWillDisappear(animated: Bool) {
updateDefaulTip()
updateDefaultColor()
super.viewWillDisappear(animated)
}
@IBAction func defaultTipControlChange(sender: UISegmentedControl) {
//update default tip control
updateDefaulTip()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
KaushalElsewhere/AllHandsOn | IGListDemo/IGListDemo/DataLoader.swift | 1 | 1217 | //
// DataLoader.swift
// IGListDemo
//
// Created by Kaushal Elsewhere on 20/01/2017.
// Copyright ยฉ 2017 Kaushal Elsewhere. All rights reserved.
//
import UIKit
class DataLoader: NSObject {
static func readFeedItems() -> [FeedItem]? {
return getFeedFromJSON("feed")
}
static func readAnychanges() -> [FeedItem]? {
return getFeedFromJSON("changes")
}
static func getFeedFromJSON(filename: String) -> [FeedItem]? {
if let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json") {
do {
let data = try NSData(contentsOfURL: NSURL(fileURLWithPath: path), options: NSDataReadingOptions.DataReadingMappedIfSafe)
let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! [String : AnyObject]
let response = FeedResponse(JSON: jsonData )
return response?.data
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
} else {
print("Invalid filename/path.")
return nil
}
}
} | mit |
ahoppen/swift | test/SILGen/dynamically_replaceable.swift | 21 | 19528 | // RUN: %target-swift-emit-silgen -swift-version 5 %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -swift-version 5 %s -enable-implicit-dynamic | %FileCheck %s --check-prefix=IMPLICIT
// RUN: %target-swift-emit-silgen -swift-version 5 %s -disable-previous-implementation-calls-in-dynamic-replacements | %FileCheck %s --check-prefix=NOPREVIOUS
// CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable014maybe_dynamic_B0yyF : $@convention(thin) () -> () {
// IMPLICIT-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable014maybe_dynamic_B0yyF : $@convention(thin) () -> () {
func maybe_dynamic_replaceable() {
}
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable08dynamic_B0yyF : $@convention(thin) () -> () {
dynamic func dynamic_replaceable() {
}
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV1xACSi_tcfC : $@convention(method) (Int, @thin Strukt.Type) -> Strukt
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV08dynamic_B0yyF : $@convention(method) (Strukt) -> () {
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV08dynamic_B4_varSivg
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV08dynamic_B4_varSivs
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktVyS2icig : $@convention(method) (Int, Strukt) -> Int
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktVyS2icis : $@convention(method) (Int, Int, @inout Strukt) -> ()
// CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV22property_with_observerSivW
// CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV22property_with_observerSivw
struct Strukt {
dynamic init(x: Int) {
}
dynamic func dynamic_replaceable() {
}
dynamic var dynamic_replaceable_var : Int {
get {
return 10
}
set {
}
}
dynamic subscript(x : Int) -> Int {
get {
return 10
}
set {
}
}
dynamic var property_with_observer : Int {
didSet {
}
willSet {
}
}
}
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC1xACSi_tcfc : $@convention(method) (Int, @owned Klass) -> @owned Klass
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC08dynamic_B0yyF : $@convention(method) (@guaranteed Klass) -> () {
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC08dynamic_B4_varSivg
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC08dynamic_B4_varSivs
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassCyS2icig : $@convention(method) (Int, @guaranteed Klass) -> Int
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassCyS2icis : $@convention(method) (Int, Int, @guaranteed Klass) -> ()
// CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC22property_with_observerSivW
// CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC22property_with_observerSivw
class Klass {
dynamic init(x: Int) {
}
dynamic convenience init(c: Int) {
self.init(x: c)
}
dynamic convenience init(a: Int, b: Int) {
}
dynamic func dynamic_replaceable() {
}
dynamic func dynamic_replaceable2() {
}
dynamic var dynamic_replaceable_var : Int {
get {
return 10
}
set {
}
}
dynamic subscript(x : Int) -> Int {
get {
return 10
}
set {
}
}
dynamic var property_with_observer : Int {
didSet {
}
willSet {
}
}
}
class SubKlass : Klass {
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable8SubKlassC1xACSi_tcfc
// CHECK: // dynamic_function_ref Klass.init(x:)
// CHECK: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1xACSi_tcfc
// CHECK: apply [[FUN]]
dynamic override init(x: Int) {
super.init(x: x)
}
}
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6globalSivg : $@convention(thin) () -> Int {
dynamic var global : Int {
return 1
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable11replacementyyF : $@convention(thin) () -> () {
@_dynamicReplacement(for: dynamic_replaceable())
func replacement() {
}
extension Klass {
// Calls to the replaced function inside the replacing function should be
// statically dispatched.
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable5KlassC11replacementyyF : $@convention(method) (@guaranteed Klass) -> () {
// CHECK: [[FN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC11replacementyyF
// CHECK: apply [[FN]](%0) : $@convention(method) (@guaranteed Klass) -> ()
// CHECK: [[METHOD:%.*]] = class_method %0 : $Klass, #Klass.dynamic_replaceable2 :
// CHECK: = apply [[METHOD]](%0) : $@convention(method) (@guaranteed Klass) -> ()
// CHECK: return
// NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable5KlassC11replacementyyF : $@convention(method) (@guaranteed Klass) -> () {
// NOPREVIOUS: [[FN:%.*]] = class_method %0 : $Klass, #Klass.dynamic_replaceable
// NOPREVIOUS: apply [[FN]](%0) : $@convention(method) (@guaranteed Klass) -> ()
// NOPREVIOUS: [[METHOD:%.*]] = class_method %0 : $Klass, #Klass.dynamic_replaceable2 :
// NOPREVIOUS: = apply [[METHOD]](%0) : $@convention(method) (@guaranteed Klass) -> ()
// NOPREVIOUS: return
@_dynamicReplacement(for: dynamic_replaceable())
func replacement() {
dynamic_replaceable()
dynamic_replaceable2()
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1cACSi_tcfC"] [ossa] @$s23dynamically_replaceable5KlassC2crACSi_tcfC : $@convention(method) (Int, @thick Klass.Type) -> @owned Klass {
// CHECK: [[FUN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC2crACSi_tcfC
// CHECK: apply [[FUN]]({{.*}}, %1)
// NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1cACSi_tcfC"] [ossa] @$s23dynamically_replaceable5KlassC2crACSi_tcfC : $@convention(method) (Int, @thick Klass.Type) -> @owned Klass {
// NOPREVIOUS: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1cACSi_tcfC
// NOPREVIOUS: apply [[FUN]]({{.*}}, %1)
@_dynamicReplacement(for: init(c:))
convenience init(cr: Int) {
self.init(c: cr + 1)
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1a1bACSi_SitcfC"] [ossa] @$s23dynamically_replaceable5KlassC2ar2brACSi_SitcfC
// CHECK: // dynamic_function_ref Klass.__allocating_init(c:)
// CHECK: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1cACSi_tcfC
// CHECK: apply [[FUN]]({{.*}}, %2)
// NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1a1bACSi_SitcfC"] [ossa] @$s23dynamically_replaceable5KlassC2ar2brACSi_SitcfC
// NOPREVIOUS: // dynamic_function_ref Klass.__allocating_init(c:)
// NOPREVIOUS: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1cACSi_tcfC
// NOPREVIOUS: apply [[FUN]]({{.*}}, %2)
@_dynamicReplacement(for: init(a: b:))
convenience init(ar: Int, br: Int) {
self.init(c: ar + br)
}
@_dynamicReplacement(for: init(x:))
init(xr: Int) {
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable5KlassC1rSivg : $@convention(method) (@guaranteed Klass) -> Int {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Klass):
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1rSivg
// CHECK: apply [[ORIG]]([[ARG]]) : $@convention(method) (@guaranteed Klass) -> Int
// NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable5KlassC1rSivg : $@convention(method) (@guaranteed Klass) -> Int {
// NOPREVIOUS: bb0([[ARG:%.*]] : @guaranteed $Klass):
// NOPREVIOUS: [[ORIG:%.*]] = class_method [[ARG]] : $Klass, #Klass.dynamic_replaceable_var!getter
// NOPREVIOUS: apply [[ORIG]]([[ARG]]) : $@convention(method) (@guaranteed Klass) -> Int
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable5KlassC1rSivs : $@convention(method) (Int, @guaranteed Klass) -> () {
// CHECK: bb0({{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass):
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1rSivs
// CHECK: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method)
// NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable5KlassC1rSivs : $@convention(method) (Int, @guaranteed Klass) -> () {
// NOPREVIOUS: bb0({{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass):
// NOPREVIOUS: [[ORIG:%.*]] = class_method [[SELF]] : $Klass, #Klass.dynamic_replaceable_var!setter
// NOPREVIOUS: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method)
@_dynamicReplacement(for: dynamic_replaceable_var)
var r : Int {
get {
return dynamic_replaceable_var + 1
}
set {
dynamic_replaceable_var = newValue + 1
}
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassCyS2icig"] [ossa] @$s23dynamically_replaceable5KlassC1xS2i_tcig
// CHECK: bb0({{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass):
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1xS2i_tcig
// CHECK: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method) (Int, @guaranteed Klass) -> Int
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassCyS2icis"] [ossa] @$s23dynamically_replaceable5KlassC1xS2i_tcis
// CHECK: bb0({{.*}} : $Int, {{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass):
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1xS2i_tcis
// CHECK: apply [[ORIG]]({{.*}}, {{.*}}, [[SELF]]) : $@convention(method) (Int, Int, @guaranteed Klass) -> ()
@_dynamicReplacement(for: subscript(_:))
subscript(x y: Int) -> Int {
get {
return self[y]
}
set {
self[y] = newValue
}
}
}
extension Strukt {
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable6StruktV11replacementyyF : $@convention(method) (Strukt) -> () {
// CHECK: [[FUN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV11replacementyyF
// CHECK: apply [[FUN]](%0) : $@convention(method) (Strukt) -> ()
@_dynamicReplacement(for: dynamic_replaceable())
func replacement() {
dynamic_replaceable()
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV1xACSi_tcfC"] [ossa] @$s23dynamically_replaceable6StruktV1yACSi_tcfC : $@convention(method) (Int, @thin Strukt.Type) -> Strukt {
// CHECK: [[FUN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1yACSi_tcfC
// CHECK: apply [[FUN]]({{.*}}, %1)
@_dynamicReplacement(for: init(x:))
init(y: Int) {
self.init(x: y + 1)
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable6StruktV1rSivg
// CHECK: bb0([[ARG:%.*]] : $Strukt):
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1rSivg
// CHECK: apply [[ORIG]]([[ARG]]) : $@convention(method) (Strukt) -> Int
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable6StruktV1rSivs
// CHECK: bb0({{.*}} : $Int, [[ARG:%.*]] : $*Strukt):
// CHECK: [[BA:%.*]] = begin_access [modify] [unknown] [[ARG]] : $*Strukt
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1rSivs
// CHECK: apply [[ORIG]]({{.*}}, [[BA]]) : $@convention(method) (Int, @inout Strukt) -> ()
// CHECK: end_access [[BA]] : $*Strukt
@_dynamicReplacement(for: dynamic_replaceable_var)
var r : Int {
get {
return dynamic_replaceable_var + 1
}
set {
dynamic_replaceable_var = newValue + 1
}
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktVyS2icig"] [ossa] @$s23dynamically_replaceable6StruktV1xS2i_tcig
// CHECK: bb0({{.*}} : $Int, [[SELF:%.*]] : $Strukt):
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1xS2i_tcig
// CHECK: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method) (Int, Strukt) -> Int
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktVyS2icis"] [ossa] @$s23dynamically_replaceable6StruktV1xS2i_tcis
// CHECK: bb0({{.*}} : $Int, {{.*}} : $Int, [[SELF:%.*]] : $*Strukt):
// CHECK: [[BA:%.*]] = begin_access [modify] [unknown] [[SELF]] : $*Strukt
// CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1xS2i_tcis
// CHECK: apply [[ORIG]]({{.*}}, {{.*}}, [[BA]]) : $@convention(method) (Int, Int, @inout Strukt) -> ()
// CHECK: end_access [[BA]] : $*Strukt
@_dynamicReplacement(for: subscript(_:))
subscript(x y: Int) -> Int {
get {
return self[y]
}
set {
self[y] = newValue
}
}
}
struct GenericS<T> {
dynamic init(x: Int) {
}
dynamic func dynamic_replaceable() {
}
dynamic var dynamic_replaceable_var : Int {
get {
return 10
}
set {
}
}
dynamic subscript(x : Int) -> Int {
get {
return 10
}
set {
}
}
// CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable8GenericSV22property_with_observerSivW
// CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable8GenericSV22property_with_observerSivw
dynamic var property_with_observer : Int {
didSet {
}
willSet {
}
}
}
extension GenericS {
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable8GenericSV11replacementyyF
// CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV11replacementyyF
@_dynamicReplacement(for: dynamic_replaceable())
func replacement() {
dynamic_replaceable()
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV1xACyxGSi_tcfC"] [ossa] @$s23dynamically_replaceable8GenericSV1yACyxGSi_tcfC
// CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1yACyxGSi_tcfC
@_dynamicReplacement(for: init(x:))
init(y: Int) {
self.init(x: y + 1)
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable8GenericSV1rSivg
// CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1rSivg
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable8GenericSV1rSivs
// CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1rSivs
@_dynamicReplacement(for: dynamic_replaceable_var)
var r : Int {
get {
return dynamic_replaceable_var + 1
}
set {
dynamic_replaceable_var = newValue + 1
}
}
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSVyS2icig"] [ossa] @$s23dynamically_replaceable8GenericSV1xS2i_tcig
// CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1xS2i_tcig
// CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSVyS2icis"] [ossa] @$s23dynamically_replaceable8GenericSV1xS2i_tcis
// CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1xS2i_tcis
@_dynamicReplacement(for: subscript(_:))
subscript(x y: Int) -> Int {
get {
return self[y]
}
set {
self[y] = newValue
}
}
// CHECK-LABEL: sil private [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV22property_with_observerSivW"] [ossa] @$s23dynamically_replaceable8GenericSV34replacement_property_with_observerSivW
// CHECK-LABEL: sil private [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV22property_with_observerSivw"] [ossa] @$s23dynamically_replaceable8GenericSV34replacement_property_with_observerSivw
@_dynamicReplacement(for: property_with_observer)
var replacement_property_with_observer : Int {
didSet {
}
willSet {
}
}
}
dynamic var globalX = 0
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable7globalXSivg : $@convention(thin) () -> Int
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable7globalXSivs : $@convention(thin) (Int) -> ()
// CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable7getsetXyS2iF
// CHECK: dynamic_function_ref @$s23dynamically_replaceable7globalXSivs
// CHECK: dynamic_function_ref @$s23dynamically_replaceable7globalXSivg
func getsetX(_ x: Int) -> Int {
globalX = x
return globalX
}
// CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable18funcWithDefaultArgyySSFfA_
// CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable18funcWithDefaultArgyySSF
dynamic func funcWithDefaultArg(_ arg : String = String("hello")) {
print("hello")
}
// IMPLICIT-LABEL: sil hidden [thunk] [ossa] @barfoo
@_cdecl("barfoo")
func foobar() {
}
// IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable6$deferL_yyF
var x = 10
defer {
let y = x
}
// IMPLICIT-LABEL: sil [dynamically_replacable] [ossa] @$s23dynamically_replaceable16testWithLocalFunyyF
// IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable16testWithLocalFunyyF05localF0L_yyF
// IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable16testWithLocalFunyyF05localF0L_yyF0geF0L_yyF
// IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable16testWithLocalFunyyFyycfU_
public func testWithLocalFun() {
func localFun() {
func localLocalFun() { print("bar") }
print("foo")
localLocalFun()
}
localFun()
let unamedClosure = { print("foo") }
unamedClosure()
}
@propertyWrapper
struct WrapperWithInitialValue<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
// CHECK-NOT: sil hidden [ossa] @$s23dynamically_replaceable10SomeStructV1tSbvpfP
public struct SomeStruct {
@WrapperWithInitialValue var t = false
}
// Make sure that declaring the replacement before the original does not assert.
@_dynamicReplacement(for: orig)
func opaqueReplacement() -> Int {
return 2
}
dynamic func orig() -> Int {
return 1
}
| apache-2.0 |
jiecao-fm/SwiftTheme | Source/ThemeManager.swift | 3 | 2191 | //
// ThemeManager.swift
// SwiftTheme
//
// Created by Gesen on 16/1/22.
// Copyright ยฉ 2016ๅนด Gesen. All rights reserved.
//
import Foundation
public let ThemeUpdateNotification = "ThemeUpdateNotification"
public enum ThemePath {
case mainBundle
case sandbox(Foundation.URL)
public var URL: Foundation.URL? {
switch self {
case .mainBundle : return nil
case .sandbox(let path) : return path
}
}
public func plistPath(name: String) -> String? {
switch self {
case .mainBundle:
return Bundle.main.path(forResource: name, ofType: "plist")
case .sandbox(let path):
let name = name.hasSuffix(".plist") ? name : name + ".plist"
let url = path.appendingPathComponent(name)
return url.path
}
}
}
@objc public final class ThemeManager: NSObject {
@objc public static var animationDuration = 0.3
@objc public fileprivate(set) static var currentTheme: NSDictionary?
@objc public fileprivate(set) static var currentThemeIndex: Int = 0
public fileprivate(set) static var currentThemePath: ThemePath?
}
public extension ThemeManager {
@objc class func setTheme(index: Int) {
currentThemeIndex = index
NotificationCenter.default.post(name: Notification.Name(rawValue: ThemeUpdateNotification), object: nil)
}
class func setTheme(plistName: String, path: ThemePath) {
guard let plistPath = path.plistPath(name: plistName) else {
print("SwiftTheme WARNING: Can't find plist '\(plistName)' at: \(path)")
return
}
guard let plistDict = NSDictionary(contentsOfFile: plistPath) else {
print("SwiftTheme WARNING: Can't read plist '\(plistName)' at: \(plistPath)")
return
}
self.setTheme(dict: plistDict, path: path)
}
class func setTheme(dict: NSDictionary, path: ThemePath) {
currentTheme = dict
currentThemePath = path
NotificationCenter.default.post(name: Notification.Name(rawValue: ThemeUpdateNotification), object: nil)
}
}
| mit |
RMizin/PigeonMessenger-project | FalconMessenger/AppDelegate/SplitViewController/SplitViewController.swift | 1 | 1343 | //
// SplitViewController.swift
// FalconMessenger
//
// Created by Roman Mizin on 8/23/18.
// Copyright ยฉ 2018 Roman Mizin. All rights reserved.
//
import UIKit
final class SplitViewController: UISplitViewController, UISplitViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
preferredDisplayMode = .allVisible
}
override var traitCollection: UITraitCollection {
if DeviceType.isIPad {
return super.traitCollection
} else {
return UITraitCollection(horizontalSizeClass: .compact)
}
}
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
return true
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return ThemeManager.currentTheme().statusBarStyle
}
}
extension SplitViewController {
var masterViewController: UIViewController? {
return viewControllers.first
}
var detailViewController: UIViewController? {
guard viewControllers.count == 2 else { return nil }
return viewControllers.last
}
}
extension UINavigationController {
open override var preferredStatusBarStyle: UIStatusBarStyle {
return ThemeManager.currentTheme().statusBarStyle
}
}
| gpl-3.0 |
suragch/MongolAppDevelopment-iOS | Mongol App Componants/UIMongolTableView.swift | 1 | 4853 |
import UIKit
@IBDesignable class UIMongolTableView: UIView {
// MARK:- Unique to TableView
// ********* Unique to TableView *********
fileprivate var view = UITableView()
fileprivate let rotationView = UIView()
fileprivate var userInteractionEnabledForSubviews = true
// read only refernce to the underlying tableview
var tableView: UITableView {
get {
return view
}
}
var setTableFooterView: UIView? {
get {
return view.tableFooterView
}
set {
view.tableFooterView = newValue
}
}
var backgroundView: UIView? {
get {
return view.backgroundView
}
set {
view.backgroundView = newValue
}
}
var estimatedRowHeight: CGFloat {
get {
return view.estimatedRowHeight
}
set {
view.estimatedRowHeight = newValue
}
}
var rowHeight: CGFloat {
get {
return view.rowHeight
}
set {
view.rowHeight = newValue
}
}
var separatorInset: UIEdgeInsets {
get {
return view.separatorInset
}
set {
view.separatorInset = newValue
}
}
override var backgroundColor: UIColor? {
get {
return view.backgroundColor
}
set {
view.backgroundColor = newValue
}
}
func registerNib(_ nib: UINib?, forCellReuseIdentifier identifier: String) {
view.register(nib, forCellReuseIdentifier: identifier)
}
func setup() {
// do any setup necessary
self.addSubview(rotationView)
rotationView.addSubview(view)
self.backgroundColor = UIColor.clear
view.layoutMargins = UIEdgeInsets.zero
view.separatorInset = UIEdgeInsets.zero
}
// FIXME: @IBOutlet still can't be set in IB
@IBOutlet weak var delegate: UITableViewDelegate? {
get {
return view.delegate
}
set {
view.delegate = newValue
}
}
// FIXME: @IBOutlet still can't be set in IB
@IBOutlet weak var dataSource: UITableViewDataSource? {
get {
return view.dataSource
}
set {
view.dataSource = newValue
}
}
@IBInspectable var scrollEnabled: Bool {
get {
return view.isScrollEnabled
}
set {
view.isScrollEnabled = newValue
}
}
func scrollToRowAtIndexPath(_ indexPath: IndexPath, atScrollPosition: UITableViewScrollPosition, animated: Bool) {
view.scrollToRow(at: indexPath, at: atScrollPosition, animated: animated)
}
func registerClass(_ cellClass: AnyClass?, forCellReuseIdentifier identifier: String) {
view.register(cellClass, forCellReuseIdentifier: identifier)
}
func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell? {
return view.dequeueReusableCell(withIdentifier: identifier)
}
func reloadData() {
view.reloadData()
}
// MARK:- General code for Mongol views
// *******************************************
// ****** General code for Mongol views ******
// *******************************************
// This method gets called if you create the view in the Interface Builder
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// This method gets called if you create the view in code
override init(frame: CGRect){
super.init(frame: frame)
self.setup()
}
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
}
override func layoutSubviews() {
super.layoutSubviews()
rotationView.transform = CGAffineTransform.identity
rotationView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.bounds.height, height: self.bounds.width))
rotationView.transform = translateRotateFlip()
view.frame = rotationView.bounds
}
func translateRotateFlip() -> CGAffineTransform {
var transform = CGAffineTransform.identity
// translate to new center
transform = transform.translatedBy(x: (self.bounds.width / 2)-(self.bounds.height / 2), y: (self.bounds.height / 2)-(self.bounds.width / 2))
// rotate counterclockwise around center
transform = transform.rotated(by: CGFloat(-M_PI_2))
// flip vertically
transform = transform.scaledBy(x: -1, y: 1)
return transform
}
}
| mit |
dreamsxin/swift | benchmark/single-source/StringBuilder.swift | 7 | 778 | //===--- StringBuilder.swift ----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
@inline(never)
func buildString() -> String {
var sb = "a"
for str in ["b","c","d","pizza"] {
sb += str
}
return sb
}
@inline(never)
public func run_StringBuilder(_ N: Int) {
for _ in 1...5000*N {
_ = buildString()
}
}
| apache-2.0 |
ontouchstart/swift3-playground | Learn to Code 1.playgroundbook/Contents/Chapters/Document5.playgroundchapter/Pages/Exercise1.playgroundpage/Contents.swift | 1 | 1406 | //#-hidden-code
//
// Contents.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
//#-end-hidden-code
/*:
**Goal:** Use an [``if`` statement](glossary://if%20statement) to toggle only closed switches.
Try running this puzzle a few times before you write any code. You'll notice three switches on the walkway, each *randomly* toggled open or closed.
If Byte toggles a switch thatโs already open, the switch will close. Youโll need to use an [``if`` statement](glossary://if%20statement) to check each switch before telling Byte to toggle it.
Use ``isOnClosedSwitch`` as the **condition** in the ``if`` statement so you can tell Byte, "if you are on a closed switch, toggle the switch."
if isOnClosedSwitch {
toggleSwitch()
}
1. steps: Move Byte to the first switch.
2. Tap `if` in the shortcut bar to add an `if` statement.
3. Add the condition ``isOnClosedSwitch``, and toggle the switch if true.
4. Repeat for the two remaining switches.
*/
//#-hidden-code
playgroundPrologue()
//#-end-hidden-code
//#-code-completion(everything, hide)
//#-code-completion(currentmodule, show)
//#-code-completion(identifier, show, isOnOpenSwitch, moveForward(), turnLeft(), collectGem(), toggleSwitch(), turnRight(), isOnClosedSwitch, if, func, for)
//#-editable-code Tap to enter code
//#-end-editable-code
//#-hidden-code
playgroundEpilogue()
//#-end-hidden-code
| mit |
itouch2/LeetCode | LeetCodeTests/FindTheDuplicateNumberTest.swift | 1 | 957 | //
// FindTheDuplicateNumberTest.swift
// LeetCode
//
// Created by You Tu on 2017/6/6.
// Copyright ยฉ 2017ๅนด You Tu. All rights reserved.
//
import XCTest
class FindTheDuplicateNumberTest: XCTestCase {
func testFindTheDuplicateNumber() {
let findTheDuplicateNumber = FindTheDuplicateNumber()
XCTAssertEqual(findTheDuplicateNumber.findDuplicate([1, 2, 3, 3]), 3)
XCTAssertEqual(findTheDuplicateNumber.findDuplicate([1, 2, 2, 3]), 2)
XCTAssertEqual(findTheDuplicateNumber.findDuplicate([1, 2, 3, 4, 5, 6, 6]), 6)
XCTAssertEqual(findTheDuplicateNumber.findDuplicate([1, 3, 4, 2, 2]), 2)
XCTAssertEqual(findTheDuplicateNumber.findDuplicate([8, 1, 1, 9, 5, 4, 2, 7, 3, 6]), 1)
XCTAssertEqual(findTheDuplicateNumber.findDuplicate([8, 8, 8, 8, 5, 4, 2, 7, 3, 6]), 8)
XCTAssertEqual(findTheDuplicateNumber.findDuplicate([8, 1, 7, 9, 10, 11, 12, 8, 8, 15, 5, 4, 2, 8, 3, 6]), 8)
}
}
| mit |
RocketChat/Rocket.Chat.iOS | Rocket.ChatTests/API/Requests/Room/RoomRolesRequestSpec.swift | 1 | 5932 | //
// RoomRolesRequestSpec.swift
// Rocket.ChatTests
//
// Created by Rafael Kellermann Streit on 11/05/18.
// Copyright ยฉ 2018 Rocket.Chat. All rights reserved.
//
import XCTest
import SwiftyJSON
@testable import Rocket_Chat
class RoomRolesRequestSpec: APITestCase {
func testRequest() {
let reactRequest = RoomRolesRequest(roomName: "general", subscriptionType: .channel)
guard let request = reactRequest.request(for: api) else {
return XCTFail("request is not nil")
}
XCTAssertEqual(request.url?.path, "/api/v1/channels.roles", "path is correct")
XCTAssertEqual(request.httpMethod, "GET", "http method is correct")
XCTAssertEqual(request.url?.query, "roomName=general", "query value is correct")
XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "application/json", "content type is correct")
}
func testResult() {
let jsonString = """
{
"roles": [{
"u": {
"name": "John Appleseed",
"username": "john.appleseed",
"_id": "Xx6KW6XQsFkmDPGdE"
},
"_id": "j2pdXnucQbLg5WXRu",
"rid": "ABsnusN6m9h7Z7KnR",
"roles": [
"owner",
"moderator",
"leader"
]
},{
"u": {
"name": "John Applesee 2",
"username": "john.appleseed.2",
"_id": "xyJPCay3ShCQyuezh"
},
"_id": "oCMaLjQ74HuhSEW9g",
"rid": "ABsnusN6m9h7Z7KnR",
"roles": [
"moderator"
]
}
],
"success": true
}
"""
let json = JSON(parseJSON: jsonString)
let result = RoomRolesResource(raw: json)
XCTAssertEqual(result.roomRoles?.count, 2)
XCTAssertEqual(result.roomRoles?.first?.user?.username, "john.appleseed")
XCTAssertEqual(result.roomRoles?.first?.roles.count, 3)
XCTAssertEqual(result.roomRoles?.first?.roles.first, Role.owner.rawValue)
XCTAssertTrue(result.success)
}
func testNullUserObject() {
let jsonString = """
{
"roles": [{
"u": null,
"_id": "j2pdXnucQbLg5WXRu",
"rid": "ABsnusN6m9h7Z7KnR",
"roles": [
"owner",
"moderator",
"leader"
]
}
],
"success": true
}
"""
let json = JSON(parseJSON: jsonString)
let result = RoomRolesResource(raw: json)
XCTAssertTrue(result.success)
XCTAssertEqual(result.roomRoles?.count, 1)
XCTAssertEqual(result.roomRoles?.first?.roles.count, 3)
XCTAssertNotNil(result.roomRoles?.first?.user)
XCTAssertNil(result.roomRoles?.first?.user?.identifier)
}
func testInvalidUserObject() {
let jsonString = """
{
"roles": [{
"u": {
"foo": "bar"
},
"_id": "j2pdXnucQbLg5WXRu",
"rid": "ABsnusN6m9h7Z7KnR",
"roles": [
"owner",
"moderator",
"leader"
]
}
],
"success": true
}
"""
let json = JSON(parseJSON: jsonString)
let result = RoomRolesResource(raw: json)
XCTAssertTrue(result.success)
XCTAssertEqual(result.roomRoles?.count, 1)
XCTAssertEqual(result.roomRoles?.first?.roles.count, 3)
XCTAssertNotNil(result.roomRoles?.first?.user)
XCTAssertNil(result.roomRoles?.first?.user?.identifier)
}
func testArrayUserObject() {
let jsonString = """
{
"roles": [{
"u": ["foo"],
"_id": "j2pdXnucQbLg5WXRu",
"rid": "ABsnusN6m9h7Z7KnR",
"roles": [
"owner",
"moderator",
"leader"
]
}
],
"success": true
}
"""
let json = JSON(parseJSON: jsonString)
let result = RoomRolesResource(raw: json)
XCTAssertTrue(result.success)
XCTAssertEqual(result.roomRoles?.count, 1)
XCTAssertEqual(result.roomRoles?.first?.roles.count, 3)
XCTAssertNotNil(result.roomRoles?.first?.user)
XCTAssertNil(result.roomRoles?.first?.user?.identifier)
}
func testEmtpyRolesObject() {
let jsonString = """
{
"roles": [{
"u": {
"name": "John Appleseed",
"username": "john.appleseed",
"_id": "Xx6KW6XQsFkmDPGdE"
},
"_id": "j2pdXnucQbLg5WXRu",
"rid": "ABsnusN6m9h7Z7KnR",
"roles": [ ]
}
],
"success": true
}
"""
let json = JSON(parseJSON: jsonString)
let result = RoomRolesResource(raw: json)
XCTAssertTrue(result.success)
XCTAssertEqual(result.roomRoles?.count, 1)
XCTAssertEqual(result.roomRoles?.first?.roles.count, 0)
XCTAssertEqual(result.roomRoles?.first?.user?.username, "john.appleseed")
}
func testEmptyResults() {
let nilResult = RoomRolesResource(raw: nil)
XCTAssertNil(nilResult.roomRoles)
}
}
| mit |
hermantai/samples | ios/cs193p/CardMatching/CardMatching/GameThemeStore.swift | 1 | 3030 | //
// GameThemeStore.swift
// CardMatching
//
// Created by Herman (Heung) Tai on 11/7/21.
//
import Foundation
class GameThemeStore: ObservableObject {
@Published var gameThemes = [GameTheme]() {
didSet {
storeInUserDefaults()
}
}
let name: String
private var userDefaultsKey: String {
"GameThemeStore:" + name
}
private func storeInUserDefaults() {
UserDefaults.standard.set(try? JSONEncoder().encode(gameThemes), forKey: userDefaultsKey)
}
private func restoreFromUserDefaults() {
if let jsonData = UserDefaults.standard.data(forKey: userDefaultsKey),
let decodedPalettes = try? JSONDecoder().decode(Array<GameTheme>.self, from: jsonData) {
gameThemes = decodedPalettes
}
}
init(named name: String) {
self.name = name
restoreFromUserDefaults()
if gameThemes.isEmpty {
insertTheme(named: "Animals",
emojis: "๐ถ๐ฑ๐ญ๐น๐ฐ๐ฆ๐ป๐ผ๐ปโโ๏ธ๐จ๐ฏ๐ฆ๐ฎ๐ท๐ธ๐ต",
color: RGBAColor(color: .red))
insertTheme(
named: "Food",
emojis: "๐๐๐๐๐๐๐๐๐ซ๐๐๐๐ฅญ๐๐ฅฅ๐ฅ๐
๐๐ฅ๐ฅฆ",
color: RGBAColor(color: .orange))
insertTheme(
named: "Vehicles",
emojis: "๐๐๐๐๐๐๐๐๐๐๐ป๐๐๐๐๐โต๏ธ๐ค๐ฆผ๐ด๐โ๏ธ๐๐",
color: RGBAColor(color: .yellow))
insertTheme(
named: "Halloween",
emojis: "๐ป๐๐ท",
color: RGBAColor(color: .gray))
}
}
// MARK: - Intent
func gameTheme(at index: Int) -> GameTheme {
let safeIndex = min(max(index, 0), gameThemes.count - 1)
return gameThemes[safeIndex]
}
@discardableResult
func removeTheme(at index: Int) -> Int {
if gameThemes.count > 1, gameThemes.indices.contains(index) {
gameThemes.remove(at: index)
}
return index % gameThemes.count
}
func insertTheme(named name: String, emojis: String, color: RGBAColor, at index: Int = 0) {
let unique = (gameThemes.max(by: { $0.id < $1.id })?.id ?? 0) + 1
let gameTheme = GameTheme(name: name, emojis: emojis, color: color, id: unique)
let safeIndex = min(max(index, 0), gameThemes.count)
gameThemes.insert(gameTheme, at: safeIndex)
}
}
/// A Theme consists of a name
/// for the theme, a set of emoji to use, a number of pairs of cards to show, and an
/// appropriate color to use to draw the cards.
struct GameTheme: Identifiable, Codable, Hashable {
let name: String
let emojis: String
let color: RGBAColor
let id: Int
}
struct RGBAColor: Codable, Equatable, Hashable {
let red: Double
let green: Double
let blue: Double
let alpha: Double
}
| apache-2.0 |
RocketChat/Rocket.Chat.iOS | Rocket.ChatTests/Extensions/API/APIExtensionsSpec.swift | 1 | 1145 | //
// APIExtensionsSpec.swift
// Rocket.ChatTests
//
// Created by Matheus Cardoso on 11/28/17.
// Copyright ยฉ 2017 Rocket.Chat. All rights reserved.
//
import XCTest
import RealmSwift
@testable import Rocket_Chat
class APIExtensionsSpec: XCTestCase {
func testCurrent() {
guard let realm = Realm.current else {
XCTFail("realm could not be instantiated")
return
}
var auth = Auth.testInstance()
realm.execute({ realm in
realm.add(auth)
})
var api = API.current(realm: realm)
XCTAssertEqual(api?.userId, "auth-userid")
XCTAssertEqual(api?.authToken, "auth-token")
XCTAssertEqual(api?.version, Version(1, 2, 3))
Realm.execute({ realm in
auth.serverVersion = "invalid"
realm.add(auth, update: true)
})
api = API.current(realm: realm)
XCTAssertEqual(api?.version, Version.zero)
auth = Auth()
api = API.current(realm: realm)
XCTAssertNotNil(api)
auth = Auth()
api = API.current(realm: nil)
XCTAssertNil(api)
}
}
| mit |
velvetroom/columbus | Source/View/CreateSave/VCreateSaveStatusError+Constants.swift | 1 | 494 | import UIKit
extension VCreateSaveStatusError
{
struct Constants
{
static let labelBottom:CGFloat = -200
static let labelHeight:CGFloat = 220
static let titleFontSize:CGFloat = 20
static let descrFontSize:CGFloat = 14
static let buttonWidth:CGFloat = 120
static let buttonHeight:CGFloat = 40
static let cancelFontSize:CGFloat = 16
static let retryFontSize:CGFloat = 18
static let imageHeight:CGFloat = 80
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.