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 |
---|---|---|---|---|---|
ducn/Slux | Example/Slux/Components/ViewController.swift | 1 | 502 | //
// ViewController.swift
// Slux
//
// Created by ducn on 01/29/2016.
// Copyright (c) 2016 ducn. All rights reserved.
//
import UIKit
import Slux
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 |
DanielAsher/VIPER-SWIFT | Carthage/Checkouts/RxSwift/Rx.playground/Pages/Mathematical_and_Aggregate_Operators.xcplaygroundpage/Contents.swift | 2 | 2041 | /*:
> # IMPORTANT: To use `Rx.playground`, please:
1. Open `Rx.xcworkspace`
2. Build `RxSwift-OSX` scheme
3. And then open `Rx` playground in `Rx.xcworkspace` tree view.
4. Choose `View > Show Debug Area`
*/
//: [<< Previous](@previous) - [Index](Index)
import RxSwift
/*:
## Mathematical and Aggregate Operators
Operators that operate on the entire sequence of items emitted by an Observable
*/
/*:
### `concat`
Emit the emissions from two or more Observables without interleaving them.

[More info in reactive.io website]( http://reactivex.io/documentation/operators/concat.html )
*/
example("concat") {
let var1 = BehaviorSubject(value: 0)
let var2 = BehaviorSubject(value: 200)
// var3 is like an Observable<Observable<Int>>
let var3 = BehaviorSubject(value: var1)
let d = var3
.concat()
.subscribe {
print($0)
}
var1.on(.Next(1))
var1.on(.Next(2))
var1.on(.Next(3))
var1.on(.Next(4))
var3.on(.Next(var2))
var2.on(.Next(201))
var1.on(.Next(5))
var1.on(.Next(6))
var1.on(.Next(7))
var1.on(.Completed)
var2.on(.Next(202))
var2.on(.Next(203))
var2.on(.Next(204))
}
/*:
### `reduce`
Apply a function to each item emitted by an Observable, sequentially, and emit the final value.
This function will perform a function on each element in the sequence until it is completed, then send a message with the aggregate value. It works much like the Swift `reduce` function works on sequences.

[More info in reactive.io website]( http://reactivex.io/documentation/operators/reduce.html )
*/
example("reduce") {
_ = Observable.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
.reduce(0, accumulator: +)
.subscribe {
print($0)
}
}
//: [Index](Index) - [Next >>](@next)
| mit |
moltin/ios-sdk | Examples/moltin WatchKit Example Extension/ExtensionDelegate.swift | 1 | 1706 | //
// ExtensionDelegate.swift
// moltin WatchKit Example Extension
//
// Created by Craig Tweedy on 21/02/2018.
//
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
for task in backgroundTasks {
// Use a switch statement to check the task type
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
// Be sure to complete the background task once you’re done.
backgroundTask.setTaskCompletedWithSnapshot(false)
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
// Snapshot tasks have a unique completion call, make sure to set your expiration date
snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
// Be sure to complete the connectivity task once you’re done.
connectivityTask.setTaskCompletedWithSnapshot(false)
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// Be sure to complete the URL session task once you’re done.
urlSessionTask.setTaskCompletedWithSnapshot(false)
default:
// make sure to complete unhandled task types
task.setTaskCompletedWithSnapshot(false)
}
}
}
}
| mit |
gregomni/swift | validation-test/IDE/crashers_2_fixed/0026-completion-type-not-part-of-solution.swift | 9 | 458 | // RUN: %swift-ide-test -code-completion -code-completion-token=COMPLETE -source-filename=%s
struct Image {}
@resultBuilder struct ViewBuilder2 {
static func buildBlock<Content>(_ content: Content) -> Content { fatalError() }
}
struct NavigationLink<Destination> {
init(@ViewBuilder2 destination: () -> Destination)
init(_ title: String)
}
struct CollectionRowView {
func foo() {
NavigationLink() {
Image().#^COMPLETE^#
| apache-2.0 |
mlavergn/swiftutil | Sources/datetime.swift | 1 | 2296 | /// Extensions to Date
/// DateTime struct with Date related helpers
///
/// - author: Marc Lavergne <mlavergn@gmail.com>
/// - copyright: 2017 Marc Lavergne. All rights reserved.
/// - license: MIT
import Foundation
// MARK: - Date extension
public extension Date {
/// Compare caller to date to caller and determine if caller is earlier
///
/// - Parameter date: Date to compare caller against
/// - Returns: Bool with true if date is later than caller, otherwise false
public func isBefore(date: Date) -> Bool {
return self.compare(date) == .orderedAscending ? true : false
}
/// Compare caller to date to caller and determine if caller is later
///
/// - Parameter date: Date to compare caller against
/// - Returns: Bool with true if date is earlier than caller, otherwise false
public func isAfter(date: Date) -> Bool {
return self.compare(date) == .orderedDescending ? true : false
}
/// Compare caller to date to caller and determine if caller is equal
///
/// - Parameter date: Date to compare caller against
/// - Returns: Bool with true if date is equal to caller, otherwise false
public func isEqual(date: Date) -> Bool {
return self.compare(date) == .orderedSame ? true : false
}
}
// MARK: - DateTime struct
public struct DateTime {
/// Obtain the epoch time as an Int
public static var epoch: Int {
return Int(NSDate().timeIntervalSince1970)
}
/// Constructs a Date object based on the Gregorian calendar
///
/// - Parameters:
/// - year: year as an Int
/// - month: month as an Int
/// - day: day as an Int
/// - Returns: Date optional
public static func dateWith(year: Int, month: Int, day: Int) -> Date? {
var components = DateComponents()
components.year = year
components.month = month
components.day = day
return NSCalendar(identifier: NSCalendar.Identifier.gregorian)?.date(from: components)
}
/// Constructs a Date from a format mask and string representation
///
/// - Parameters:
/// - format: format mask String
/// - date: date as String
/// - Returns: Date optional
public static func stringToDate(format: String, date: String) -> Date? {
let dateFormat = DateFormatter()
dateFormat.timeZone = NSTimeZone.default
dateFormat.dateFormat = format
return dateFormat.date(from: date)
}
}
| mit |
benlangmuir/swift | validation-test/compiler_crashers_fixed/28017-swift-protocoldecl-existentialtypesupportedslow.swift | 65 | 452 | // 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
enum S<T where g:e{class T{let a={protocol P{func f:P
| apache-2.0 |
benlangmuir/swift | test/Incremental/Fingerprints/member-moves-extensions.swift | 13 | 1311 | // Test per-type-body fingerprints using simple extensions
//
// If the parser is allowed to use a body fingerprint for an extension
// this test will fail because usesA.swift won't be recompiled for the
// last step.
// Establish status quo
// RUN: %empty-directory(%t)
// RUN: cp %S/Inputs/member-moves-extensions/* %t
// RUN: cp %t/definesS{-before,}.swift
// Seeing weird failure on CI, so set the mod times
// RUN: touch -t 200101010101 %t/*.swift
// RUN: cd %t && %target-swiftc_driver -enable-batch-mode -j2 -incremental -driver-show-incremental main.swift definesS.swift -module-name main -output-file-map ofm.json >& %t/output3
// Change one type, only uses of that type get recompiled
// RUN: cp %t/definesS{-after,}.swift
// Seeing weird failure on CI, so ensure that definesS.swift is newer
// RUN: touch -t 200201010101 %t/*
// RUN: touch -t 200101010101 %t/*.swift
// RUN: touch -t 200301010101 %t/definesS.swift
// RUN: cd %t && %target-swiftc_driver -enable-batch-mode -j2 -incremental -driver-show-incremental main.swift definesS.swift -module-name main -output-file-map ofm.json >& %t/output4
// RUN: %FileCheck -check-prefix=CHECK-RECOMPILED-W %s < %t/output4
// CHECK-RECOMPILED-W: {compile: definesS.o <= definesS.swift}
// CHECK-RECOMPILED-W: {compile: main.o <= main.swift}
| apache-2.0 |
objecthub/swift-lispkit | Sources/LispKit/IO/BinaryInputSource.swift | 1 | 8272 | //
// BinaryInputSource.swift
// LispKit
//
// Created by Matthias Zenger on 01/11/2017.
// Copyright © 2017 ObjectHub. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
public protocol BinaryInputSource {
init?(url: URL)
func open()
func close()
var hasBytesAvailable: Bool { get }
func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength len: Int) -> Int
}
extension InputStream: BinaryInputSource {
}
public final class HTTPInputStream: BinaryInputSource {
/// A condition object used to synchronize changes between tasks and the input stream object
fileprivate let condition = NSCondition()
/// The target URL of the request
public let url: URL
/// The network task associated with this input stream
private var task: URLSessionTask? = nil
/// The HTTP response header object once it was received
fileprivate var response: HTTPURLResponse? = nil
/// Data of the body of the HTTP response
public fileprivate(set) var data: Data
/// The current read index
public private(set) var readIndex: Data.Index
/// The timeout for the HTTP connection
public let timeout: Double
/// Number of bytes that were received from the HTTP GET request
public fileprivate(set) var bytesReceived: Int64 = 0
/// If an error was encountered, it is being stored here
public fileprivate(set) var error: Error? = nil
/// Returns `false` as long as this input stream is connected to a network task.
public fileprivate(set) var completed: Bool = false
private static let sessionDelegate = SessionDelegate()
/// The default request timeout
public static let defaultTimeout: Double = 60.0
public private(set) static var session: URLSession = {
let configuration = URLSessionConfiguration.default
configuration.requestCachePolicy = .useProtocolCachePolicy
configuration.timeoutIntervalForRequest = TimeInterval(HTTPInputStream.defaultTimeout)
return URLSession(configuration: configuration,
delegate: HTTPInputStream.sessionDelegate,
delegateQueue: nil)
}()
public convenience init?(url: URL) {
self.init(url: url, timeout: HTTPInputStream.defaultTimeout)
}
public init?(url: URL, timeout: Double) {
guard let scheme = url.scheme, scheme == "http" || scheme == "https" else {
return nil
}
self.url = url
self.data = Data()
self.readIndex = self.data.startIndex
self.timeout = timeout
}
public func open() {
self.openConnection(timeout: self.timeout)
self.waitForResponse()
}
public func openConnection(timeout: Double) {
guard self.task == nil && !self.completed else {
return
}
var request = URLRequest(url: self.url)
request.httpMethod = "GET"
request.cachePolicy = .useProtocolCachePolicy
request.timeoutInterval = TimeInterval(timeout)
request.httpShouldHandleCookies = false
let task = HTTPInputStream.session.dataTask(with: request)
HTTPInputStream.sessionDelegate.registerTask(task, forStream: self)
self.task = task
task.resume()
}
public func close() {
if !self.completed {
if let task = self.task {
task.cancel()
self.task = nil
} else {
self.completed = true
}
}
}
public func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength len: Int) -> Int {
self.condition.lock()
while !self.completed && self.readIndex == self.data.endIndex {
self.condition.wait()
}
let bytesRead = min(len, self.data.endIndex - self.readIndex)
let nextReadIndex = self.data.index(self.readIndex, offsetBy: bytesRead)
self.data.copyBytes(to: buffer, from: self.readIndex ..< nextReadIndex)
self.readIndex = nextReadIndex
self.condition.unlock()
return bytesRead
}
public var hasBytesAvailable: Bool {
return !self.completed || self.readIndex < self.data.endIndex
}
/// Waits until a response was received (or the request was terminated)
public func waitForResponse() {
self.condition.lock()
while self.response == nil && !self.completed {
self.condition.wait()
}
self.condition.unlock()
}
/// Waits until all data was received (or the request was terminated)
public func waitForData() {
self.condition.lock()
while !self.completed {
self.condition.wait()
}
self.condition.unlock()
}
/// The status code of the HTTP response
public var statusCode: Int? {
return self.response?.statusCode
}
/// A textual description of the status code of the HTTP response
public var statusCodeDescription: String? {
guard let statusCode = self.statusCode else {
return nil
}
return HTTPURLResponse.localizedString(forStatusCode: statusCode)
}
/// The number of bytes that are supposed to be read
public var expectedContentLength: Int64? {
return self.response?.expectedContentLength
}
/// The name of the text encoding.
public var textEncodingName: String? {
return self.response?.textEncodingName
}
/// The mime type name.
public var mimeType: String? {
return self.response?.mimeType
}
/// The URL of the response.
public var responseUrl: URL? {
return self.response?.url
}
/// All header fields of the HTTP response.
public var headerFields: [String : String]? {
guard let response = self.response else {
return nil
}
var res: [String : String] = [:]
for (key, value) in response.allHeaderFields {
if let str = value as? String {
res[key.description] = str
}
}
return res
}
}
fileprivate class SessionDelegate: NSObject,
URLSessionDelegate,
URLSessionTaskDelegate,
URLSessionDataDelegate {
private var inputStreamForTask: [Int : HTTPInputStream] = [:]
public func registerTask(_ task: URLSessionTask, forStream stream: HTTPInputStream) {
self.inputStreamForTask[task.taskIdentifier] = stream
}
/// This callback is the last one done for each task. Remove the input stream from the
/// list of all open input streams.
public func urlSession(_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?) {
guard let inputStream = self.inputStreamForTask[task.taskIdentifier] else {
return
}
inputStream.condition.lock()
inputStream.error = inputStream.error ?? error
inputStream.completed = true
self.inputStreamForTask.removeValue(forKey: task.taskIdentifier)
inputStream.condition.signal()
inputStream.condition.unlock()
}
public func urlSession(_ session: URLSession,
dataTask task: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
guard let inputStream = self.inputStreamForTask[task.taskIdentifier] else {
completionHandler(.allow)
return
}
inputStream.condition.lock()
if let response = response as? HTTPURLResponse {
inputStream.response = response
inputStream.condition.signal()
}
inputStream.condition.unlock()
completionHandler(.allow)
}
public func urlSession(_ session: URLSession,
dataTask task: URLSessionDataTask,
didReceive data: Data) {
guard let inputStream = self.inputStreamForTask[task.taskIdentifier] else {
return
}
inputStream.data.append(data)
inputStream.bytesReceived += Int64(data.count)
}
}
| apache-2.0 |
GuiBayma/PasswordVault | PasswordVault/AppDelegate.swift | 1 | 4965 | //
// AppDelegate.swift
// PasswordVault
//
// Created by Guilherme Bayma on 7/26/17.
// Copyright © 2017 Bayma. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var backgroundView: BackgroundView?
var didShowPasswordView = false
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Debug
let groups = GroupManager.sharedInstance.getAllGroups()
print("\(groups.count) groups found\n")
// for group in groups {
// _ = GroupManager.sharedInstance.delete(object: group)
// }
let items = ItemManager.sharedInstance.getAllItems()
print("\(items.count) items found\n")
// for item in items {
// _ = GroupManager.sharedInstance.delete(object: item)
// }
self.window = UIWindow(frame: UIScreen.main.bounds)
backgroundView = BackgroundView(frame: window?.frame ?? CGRect())
let mainView = GroupsTableViewController()
let navController = UINavigationController(rootViewController: mainView)
self.window?.rootViewController = navController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
guard
let bView = backgroundView,
didShowPasswordView != true
else {
return
}
if let topController = UIApplication.topViewController() {
let topView = topController.view
topView?.addSubview(bView)
}
UIApplication.shared.ignoreSnapshotOnNextApplicationLaunch()
}
func applicationDidBecomeActive(_ application: UIApplication) {
if didShowPasswordView {
return
}
if let topController = UIApplication.topViewController() {
if let _ = UserDefaults.standard.string(forKey: "AppPasswordKey") {
let passView = PasswordViewController()
topController.present(passView, animated: false) {
self.backgroundView?.removeFromSuperview()
self.didShowPasswordView = true
}
} else {
let newPassView = NewPasswordViewController()
topController.present(newPassView, animated: false) {
self.backgroundView?.removeFromSuperview()
}
}
}
}
func applicationWillTerminate(_ application: UIApplication) {
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "PasswordVault")
container.loadPersistentStores(completionHandler: { (_, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit |
mortenjust/androidtool-mac | AndroidTool/ObbHandler.swift | 1 | 1195 | //
// ObbHandler.swift
// AndroidTool
//
// Created by Morten Just Petersen on 1/20/16.
// Copyright © 2016 Morten Just Petersen. All rights reserved.
//
import Cocoa
protocol ObbHandlerDelegate {
func obbHandlerDidStart(_ bytes:String)
func obbHandlerDidFinish()
}
class ObbHandler: NSObject {
var filePath:String!
var delegate:ObbHandlerDelegate?
var device:Device!
var fileSize:UInt64?
init(filePath:String, device:Device){
print(">>obb init obbhandler")
super.init()
self.filePath = filePath
self.device = device
self.fileSize = Util.getFileSizeForFilePath(filePath)
}
func pushToDevice(){
print(">>zip flash")
let shell = ShellTasker(scriptFile: "installObbForSerial")
let bytes = (fileSize != nil) ? Util.formatBytes(fileSize!) : "? bytes"
delegate?.obbHandlerDidStart(bytes)
print("startin obb copying the \(bytes) file")
shell.run(arguments: [self.device.adbIdentifier!, self.filePath]) { (output) -> Void in
print("done copying OBB to device")
self.delegate?.obbHandlerDidFinish()
}
}
}
| apache-2.0 |
adrfer/swift | validation-test/compiler_crashers_fixed/25154-swift-constraints-constraintsystem-opengeneric.swift | 4 | 287 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{struct B<T where B:C{class B{class B{{}let b=true as S}struct S<T
| apache-2.0 |
ioscreator/ioscreator | IOSShakeGestureTutorial/IOSShakeGestureTutorial/ViewController.swift | 1 | 702 | //
// ViewController.swift
// IOSShakeGestureTutorial
//
// Created by Arthur Knopper on 18/02/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var shakeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func becomeFirstResponder() -> Bool {
return true
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if motion == .motionShake {
shakeLabel.text = "Shaken, not stirred"
}
}
}
| mit |
ScottRobbins/SRBubbleProgressTracker | SRBubbleProgressTracker/SRBubbleProgressTrackerView.swift | 1 | 15019 | //
// SRBubbleProgressTrackerView.swift
// SRBubbleProgressTracker
//
// Created by Samuel Scott Robbins on 2/9/15.
// Copyright (c) 2015 Scott Robbins Software. All rights reserved.
//
import UIKit
public enum BubbleAllignment {
case Vertical
case Horizontal
}
public class SRBubbleProgressTrackerView : UIView {
// MARK: Initializations
private var lastBubbleCompleted = 0
private var bubbleArray = [UIView]()
private var connectLineArray = [UIView]()
private var bubbleAllignment = BubbleAllignment.Vertical
private var animateToBubbleQueue = [Int]()
// MARK: Color Defaults
@IBInspectable
var lineColorForNotCompleted : UIColor = .grayColor()
@IBInspectable
var lineColorForCompleted : UIColor = .greenColor()
@IBInspectable
var bubbleBackgroundColorForNotCompleted : UIColor = .grayColor()
@IBInspectable
var bubbleBackgroundColorForCompleted : UIColor = .greenColor()
@IBInspectable
var bubbleBackgroundColorForNextToComplete : UIColor = .orangeColor()
@IBInspectable
var bubbleTextColorForNotCompleted : UIColor = .whiteColor()
@IBInspectable
var bubbleTextColorForCompleted : UIColor = .whiteColor()
@IBInspectable
var bubbleTextColorForNextToComplete : UIColor = .whiteColor()
// MARK: Setup View
public func setupInitialBubbleProgressTrackerView(numBubbles : Int, dotDiameter : CGFloat, allign : BubbleAllignment) {
bubbleAllignment = allign
for line in connectLineArray { line.removeFromSuperview() }
connectLineArray.removeAll(keepCapacity: false)
for bubble in bubbleArray { removeFromSuperview() }
bubbleArray.removeAll(keepCapacity: false)
lastBubbleCompleted = 0
// Add the lines into the view
let lineStartDown = dotDiameter / 2.0
let lineWidth = dotDiameter * 0.2
let length = (bubbleAllignment == .Vertical) ? self.frame.size.height : self.frame.size.width
let width = (bubbleAllignment == .Vertical) ? self.frame.size.width : self.frame.size.height
var lineStartMiddle = (width / 2.0) - (lineWidth / 2.0)
let lineHeight = (length - lineStartDown * 2.0) / CGFloat(numBubbles - 1)
addLinesIntoView(lineStartDown, lineStartMiddle: lineStartMiddle, lineHeight: lineHeight, lineWidth: lineWidth, numLines: numBubbles - 1)
lineStartMiddle = (width / 2.0) - (dotDiameter / 2.0)
// Add bubbles into the view
for i in 0..<numBubbles {
addBubbleIntoView(lineStartMiddle, lineHeight: lineHeight, lineWidth: lineWidth, dotDiameter: dotDiameter, bubbleNumber: i)
}
}
public func setupInitialBubbleProgressTrackerView(numBubbles : Int, dotDiameter : CGFloat, allign : BubbleAllignment, leftOrTopViews : [UIView], rightOrBottomViews : [UIView]) {
let spaceLeftOrTopOfBubbles : CGFloat = 20.0
bubbleAllignment = allign
connectLineArray.removeAll(keepCapacity: false)
bubbleArray.removeAll(keepCapacity: false)
lastBubbleCompleted = 0
// Add the lines into the view
let lineStartDown = dotDiameter / 2.0
let lineWidth = dotDiameter * 0.2
let length = (bubbleAllignment == .Vertical) ? self.frame.size.height : self.frame.size.width
let width = (bubbleAllignment == .Vertical) ? self.frame.size.width : self.frame.size.height
var startMiddle = (width / 2.0) - (lineWidth / 2.0)
let lineHeight = (length - lineStartDown * 2.0) / CGFloat(numBubbles - 1)
addLinesIntoView(lineStartDown, lineStartMiddle: startMiddle, lineHeight: lineHeight, lineWidth: lineWidth, numLines: numBubbles - 1)
startMiddle = (width / 2.0) - (dotDiameter / 2.0)
// Add bubbles into the view
for i in 0..<numBubbles {
let bubbleFrame = addBubbleIntoView(startMiddle, lineHeight: lineHeight, lineWidth: lineWidth, dotDiameter: dotDiameter, bubbleNumber: i)
if i < leftOrTopViews.count {
if bubbleAllignment == .Vertical {
let pointYCenter : CGFloat = bubbleFrame.origin.y + bubbleFrame.size.height / 2.0
let pointY : CGFloat = pointYCenter - (leftOrTopViews[i].frame.size.height / 2.0)
let pointX : CGFloat = bubbleFrame.origin.x - spaceLeftOrTopOfBubbles - leftOrTopViews[i].frame.size.width
leftOrTopViews[i].frame.origin = CGPointMake(pointX, pointY)
} else {
let pointXCenter : CGFloat = bubbleFrame.origin.x + bubbleFrame.size.width / 2.0
let pointX : CGFloat = pointXCenter - (leftOrTopViews[i].frame.size.width / 2.0)
let pointY : CGFloat = bubbleFrame.origin.y - spaceLeftOrTopOfBubbles - leftOrTopViews[i].frame.size.height
leftOrTopViews[i].frame.origin = CGPointMake(pointX, pointY)
}
self.addSubview(leftOrTopViews[i])
}
if i < rightOrBottomViews.count {
if bubbleAllignment == .Vertical {
let pointYCenter : CGFloat = bubbleFrame.origin.y + bubbleFrame.size.height / 2.0
let pointY : CGFloat = pointYCenter - (rightOrBottomViews[i].frame.size.height / 2.0)
let pointX : CGFloat = bubbleFrame.origin.x + bubbleFrame.size.width + spaceLeftOrTopOfBubbles
rightOrBottomViews[i].frame.origin = CGPointMake(pointX, pointY)
} else {
let pointXCenter : CGFloat = bubbleFrame.origin.x + bubbleFrame.size.width / 2.0
let pointX : CGFloat = pointXCenter - (rightOrBottomViews[i].frame.size.width / 2.0)
let pointY : CGFloat = bubbleFrame.origin.y + bubbleFrame.size.height + spaceLeftOrTopOfBubbles
rightOrBottomViews[i].frame.origin = CGPointMake(pointX, pointY)
}
self.addSubview(rightOrBottomViews[i])
}
}
}
private func addLinesIntoView(lineStartDown : CGFloat, lineStartMiddle : CGFloat, lineHeight : CGFloat, lineWidth : CGFloat, numLines : Int) {
// Add lines into view
for i in 0..<numLines {
var lineView = UIView()
if bubbleAllignment == .Vertical {
lineView.frame = CGRectMake(lineStartMiddle, lineStartDown + lineHeight * CGFloat(i), lineWidth, lineHeight)
} else {
lineView.frame = CGRectMake(lineStartDown + lineHeight * CGFloat(i), lineStartMiddle, lineHeight, lineWidth)
}
lineView.backgroundColor = lineColorForNotCompleted
connectLineArray.append(lineView)
self.addSubview(lineView)
}
}
private func addBubbleIntoView(bubbleStartMiddle : CGFloat, lineHeight : CGFloat, lineWidth : CGFloat, dotDiameter : CGFloat, bubbleNumber : Int) -> CGRect {
var bubbleViewFrame = CGRect()
if bubbleAllignment == .Vertical {
bubbleViewFrame = CGRectMake(bubbleStartMiddle, lineHeight * CGFloat(bubbleNumber), dotDiameter, dotDiameter)
} else {
bubbleViewFrame = CGRectMake(lineHeight * CGFloat(bubbleNumber), bubbleStartMiddle, dotDiameter, dotDiameter)
}
var bubbleView = getBubbleView(bubbleViewFrame, number: bubbleNumber+1)
bubbleArray.append(bubbleView)
self.addSubview(bubbleView)
return bubbleView.frame
}
private func getBubbleView(frame : CGRect, number : Int) -> UIView {
var bubbleView = UIView(frame: frame)
var numberLabel = UILabel()
numberLabel.frame = CGRectMake(0, 0, bubbleView.frame.size.width, bubbleView.frame.size.height)
numberLabel.text = "\(number)"
numberLabel.textAlignment = NSTextAlignment.Center
numberLabel.textColor = (number == 1) ? bubbleTextColorForNextToComplete : bubbleTextColorForNotCompleted
numberLabel.font = UIFont.systemFontOfSize(30.0)
bubbleView.addSubview(numberLabel)
bubbleView.backgroundColor = (number == 1) ? bubbleBackgroundColorForNextToComplete : bubbleBackgroundColorForNotCompleted
bubbleView.layer.cornerRadius = bubbleView.frame.size.width / 2.0
return bubbleView
}
// MARK: Magic
public func bubbleCompleted(numBubbleCompleted : Int) {
if animateToBubbleQueue.isEmpty {
if let startBubble = getStartBubble(numBubbleCompleted) {
animateToBubbleQueue.append(startBubble)
checkBubbleCompleted(startBubble, start: lastBubbleCompleted++)
}
} else {
for num in animateToBubbleQueue {
if num >= numBubbleCompleted { return }
}
animateToBubbleQueue.append(numBubbleCompleted)
}
}
private func removeAnimatedBubbleFromQueueAndContinue() {
if !animateToBubbleQueue.isEmpty {
animateToBubbleQueue.removeAtIndex(0)
if !animateToBubbleQueue.isEmpty {
if let startBubble = getStartBubble(animateToBubbleQueue[0]) {
checkBubbleCompleted(startBubble, start: lastBubbleCompleted++)
}
}
}
}
private func getStartBubble(numBubbleCompleted : Int) -> Int? {
var startBubble = Int()
if numBubbleCompleted >= bubbleArray.count {
if lastBubbleCompleted == bubbleArray.count { return nil }
startBubble = bubbleArray.count
} else {
if lastBubbleCompleted >= numBubbleCompleted { return nil }
startBubble = numBubbleCompleted
}
return startBubble
}
private func checkBubbleCompleted(numBubbleCompleted : Int, start : Int) {
var frame = bubbleArray[start].frame
var newFrame = CGRectMake(frame.size.width / 2.0, frame.size.height / 2.0, 0, 0)
var temporaryBubble = getBubbleView(frame, number: start+1)
var labelView = temporaryBubble.subviews[0] as UILabel
labelView.textColor = bubbleTextColorForCompleted
var tempBubbleCornerRadius = temporaryBubble.layer.cornerRadius
temporaryBubble.layer.cornerRadius = 0.0 // so we can animate the corner radius
labelView.removeFromSuperview() // so we can add it overtop teh new filling bubble
temporaryBubble.frame = newFrame
temporaryBubble.backgroundColor = bubbleBackgroundColorForCompleted
bubbleArray[start].addSubview(temporaryBubble)
bubbleArray[start].addSubview(labelView)
// Animate the first bubble filling iwth its new color
UIView.animateWithDuration(0.4, animations: { () -> Void in
temporaryBubble.frame = CGRectMake(0, 0, self.bubbleArray[start].frame.size.width, self.bubbleArray[start].frame.size.height)
temporaryBubble.layer.cornerRadius = tempBubbleCornerRadius
}, completion: { (finished) -> Void in
// Change the original bubble color and then remove the covering ones
self.bubbleArray[start].backgroundColor = self.bubbleBackgroundColorForCompleted
temporaryBubble.removeFromSuperview()
labelView.removeFromSuperview()
if start < numBubbleCompleted && start+1 < self.bubbleArray.count {
var newLine : UIView = UIView()
newLine.backgroundColor = self.lineColorForCompleted
newLine.frame = self.connectLineArray[start].frame
// create the line with a frame collapsed in height to reach the edge of the bubble
if (self.bubbleAllignment == BubbleAllignment.Vertical) {
newLine.frame.size = CGSizeMake(newLine.frame.size.width, self.bubbleArray[start].frame.size.width / 2.0)
} else {
newLine.frame.size = CGSizeMake(self.bubbleArray[start].frame.size.width / 2.0, newLine.frame.size.height)
}
newLine.frame.origin = CGPointMake(0, 0)
self.connectLineArray[start].addSubview(newLine)
UIView.animateWithDuration(0.4, animations: { () -> Void in
newLine.frame.size = self.connectLineArray[start].frame.size
}, completion: { (finished) -> Void in
// change the original line's color and then remove the covering one
self.connectLineArray[start].backgroundColor = self.lineColorForCompleted
newLine.removeFromSuperview()
})
// Do the same thing as we did for the other bubble
temporaryBubble = self.getBubbleView(frame, number: start + 2)
labelView = temporaryBubble.subviews[0] as UILabel
labelView.removeFromSuperview() // remove it so we can add it overtop of the new filling bubble
temporaryBubble.frame = newFrame
temporaryBubble.backgroundColor = self.bubbleBackgroundColorForNextToComplete
tempBubbleCornerRadius = temporaryBubble.layer.cornerRadius
temporaryBubble.layer.cornerRadius = 0.0
self.bubbleArray[start+1].addSubview(temporaryBubble)
self.bubbleArray[start+1].addSubview(labelView)
UIView.animateWithDuration(0.4, animations: { () -> Void in
temporaryBubble.frame = CGRectMake(0, 0, self.bubbleArray[start+1].frame.size.width, self.bubbleArray[start+1].frame.size.height)
temporaryBubble.layer.cornerRadius = tempBubbleCornerRadius
}, completion: { (finished) -> Void in
self.bubbleArray[start+1].backgroundColor = self.bubbleBackgroundColorForNextToComplete
temporaryBubble.removeFromSuperview()
labelView.removeFromSuperview()
if (start+1 < numBubbleCompleted) {
self.checkBubbleCompleted(numBubbleCompleted, start: self.lastBubbleCompleted++)
} else {
self.removeAnimatedBubbleFromQueueAndContinue()
}
})
} else {
self.removeAnimatedBubbleFromQueueAndContinue()
}
})
}
}
| mit |
kylelol/KKFloatingActionButton | ExampleTests/ExampleTests.swift | 1 | 904 | //
// ExampleTests.swift
// ExampleTests
//
// Created by Kyle Kirkland on 7/12/15.
// Copyright (c) 2015 Kyle Kirkland. All rights reserved.
//
import UIKit
import XCTest
class ExampleTests: 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 |
eofster/Telephone | UseCases/LazyDiscardingContactMatchingIndex.swift | 1 | 1589 | //
// LazyDiscardingContactMatchingIndex.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
public final class LazyDiscardingContactMatchingIndex {
private var origin: ContactMatchingIndex!
private let factory: ContactMatchingIndexFactory
public init(factory: ContactMatchingIndexFactory) {
self.factory = factory
}
private func createOriginIfNeeded() {
if origin == nil {
origin = factory.make()
}
}
}
extension LazyDiscardingContactMatchingIndex: ContactMatchingIndex {
public func contact(forPhone phone: ExtractedPhoneNumber) -> MatchedContact? {
createOriginIfNeeded()
return origin.contact(forPhone: phone)
}
public func contact(forEmail email: NormalizedLowercasedString) -> MatchedContact? {
createOriginIfNeeded()
return origin.contact(forEmail: email)
}
}
extension LazyDiscardingContactMatchingIndex: ContactsChangeEventTarget {
public func contactsDidChange() {
origin = nil
}
}
| gpl-3.0 |
aschwaighofer/swift | stdlib/public/core/SequenceAlgorithms.swift | 1 | 31714 | //===--- SequenceAlgorithms.swift -----------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// enumerated()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a sequence of pairs (*n*, *x*), where *n* represents a
/// consecutive integer starting at zero and *x* represents an element of
/// the sequence.
///
/// This example enumerates the characters of the string "Swift" and prints
/// each character along with its place in the string.
///
/// for (n, c) in "Swift".enumerated() {
/// print("\(n): '\(c)'")
/// }
/// // Prints "0: 'S'"
/// // Prints "1: 'w'"
/// // Prints "2: 'i'"
/// // Prints "3: 'f'"
/// // Prints "4: 't'"
///
/// When you enumerate a collection, the integer part of each pair is a counter
/// for the enumeration, but is not necessarily the index of the paired value.
/// These counters can be used as indices only in instances of zero-based,
/// integer-indexed collections, such as `Array` and `ContiguousArray`. For
/// other collections the counters may be out of range or of the wrong type
/// to use as an index. To iterate over the elements of a collection with its
/// indices, use the `zip(_:_:)` function.
///
/// This example iterates over the indices and elements of a set, building a
/// list consisting of indices of names with five or fewer letters.
///
/// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
/// var shorterIndices: [Set<String>.Index] = []
/// for (i, name) in zip(names.indices, names) {
/// if name.count <= 5 {
/// shorterIndices.append(i)
/// }
/// }
///
/// Now that the `shorterIndices` array holds the indices of the shorter
/// names in the `names` set, you can use those indices to access elements in
/// the set.
///
/// for i in shorterIndices {
/// print(names[i])
/// }
/// // Prints "Sofia"
/// // Prints "Mateo"
///
/// - Returns: A sequence of pairs enumerating the sequence.
///
/// - Complexity: O(1)
@inlinable // protocol-only
public func enumerated() -> EnumeratedSequence<Self> {
return EnumeratedSequence(_base: self)
}
}
//===----------------------------------------------------------------------===//
// min(), max()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns the minimum element in the sequence, using the given predicate as
/// the comparison between elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// This example shows how to use the `min(by:)` method on a
/// dictionary to find the key-value pair with the lowest value.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// let leastHue = hues.min { a, b in a.value < b.value }
/// print(leastHue)
/// // Prints "Optional((key: "Coral", value: 16))"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The sequence's minimum element, according to
/// `areInIncreasingOrder`. If the sequence has no elements, returns
/// `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable // protocol-only
@warn_unqualified_access
public func min(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Element? {
var it = makeIterator()
guard var result = it.next() else { return nil }
while let e = it.next() {
if try areInIncreasingOrder(e, result) { result = e }
}
return result
}
/// Returns the maximum element in the sequence, using the given predicate
/// as the comparison between elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// This example shows how to use the `max(by:)` method on a
/// dictionary to find the key-value pair with the highest value.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// let greatestHue = hues.max { a, b in a.value < b.value }
/// print(greatestHue)
/// // Prints "Optional((key: "Heliotrope", value: 296))"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`.
/// - Returns: The sequence's maximum element if the sequence is not empty;
/// otherwise, `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable // protocol-only
@warn_unqualified_access
public func max(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Element? {
var it = makeIterator()
guard var result = it.next() else { return nil }
while let e = it.next() {
if try areInIncreasingOrder(result, e) { result = e }
}
return result
}
}
extension Sequence where Element: Comparable {
/// Returns the minimum element in the sequence.
///
/// This example finds the smallest value in an array of height measurements.
///
/// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
/// let lowestHeight = heights.min()
/// print(lowestHeight)
/// // Prints "Optional(58.5)"
///
/// - Returns: The sequence's minimum element. If the sequence has no
/// elements, returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
@warn_unqualified_access
public func min() -> Element? {
return self.min(by: <)
}
/// Returns the maximum element in the sequence.
///
/// This example finds the largest value in an array of height measurements.
///
/// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
/// let greatestHeight = heights.max()
/// print(greatestHeight)
/// // Prints "Optional(67.5)"
///
/// - Returns: The sequence's maximum element. If the sequence has no
/// elements, returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
@warn_unqualified_access
public func max() -> Element? {
return self.max(by: <)
}
}
//===----------------------------------------------------------------------===//
// starts(with:)
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether the initial elements of the
/// sequence are equivalent to the elements in another sequence, using
/// the given predicate as the equivalence test.
///
/// The predicate must be a *equivalence relation* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areEquivalent(a, a)` is always `true`. (Reflexivity)
/// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
/// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then
/// `areEquivalent(a, c)` is also `true`. (Transitivity)
///
/// - Parameters:
/// - possiblePrefix: A sequence to compare to this sequence.
/// - areEquivalent: A predicate that returns `true` if its two arguments
/// are equivalent; otherwise, `false`.
/// - Returns: `true` if the initial elements of the sequence are equivalent
/// to the elements of `possiblePrefix`; otherwise, `false`. If
/// `possiblePrefix` has no elements, the return value is `true`.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `possiblePrefix`.
@inlinable
public func starts<PossiblePrefix: Sequence>(
with possiblePrefix: PossiblePrefix,
by areEquivalent: (Element, PossiblePrefix.Element) throws -> Bool
) rethrows -> Bool {
var possiblePrefixIterator = possiblePrefix.makeIterator()
for e0 in self {
if let e1 = possiblePrefixIterator.next() {
if try !areEquivalent(e0, e1) {
return false
}
}
else {
return true
}
}
return possiblePrefixIterator.next() == nil
}
}
extension Sequence where Element: Equatable {
/// Returns a Boolean value indicating whether the initial elements of the
/// sequence are the same as the elements in another sequence.
///
/// This example tests whether one countable range begins with the elements
/// of another countable range.
///
/// let a = 1...3
/// let b = 1...10
///
/// print(b.starts(with: a))
/// // Prints "true"
///
/// Passing a sequence with no elements or an empty collection as
/// `possiblePrefix` always results in `true`.
///
/// print(b.starts(with: []))
/// // Prints "true"
///
/// - Parameter possiblePrefix: A sequence to compare to this sequence.
/// - Returns: `true` if the initial elements of the sequence are the same as
/// the elements of `possiblePrefix`; otherwise, `false`. If
/// `possiblePrefix` has no elements, the return value is `true`.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `possiblePrefix`.
@inlinable
public func starts<PossiblePrefix: Sequence>(
with possiblePrefix: PossiblePrefix
) -> Bool where PossiblePrefix.Element == Element {
return self.starts(with: possiblePrefix, by: ==)
}
}
//===----------------------------------------------------------------------===//
// elementsEqual()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether this sequence and another
/// sequence contain equivalent elements in the same order, using the given
/// predicate as the equivalence test.
///
/// At least one of the sequences must be finite.
///
/// The predicate must be a *equivalence relation* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areEquivalent(a, a)` is always `true`. (Reflexivity)
/// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
/// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then
/// `areEquivalent(a, c)` is also `true`. (Transitivity)
///
/// - Parameters:
/// - other: A sequence to compare to this sequence.
/// - areEquivalent: A predicate that returns `true` if its two arguments
/// are equivalent; otherwise, `false`.
/// - Returns: `true` if this sequence and `other` contain equivalent items,
/// using `areEquivalent` as the equivalence test; otherwise, `false.`
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func elementsEqual<OtherSequence: Sequence>(
_ other: OtherSequence,
by areEquivalent: (Element, OtherSequence.Element) throws -> Bool
) rethrows -> Bool {
var iter1 = self.makeIterator()
var iter2 = other.makeIterator()
while true {
switch (iter1.next(), iter2.next()) {
case let (e1?, e2?):
if try !areEquivalent(e1, e2) {
return false
}
case (_?, nil), (nil, _?): return false
case (nil, nil): return true
}
}
}
}
extension Sequence where Element: Equatable {
/// Returns a Boolean value indicating whether this sequence and another
/// sequence contain the same elements in the same order.
///
/// At least one of the sequences must be finite.
///
/// This example tests whether one countable range shares the same elements
/// as another countable range and an array.
///
/// let a = 1...3
/// let b = 1...10
///
/// print(a.elementsEqual(b))
/// // Prints "false"
/// print(a.elementsEqual([1, 2, 3]))
/// // Prints "true"
///
/// - Parameter other: A sequence to compare to this sequence.
/// - Returns: `true` if this sequence and `other` contain the same elements
/// in the same order.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func elementsEqual<OtherSequence: Sequence>(
_ other: OtherSequence
) -> Bool where OtherSequence.Element == Element {
return self.elementsEqual(other, by: ==)
}
}
//===----------------------------------------------------------------------===//
// lexicographicallyPrecedes()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether the sequence precedes another
/// sequence in a lexicographical (dictionary) ordering, using the given
/// predicate to compare elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// - Parameters:
/// - other: A sequence to compare to this sequence.
/// - areInIncreasingOrder: A predicate that returns `true` if its first
/// argument should be ordered before its second argument; otherwise,
/// `false`.
/// - Returns: `true` if this sequence precedes `other` in a dictionary
/// ordering as ordered by `areInIncreasingOrder`; otherwise, `false`.
///
/// - Note: This method implements the mathematical notion of lexicographical
/// ordering, which has no connection to Unicode. If you are sorting
/// strings to present to the end user, use `String` APIs that perform
/// localized comparison instead.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func lexicographicallyPrecedes<OtherSequence: Sequence>(
_ other: OtherSequence,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Bool
where OtherSequence.Element == Element {
var iter1 = self.makeIterator()
var iter2 = other.makeIterator()
while true {
if let e1 = iter1.next() {
if let e2 = iter2.next() {
if try areInIncreasingOrder(e1, e2) {
return true
}
if try areInIncreasingOrder(e2, e1) {
return false
}
continue // Equivalent
}
return false
}
return iter2.next() != nil
}
}
}
extension Sequence where Element: Comparable {
/// Returns a Boolean value indicating whether the sequence precedes another
/// sequence in a lexicographical (dictionary) ordering, using the
/// less-than operator (`<`) to compare elements.
///
/// This example uses the `lexicographicallyPrecedes` method to test which
/// array of integers comes first in a lexicographical ordering.
///
/// let a = [1, 2, 2, 2]
/// let b = [1, 2, 3, 4]
///
/// print(a.lexicographicallyPrecedes(b))
/// // Prints "true"
/// print(b.lexicographicallyPrecedes(b))
/// // Prints "false"
///
/// - Parameter other: A sequence to compare to this sequence.
/// - Returns: `true` if this sequence precedes `other` in a dictionary
/// ordering; otherwise, `false`.
///
/// - Note: This method implements the mathematical notion of lexicographical
/// ordering, which has no connection to Unicode. If you are sorting
/// strings to present to the end user, use `String` APIs that
/// perform localized comparison.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func lexicographicallyPrecedes<OtherSequence: Sequence>(
_ other: OtherSequence
) -> Bool where OtherSequence.Element == Element {
return self.lexicographicallyPrecedes(other, by: <)
}
}
//===----------------------------------------------------------------------===//
// contains()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether the sequence contains an
/// element that satisfies the given predicate.
///
/// You can use the predicate to check for an element of a type that
/// doesn't conform to the `Equatable` protocol, such as the
/// `HTTPResponse` enumeration in this example.
///
/// enum HTTPResponse {
/// case ok
/// case error(Int)
/// }
///
/// let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)]
/// let hadError = lastThreeResponses.contains { element in
/// if case .error = element {
/// return true
/// } else {
/// return false
/// }
/// }
/// // 'hadError' == true
///
/// Alternatively, a predicate can be satisfied by a range of `Equatable`
/// elements or a general condition. This example shows how you can check an
/// array for an expense greater than $100.
///
/// let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
/// let hasBigPurchase = expenses.contains { $0 > 100 }
/// // 'hasBigPurchase' == true
///
/// - Parameter predicate: A closure that takes an element of the sequence
/// as its argument and returns a Boolean value that indicates whether
/// the passed element represents a match.
/// - Returns: `true` if the sequence contains an element that satisfies
/// `predicate`; otherwise, `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func contains(
where predicate: (Element) throws -> Bool
) rethrows -> Bool {
for e in self {
if try predicate(e) {
return true
}
}
return false
}
/// Returns a Boolean value indicating whether every element of a sequence
/// satisfies a given predicate.
///
/// The following code uses this method to test whether all the names in an
/// array have at least five characters:
///
/// let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
/// let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 })
/// // allHaveAtLeastFive == true
///
/// - Parameter predicate: A closure that takes an element of the sequence
/// as its argument and returns a Boolean value that indicates whether
/// the passed element satisfies a condition.
/// - Returns: `true` if the sequence contains only elements that satisfy
/// `predicate`; otherwise, `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func allSatisfy(
_ predicate: (Element) throws -> Bool
) rethrows -> Bool {
return try !contains { try !predicate($0) }
}
}
extension Sequence where Element: Equatable {
/// Returns a Boolean value indicating whether the sequence contains the
/// given element.
///
/// This example checks to see whether a favorite actor is in an array
/// storing a movie's cast.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// print(cast.contains("Marlon"))
/// // Prints "true"
/// print(cast.contains("James"))
/// // Prints "false"
///
/// - Parameter element: The element to find in the sequence.
/// - Returns: `true` if the element was found in the sequence; otherwise,
/// `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func contains(_ element: Element) -> Bool {
if let result = _customContainsEquatableElement(element) {
return result
} else {
return self.contains { $0 == element }
}
}
}
//===----------------------------------------------------------------------===//
// reduce()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns the result of combining the elements of the sequence using the
/// given closure.
///
/// Use the `reduce(_:_:)` method to produce a single value from the elements
/// of an entire sequence. For example, you can use this method on an array
/// of numbers to find their sum or product.
///
/// The `nextPartialResult` closure is called sequentially with an
/// accumulating value initialized to `initialResult` and each element of
/// the sequence. This example shows how to find the sum of an array of
/// numbers.
///
/// let numbers = [1, 2, 3, 4]
/// let numberSum = numbers.reduce(0, { x, y in
/// x + y
/// })
/// // numberSum == 10
///
/// When `numbers.reduce(_:_:)` is called, the following steps occur:
///
/// 1. The `nextPartialResult` closure is called with `initialResult`---`0`
/// in this case---and the first element of `numbers`, returning the sum:
/// `1`.
/// 2. The closure is called again repeatedly with the previous call's return
/// value and each element of the sequence.
/// 3. When the sequence is exhausted, the last value returned from the
/// closure is returned to the caller.
///
/// If the sequence has no elements, `nextPartialResult` is never executed
/// and `initialResult` is the result of the call to `reduce(_:_:)`.
///
/// - Parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// `initialResult` is passed to `nextPartialResult` the first time the
/// closure is executed.
/// - nextPartialResult: A closure that combines an accumulating value and
/// an element of the sequence into a new accumulating value, to be used
/// in the next call of the `nextPartialResult` closure or returned to
/// the caller.
/// - Returns: The final accumulated value. If the sequence has no elements,
/// the result is `initialResult`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult:
(_ partialResult: Result, Element) throws -> Result
) rethrows -> Result {
var accumulator = initialResult
for element in self {
accumulator = try nextPartialResult(accumulator, element)
}
return accumulator
}
/// Returns the result of combining the elements of the sequence using the
/// given closure.
///
/// Use the `reduce(into:_:)` method to produce a single value from the
/// elements of an entire sequence. For example, you can use this method on an
/// array of integers to filter adjacent equal entries or count frequencies.
///
/// This method is preferred over `reduce(_:_:)` for efficiency when the
/// result is a copy-on-write type, for example an Array or a Dictionary.
///
/// The `updateAccumulatingResult` closure is called sequentially with a
/// mutable accumulating value initialized to `initialResult` and each element
/// of the sequence. This example shows how to build a dictionary of letter
/// frequencies of a string.
///
/// let letters = "abracadabra"
/// let letterCount = letters.reduce(into: [:]) { counts, letter in
/// counts[letter, default: 0] += 1
/// }
/// // letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]
///
/// When `letters.reduce(into:_:)` is called, the following steps occur:
///
/// 1. The `updateAccumulatingResult` closure is called with the initial
/// accumulating value---`[:]` in this case---and the first character of
/// `letters`, modifying the accumulating value by setting `1` for the key
/// `"a"`.
/// 2. The closure is called again repeatedly with the updated accumulating
/// value and each element of the sequence.
/// 3. When the sequence is exhausted, the accumulating value is returned to
/// the caller.
///
/// If the sequence has no elements, `updateAccumulatingResult` is never
/// executed and `initialResult` is the result of the call to
/// `reduce(into:_:)`.
///
/// - Parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - updateAccumulatingResult: A closure that updates the accumulating
/// value with an element of the sequence.
/// - Returns: The final accumulated value. If the sequence has no elements,
/// the result is `initialResult`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func reduce<Result>(
into initialResult: __owned Result,
_ updateAccumulatingResult:
(_ partialResult: inout Result, Element) throws -> ()
) rethrows -> Result {
var accumulator = initialResult
for element in self {
try updateAccumulatingResult(&accumulator, element)
}
return accumulator
}
}
//===----------------------------------------------------------------------===//
// reversed()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns an array containing the elements of this sequence in reverse
/// order.
///
/// The sequence must be finite.
///
/// - Returns: An array containing the elements of this sequence in
/// reverse order.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func reversed() -> [Element] {
// FIXME(performance): optimize to 1 pass? But Array(self) can be
// optimized to a memcpy() sometimes. Those cases are usually collections,
// though.
var result = Array(self)
let count = result.count
for i in 0..<count/2 {
result.swapAt(i, count - ((i + 1) as Int))
}
return result
}
}
//===----------------------------------------------------------------------===//
// flatMap()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns an array containing the concatenated results of calling the
/// given transformation with each element of this sequence.
///
/// Use this method to receive a single-level collection when your
/// transformation produces a sequence or collection for each element.
///
/// In this example, note the difference in the result of using `map` and
/// `flatMap` with a transformation that returns an array.
///
/// let numbers = [1, 2, 3, 4]
///
/// let mapped = numbers.map { Array(repeating: $0, count: $0) }
/// // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
///
/// let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
/// // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
///
/// In fact, `s.flatMap(transform)` is equivalent to
/// `Array(s.map(transform).joined())`.
///
/// - Parameter transform: A closure that accepts an element of this
/// sequence as its argument and returns a sequence or collection.
/// - Returns: The resulting flattened array.
///
/// - Complexity: O(*m* + *n*), where *n* is the length of this sequence
/// and *m* is the length of the result.
@inlinable
public func flatMap<SegmentOfResult: Sequence>(
_ transform: (Element) throws -> SegmentOfResult
) rethrows -> [SegmentOfResult.Element] {
var result: [SegmentOfResult.Element] = []
for element in self {
result.append(contentsOf: try transform(element))
}
return result
}
}
extension Sequence {
/// Returns an array containing the non-`nil` results of calling the given
/// transformation with each element of this sequence.
///
/// Use this method to receive an array of non-optional values when your
/// transformation produces an optional value.
///
/// In this example, note the difference in the result of using `map` and
/// `compactMap` with a transformation that returns an optional `Int` value.
///
/// let possibleNumbers = ["1", "2", "three", "///4///", "5"]
///
/// let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
/// // [1, 2, nil, nil, 5]
///
/// let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
/// // [1, 2, 5]
///
/// - Parameter transform: A closure that accepts an element of this
/// sequence as its argument and returns an optional value.
/// - Returns: An array of the non-`nil` results of calling `transform`
/// with each element of the sequence.
///
/// - Complexity: O(*m* + *n*), where *n* is the length of this sequence
/// and *m* is the length of the result.
@inlinable // protocol-only
public func compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
return try _compactMap(transform)
}
// The implementation of flatMap accepting a closure with an optional result.
// Factored out into a separate functions in order to be used in multiple
// overloads.
@inlinable // protocol-only
@inline(__always)
public func _compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
var result: [ElementOfResult] = []
for element in self {
if let newElement = try transform(element) {
result.append(newElement)
}
}
return result
}
}
| apache-2.0 |
joerocca/GitHawk | Classes/Issues/ReferencedCommit/IssueReferencedCommitCell.swift | 1 | 383 | //
// IssueReferencedCell.swift
// Freetime
//
// Created by Ryan Nystrom on 7/9/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SnapKit
final class IssueReferencedCommitCell: AttributedStringCell {
// MARK: Public API
func configure(_ model: IssueReferencedCommitModel) {
set(attributedText: model.attributedText)
}
}
| mit |
allevato/SwiftCGI | Sources/SwiftCGI/CGIServer.swift | 1 | 2772 | // Copyright 2015 Tony Allevato
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
/// The server implementation used when the application is running as a CGI process.
class CGIServer: ServerProtocol {
/// The environment variable dictionary that contains the headers for the request.
private let environment: [String: String]
/// The input stream from which the request body can be read.
private let requestStream: InputStream
/// The output stream to which the response body can be written.
private let responseStream: OutputStream
/// Creates a new server with the given environment, request stream, and response stream.
///
/// This initializer exists primarily for testing.
///
/// - Parameter environment: The dictionary containing the environment variables from which the
/// request headers will be read.
/// - Parameter requestStream: The input stream from which the request body can be read.
/// - Parameter responseStream: The output stream to which the response body can be written.
init(environment: [String: String], requestStream: InputStream, responseStream: OutputStream) {
self.environment = environment
self.requestStream = requestStream
self.responseStream = responseStream
}
/// Creates a new server that takes its environment from the process's environment and that uses
/// the `stdin` and `stdout` file descriptors as its request and response streams, respectively.
convenience init() {
let process = NSProcessInfo.processInfo()
let environment = process.environment
let requestStream =
BufferingInputStream(inputStream: FileInputStream(fileDescriptor: STDIN_FILENO))
let responseStream =
BufferingOutputStream(outputStream: FileOutputStream(fileDescriptor: STDOUT_FILENO))
self.init(
environment: environment, requestStream: requestStream, responseStream: responseStream)
}
func listen(handler: (HTTPRequest, HTTPResponse) -> Void) {
let request = CGIHTTPRequest(environment: environment, contentStream: requestStream)
let response = CGIHTTPResponse(contentStream: responseStream)
handler(request, response)
responseStream.flush()
}
}
| apache-2.0 |
dasdom/Swiftandpainless | SwiftAndPainlessPlayground.playground/Pages/Functions - Basics III.xcplaygroundpage/Contents.swift | 1 | 525 | import Foundation
/*:
[⬅️](@previous) [➡️](@next)
# Functions: Basics III
## Returning Tuples
*/
func minMax(numbers: Int...) -> (min: Int, max: Int) {
precondition(numbers.count > 0)
var min = Int.max
var max = Int.min
for number in numbers {
if number <= min {
min = number
}
if number >= max {
max = number
}
}
return (min, max)
}
let result = minMax(numbers: 23, 3, 42, 5, 666)
let min = result.min
let max = result.max
print("min: \(result.0), max: \(result.1)")
| mit |
davecom/SwiftSimpleNeuralNetwork | Sources/Layer.swift | 1 | 3056 | //
// Layer.swift
// SwiftSimpleNeuralNetwork
//
// Copyright 2016-2019 David Kopec
//
// 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.
class Layer {
let previousLayer: Layer?
var neurons: [Neuron]
var outputCache: [Double]
var hasBias: Bool = false
// for future use in deserializing networks
init(previousLayer: Layer? = nil, neurons: [Neuron] = [Neuron]()) {
self.previousLayer = previousLayer
self.neurons = neurons
self.outputCache = Array<Double>(repeating: 0.0, count: neurons.count)
}
// main init
init(previousLayer: Layer? = nil, numNeurons: Int, activationFunction: @escaping (Double) -> Double, derivativeActivationFunction: @escaping (Double)-> Double, learningRate: Double, hasBias: Bool = false) {
self.previousLayer = previousLayer
self.neurons = Array<Neuron>()
self.hasBias = hasBias
for _ in 0..<numNeurons {
self.neurons.append(Neuron(weights: randomWeights(number: previousLayer?.neurons.count ?? 0), activationFunction: activationFunction, derivativeActivationFunction: derivativeActivationFunction, learningRate: learningRate))
}
if hasBias {
self.neurons.append(BiasNeuron(weights: randomWeights(number: previousLayer?.neurons.count ?? 0)))
}
self.outputCache = Array<Double>(repeating: 0.0, count: neurons.count)
}
func outputs(inputs: [Double]) -> [Double] {
if previousLayer == nil { // input layer (first layer)
outputCache = hasBias ? inputs + [1.0] : inputs
} else { // hidden layer or output layer
outputCache = neurons.map { $0.output(inputs: inputs) }
}
return outputCache
}
// should only be called on an output layer
func calculateDeltasForOutputLayer(expected: [Double]) {
for n in 0..<neurons.count {
neurons[n].delta = neurons[n].derivativeActivationFunction( neurons[n].inputCache) * (expected[n] - outputCache[n])
}
}
// should not be called on output layer
func calculateDeltasForHiddenLayer(nextLayer: Layer) {
for (index, neuron) in neurons.enumerated() {
let nextWeights = nextLayer.neurons.map { $0.weights[index] }
let nextDeltas = nextLayer.neurons.map { $0.delta }
let sumOfWeightsXDeltas = dotProduct(nextWeights, nextDeltas)
neuron.delta = neuron.derivativeActivationFunction( neuron.inputCache) * sumOfWeightsXDeltas
}
}
}
| apache-2.0 |
austinzheng/swift-compiler-crashes | crashes-duplicates/12567-swift-sourcemanager-getmessage.swift | 11 | 238 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
init( ) {
{
protocol b {
class A {
func f( ) {
deinit {
class
case ,
| mit |
mightydeveloper/swift | test/SILPasses/linker.swift | 10 | 942 | // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %target-swift-frontend -emit-module %S/Inputs/linker_pass_input.swift -o %t/Swift.swiftmodule -parse-stdlib -parse-as-library -module-name Swift -sil-serialize-all -module-link-name swiftCore
// RUN: %target-swift-frontend %s -O -I %t -sil-debug-serialization -o - -emit-sil | FileCheck %s
// CHECK: sil public_external [fragile] @_TFs11doSomethingFT_T_ : $@convention(thin) () -> () {
doSomething()
// Make sure we are not linking doSomethign2 because it is marked with 'noimport'
// CHECK: sil [_semantics "stdlib_binary_only"] @_TFs12doSomething2FT_T_ : $@convention(thin) () -> ()
// CHECK-NOT: return
doSomething2()
// CHECK: sil public_external [fragile] [noinline] @{{.*}}callDoSomething3{{.*}}
// CHECK: sil @unknown
// CHECK: sil [fragile] [noinline] [_semantics "stdlib_binary_only"] @{{.*}}doSomething3{{.*}}
// CHECK-NOT: return
// CHECK: sil {{.*}} @_TFVs1AC
callDoSomething3()
| apache-2.0 |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/0215-swift-optional-swift-infixoperatordecl.swift | 13 | 269 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
>(f: B<{ }
})
}
func prefix(with: ng) -> <T>(() -> T)
| apache-2.0 |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/2125-swift-completegenerictyperesolver-resolvedependentmembertype.swift | 13 | 382 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
lass func g<T> () {
class A {
print() -> T) -> T -> Any {
}
enum b : C) {
}
case .a<U {
protocol P {
class a {
}
for b {
protocol A {
}
}
}
}
func b: Array<T.Element>
| apache-2.0 |
Jnosh/swift | test/decl/protocol/req/unavailable.swift | 5 | 1054 | // RUN: %target-typecheck-verify-swift
// An @objc protocol can have 'unavailable'
// methods. They are treated as if they
// were marked optional
@objc protocol Proto {
@objc @available(*,unavailable) optional func bad()
func good()
}
class Foo : Proto {
@objc func good() {}
}
// Reject protocols with 'unavailable' requirements
// if a protocol is not marked @objc.
protocol NonObjCProto {
@available(*,unavailable) func bad() // expected-error {{protocol members can only be marked unavailable in an @objc protocol}} expected-note {{protocol requires function 'bad()'}}
func good()
}
class Bar : NonObjCProto { // expected-error {{type 'Bar' does not conform to protocol 'NonObjCProto'}}
func good() {}
}
// Warn about unavailable witnesses.
protocol P {
func foo(bar: Foo) // expected-note{{requirement 'foo(bar:)' declared here}}
}
struct ConformsToP : P {
@available(*, unavailable)
func foo(bar: Foo) { } // expected-warning{{unavailable instance method 'foo(bar:)' was used to satisfy a requirement of protocol 'P'}}
}
| apache-2.0 |
jeffreybergier/Hipstapaper | Hipstapaper/Packages/V3Localize/Sources/V3Localize/PropertyWrappers/BrowserShareList.swift | 1 | 2568 | //
// Created by Jeffrey Bergier on 2022/08/03.
//
// MIT License
//
// Copyright (c) 2021 Jeffrey Bergier
//
// 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 SwiftUI
import Umbrella
@propertyWrapper
public struct BrowserShareList: DynamicProperty {
public struct Value {
public var title: LocalizedString
public var shareErrorSubtitle: LocalizedString
public var done: ActionLocalization
public var copy: ActionLocalization
public var error: ActionLocalization
public var shareSaved: ActionLocalization
public var shareCurrent: ActionLocalization
internal init(_ b: LocalizeBundle) {
self.title = b.localized(key: Noun.share.rawValue)
self.shareErrorSubtitle = b.localized(key: Phrase.shareError.rawValue)
self.done = Action.doneGeneric.localized(b)
self.copy = Action.copyToClipboard.localized(b)
self.error = Action.shareError.localized(b)
self.shareSaved = Action.shareSingleSaved.localized(b)
self.shareCurrent = Action.shareSingleCurrent.localized(b)
}
}
@Localize private var bundle
public init() {}
public var wrappedValue: Value {
Value(self.bundle)
}
public func key(_ input: LocalizationKey) -> LocalizedString {
self.bundle.localized(key: input)
}
}
| mit |
radu-costea/ATests | ATests/ATests/UI/CustomViews/PickerViewController.swift | 1 | 1754 | //
// PickerViewController.swift
// ATests
//
// Created by Radu Costea on 19/06/16.
// Copyright © 2016 Radu Costea. All rights reserved.
//
import UIKit
class PickerViewControllerColumn {
var count: Int
var titleBuilder: (Int) -> String
var selected: Int
init(count: Int, selected: Int, titleBuilder: (Int) -> String) {
self.count = count
self.titleBuilder = titleBuilder
self.selected = selected
}
}
class PickerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet var picker: UIPickerView!
var columns: [PickerViewControllerColumn]!
var onCompletion: ((PickerViewController) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
(0..<columns.count).forEach{ picker.selectRow(columns[$0].selected, inComponent: $0, animated: false) }
}
/// MARK: -
/// MARK: PickerViewDelegate
// returns the number of 'columns' to display.
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return columns.count;
}
// returns the # of rows in each component..
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return columns[component].count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return columns[component].titleBuilder(row)
}
/// MARK: -
/// MARK: Actions
@IBAction func didTapDone(sender: AnyObject?) {
(0..<columns.count).forEach{ columns[$0].selected = picker.selectedRowInComponent($0) }
onCompletion?(self)
}
}
| mit |
Ryan-Vanderhoef/Antlers | AppIdeaTests/AppIdeaTests.swift | 1 | 908 | //
// AppIdeaTests.swift
// AppIdeaTests
//
// Created by Ryan Vanderhoef on 7/14/15.
// Copyright (c) 2015 Ryan Vanderhoef. All rights reserved.
//
import UIKit
import XCTest
class AppIdeaTests: 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 |
atrick/swift | stdlib/public/core/UnicodeScalarProperties.swift | 1 | 61934 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Exposes advanced properties of Unicode.Scalar defined by the Unicode
// Standard.
//===----------------------------------------------------------------------===//
import SwiftShims
extension Unicode.Scalar {
/// A value that provides access to properties of a Unicode scalar that are
/// defined by the Unicode standard.
public struct Properties: Sendable {
@usableFromInline
internal var _scalar: Unicode.Scalar
internal init(_ scalar: Unicode.Scalar) {
self._scalar = scalar
}
}
/// Properties of this scalar defined by the Unicode standard.
///
/// Use this property to access the Unicode properties of a Unicode scalar
/// value. The following code tests whether a string contains any math
/// symbols:
///
/// let question = "Which is larger, 3 * 3 * 3 or 10 + 10 + 10?"
/// let hasMathSymbols = question.unicodeScalars.contains(where: {
/// $0.properties.isMath
/// })
/// // hasMathSymbols == true
public var properties: Properties {
return Properties(self)
}
}
extension Unicode.Scalar.Properties {
// This OptionSet represents the 64 bit integer value returned when asking
// '_swift_stdlib_getBinaryProperties' where each bit indicates a unique
// Unicode defined binary property of a scalar. For example, bit 8 represents
// the 'isAlphabetic' property for scalars.
//
// WARNING: The values below must be kept in-sync with the generation script.
// If one should ever update this list below, be it reordering bits, adding
// new properties, etc., please update the generation script found at:
// 'utils/gen-unicode-data/Sources/GenScalarProps/BinProps.swift'.
fileprivate struct _BinaryProperties: OptionSet {
let rawValue: UInt64
private init(_ rawValue: UInt64) {
self.rawValue = rawValue
}
// Because we defined the labelless init, we lose the memberwise one
// generated, so define that here to satisfy the 'OptionSet' requirement.
init(rawValue: UInt64) {
self.rawValue = rawValue
}
static var changesWhenCaseFolded : Self { Self(1 &<< 0) }
static var changesWhenCaseMapped : Self { Self(1 &<< 1) }
static var changesWhenLowercased : Self { Self(1 &<< 2) }
static var changesWhenNFKCCaseFolded : Self { Self(1 &<< 3) }
static var changesWhenTitlecased : Self { Self(1 &<< 4) }
static var changesWhenUppercased : Self { Self(1 &<< 5) }
static var isASCIIHexDigit : Self { Self(1 &<< 6) }
static var isAlphabetic : Self { Self(1 &<< 7) }
static var isBidiControl : Self { Self(1 &<< 8) }
static var isBidiMirrored : Self { Self(1 &<< 9) }
static var isCaseIgnorable : Self { Self(1 &<< 10) }
static var isCased : Self { Self(1 &<< 11) }
static var isDash : Self { Self(1 &<< 12) }
static var isDefaultIgnorableCodePoint : Self { Self(1 &<< 13) }
static var isDeprecated : Self { Self(1 &<< 14) }
static var isDiacritic : Self { Self(1 &<< 15) }
static var isEmoji : Self { Self(1 &<< 16) }
static var isEmojiModifier : Self { Self(1 &<< 17) }
static var isEmojiModifierBase : Self { Self(1 &<< 18) }
static var isEmojiPresentation : Self { Self(1 &<< 19) }
static var isExtender : Self { Self(1 &<< 20) }
static var isFullCompositionExclusion : Self { Self(1 &<< 21) }
static var isGraphemeBase : Self { Self(1 &<< 22) }
static var isGraphemeExtend : Self { Self(1 &<< 23) }
static var isHexDigit : Self { Self(1 &<< 24) }
static var isIDContinue : Self { Self(1 &<< 25) }
static var isIDSBinaryOperator : Self { Self(1 &<< 26) }
static var isIDSTrinaryOperator : Self { Self(1 &<< 27) }
static var isIDStart : Self { Self(1 &<< 28) }
static var isIdeographic : Self { Self(1 &<< 29) }
static var isJoinControl : Self { Self(1 &<< 30) }
static var isLogicalOrderException : Self { Self(1 &<< 31) }
static var isLowercase : Self { Self(1 &<< 32) }
static var isMath : Self { Self(1 &<< 33) }
static var isNoncharacterCodePoint : Self { Self(1 &<< 34) }
static var isPatternSyntax : Self { Self(1 &<< 35) }
static var isPatternWhitespace : Self { Self(1 &<< 36) }
static var isQuotationMark : Self { Self(1 &<< 37) }
static var isRadical : Self { Self(1 &<< 38) }
static var isSentenceTerminal : Self { Self(1 &<< 39) }
static var isSoftDotted : Self { Self(1 &<< 40) }
static var isTerminalPunctuation : Self { Self(1 &<< 41) }
static var isUnifiedIdeograph : Self { Self(1 &<< 42) }
static var isUppercase : Self { Self(1 &<< 43) }
static var isVariationSelector : Self { Self(1 &<< 44) }
static var isWhitespace : Self { Self(1 &<< 45) }
static var isXIDContinue : Self { Self(1 &<< 46) }
static var isXIDStart : Self { Self(1 &<< 47) }
}
}
/// Boolean properties that are defined by the Unicode Standard.
extension Unicode.Scalar.Properties {
fileprivate var _binaryProperties: _BinaryProperties {
_BinaryProperties(
rawValue: _swift_stdlib_getBinaryProperties(_scalar.value)
)
}
/// A Boolean value indicating whether the scalar is alphabetic.
///
/// Alphabetic scalars are the primary units of alphabets and/or syllabaries.
///
/// This property corresponds to the "Alphabetic" and the "Other_Alphabetic"
/// properties in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isAlphabetic: Bool {
_binaryProperties.contains(.isAlphabetic)
}
/// A Boolean value indicating whether the scalar is an ASCII character
/// commonly used for the representation of hexadecimal numbers.
///
/// The only scalars for which this property is `true` are:
///
/// * U+0030...U+0039: DIGIT ZERO...DIGIT NINE
/// * U+0041...U+0046: LATIN CAPITAL LETTER A...LATIN CAPITAL LETTER F
/// * U+0061...U+0066: LATIN SMALL LETTER A...LATIN SMALL LETTER F
///
/// This property corresponds to the "ASCII_Hex_Digit" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isASCIIHexDigit: Bool {
_binaryProperties.contains(.isASCIIHexDigit)
}
/// A Boolean value indicating whether the scalar is a format control
/// character that has a specific function in the Unicode Bidirectional
/// Algorithm.
///
/// This property corresponds to the "Bidi_Control" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isBidiControl: Bool {
_binaryProperties.contains(.isBidiControl)
}
/// A Boolean value indicating whether the scalar is mirrored in
/// bidirectional text.
///
/// This property corresponds to the "Bidi_Mirrored" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isBidiMirrored: Bool {
_binaryProperties.contains(.isBidiMirrored)
}
/// A Boolean value indicating whether the scalar is a punctuation
/// symbol explicitly called out as a dash in the Unicode Standard or a
/// compatibility equivalent.
///
/// This property corresponds to the "Dash" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isDash: Bool {
_binaryProperties.contains(.isDash)
}
/// A Boolean value indicating whether the scalar is a default-ignorable
/// code point.
///
/// Default-ignorable code points are those that should be ignored by default
/// in rendering (unless explicitly supported). They have no visible glyph or
/// advance width in and of themselves, although they may affect the display,
/// positioning, or adornment of adjacent or surrounding characters.
///
/// This property corresponds to the "Default_Ignorable_Code_Point" and the
/// "Other_Default_Ignorable_Code_point" properties in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isDefaultIgnorableCodePoint: Bool {
_binaryProperties.contains(.isDefaultIgnorableCodePoint)
}
/// A Boolean value indicating whether the scalar is deprecated.
///
/// Scalars are never removed from the Unicode Standard, but the usage of
/// deprecated scalars is strongly discouraged.
///
/// This property corresponds to the "Deprecated" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isDeprecated: Bool {
_binaryProperties.contains(.isDeprecated)
}
/// A Boolean value indicating whether the scalar is a diacritic.
///
/// Diacritics are scalars that linguistically modify the meaning of another
/// scalar to which they apply. Scalars for which this property is `true` are
/// frequently, but not always, combining marks or modifiers.
///
/// This property corresponds to the "Diacritic" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isDiacritic: Bool {
_binaryProperties.contains(.isDiacritic)
}
/// A Boolean value indicating whether the scalar's principal function is
/// to extend the value or shape of a preceding alphabetic scalar.
///
/// Typical extenders are length and iteration marks.
///
/// This property corresponds to the "Extender" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isExtender: Bool {
_binaryProperties.contains(.isExtender)
}
/// A Boolean value indicating whether the scalar is excluded from
/// composition when performing Unicode normalization.
///
/// This property corresponds to the "Full_Composition_Exclusion" property in
/// the [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isFullCompositionExclusion: Bool {
_binaryProperties.contains(.isFullCompositionExclusion)
}
/// A Boolean value indicating whether the scalar is a grapheme base.
///
/// A grapheme base can be thought of as a space-occupying glyph above or
/// below which other non-spacing modifying glyphs can be applied. For
/// example, when the character `é` is represented in its decomposed form,
/// the grapheme base is "e" (U+0065 LATIN SMALL LETTER E) and it is followed
/// by a single grapheme extender, U+0301 COMBINING ACUTE ACCENT.
///
/// The set of scalars for which `isGraphemeBase` is `true` is disjoint by
/// definition from the set for which `isGraphemeExtend` is `true`.
///
/// This property corresponds to the "Grapheme_Base" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isGraphemeBase: Bool {
_binaryProperties.contains(.isGraphemeBase)
}
/// A Boolean value indicating whether the scalar is a grapheme extender.
///
/// A grapheme extender can be thought of primarily as a non-spacing glyph
/// that is applied above or below another glyph. For example, when the
/// character `é` is represented in its decomposed form, the grapheme base is
/// "e" (U+0065 LATIN SMALL LETTER E) and it is followed by a single grapheme
/// extender, U+0301 COMBINING ACUTE ACCENT.
///
/// The set of scalars for which `isGraphemeExtend` is `true` is disjoint by
/// definition from the set for which `isGraphemeBase` is `true`.
///
/// This property corresponds to the "Grapheme_Extend" and the
/// "Other_Grapheme_Extend" properties in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isGraphemeExtend: Bool {
_binaryProperties.contains(.isGraphemeExtend)
}
/// A Boolean value indicating whether the scalar is one that is commonly
/// used for the representation of hexadecimal numbers or a compatibility
/// equivalent.
///
/// This property is `true` for all scalars for which `isASCIIHexDigit` is
/// `true` as well as for their CJK halfwidth and fullwidth variants.
///
/// This property corresponds to the "Hex_Digit" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isHexDigit: Bool {
_binaryProperties.contains(.isHexDigit)
}
/// A Boolean value indicating whether the scalar is one which is
/// recommended to be allowed to appear in a non-starting position in a
/// programming language identifier.
///
/// Applications that store identifiers in NFKC normalized form should instead
/// use `isXIDContinue` to check whether a scalar is a valid identifier
/// character.
///
/// This property corresponds to the "ID_Continue" and the "Other_ID_Continue"
/// properties in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isIDContinue: Bool {
_binaryProperties.contains(.isIDContinue)
}
/// A Boolean value indicating whether the scalar is one which is
/// recommended to be allowed to appear in a starting position in a
/// programming language identifier.
///
/// Applications that store identifiers in NFKC normalized form should instead
/// use `isXIDStart` to check whether a scalar is a valid identifier
/// character.
///
/// This property corresponds to the "ID_Start" and the "Other_ID_Start"
/// properties in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isIDStart: Bool {
_binaryProperties.contains(.isIDStart)
}
/// A Boolean value indicating whether the scalar is considered to be a
/// CJKV (Chinese, Japanese, Korean, and Vietnamese) or other siniform
/// (Chinese writing-related) ideograph.
///
/// This property roughly defines the class of "Chinese characters" and does
/// not include characters of other logographic scripts such as Cuneiform or
/// Egyptian Hieroglyphs.
///
/// This property corresponds to the "Ideographic" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isIdeographic: Bool {
_binaryProperties.contains(.isIdeographic)
}
/// A Boolean value indicating whether the scalar is an ideographic
/// description character that determines how the two ideographic characters
/// or ideographic description sequences that follow it are to be combined to
/// form a single character.
///
/// Ideographic description characters are technically printable characters,
/// but advanced rendering engines may use them to approximate ideographs that
/// are otherwise unrepresentable.
///
/// This property corresponds to the "IDS_Binary_Operator" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isIDSBinaryOperator: Bool {
_binaryProperties.contains(.isIDSBinaryOperator)
}
/// A Boolean value indicating whether the scalar is an ideographic
/// description character that determines how the three ideographic characters
/// or ideographic description sequences that follow it are to be combined to
/// form a single character.
///
/// Ideographic description characters are technically printable characters,
/// but advanced rendering engines may use them to approximate ideographs that
/// are otherwise unrepresentable.
///
/// This property corresponds to the "IDS_Trinary_Operator" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isIDSTrinaryOperator: Bool {
_binaryProperties.contains(.isIDSTrinaryOperator)
}
/// A Boolean value indicating whether the scalar is a format control
/// character that has a specific function in controlling cursive joining and
/// ligation.
///
/// There are two scalars for which this property is `true`:
///
/// * When U+200C ZERO WIDTH NON-JOINER is inserted between two characters, it
/// directs the rendering engine to render them separately/disconnected when
/// it might otherwise render them as a ligature. For example, a rendering
/// engine might display "fl" in English as a connected glyph; inserting the
/// zero width non-joiner would force them to be rendered as disconnected
/// glyphs.
///
/// * When U+200D ZERO WIDTH JOINER is inserted between two characters, it
/// directs the rendering engine to render them as a connected glyph when it
/// would otherwise render them independently. The zero width joiner is also
/// used to construct complex emoji from sequences of base emoji characters.
/// For example, the various "family" emoji are encoded as sequences of man,
/// woman, or child emoji that are interleaved with zero width joiners.
///
/// This property corresponds to the "Join_Control" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isJoinControl: Bool {
_binaryProperties.contains(.isJoinControl)
}
/// A Boolean value indicating whether the scalar requires special handling
/// for operations involving ordering, such as sorting and searching.
///
/// This property applies to a small number of spacing vowel letters occurring
/// in some Southeast Asian scripts like Thai and Lao, which use a visual
/// order display model. Such letters are stored in text ahead of
/// syllable-initial consonants.
///
/// This property corresponds to the "Logical_Order_Exception" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isLogicalOrderException: Bool {
_binaryProperties.contains(.isLogicalOrderException)
}
/// A Boolean value indicating whether the scalar's letterform is
/// considered lowercase.
///
/// This property corresponds to the "Lowercase" and the "Other_Lowercase"
/// properties in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isLowercase: Bool {
_binaryProperties.contains(.isLowercase)
}
/// A Boolean value indicating whether the scalar is one that naturally
/// appears in mathematical contexts.
///
/// The set of scalars for which this property is `true` includes mathematical
/// operators and symbols as well as specific Greek and Hebrew letter
/// variants that are categorized as symbols. Notably, it does _not_ contain
/// the standard digits or Latin/Greek letter blocks; instead, it contains the
/// mathematical Latin, Greek, and Arabic letters and numbers defined in the
/// Supplemental Multilingual Plane.
///
/// This property corresponds to the "Math" and the "Other_Math" properties in
/// the [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isMath: Bool {
_binaryProperties.contains(.isMath)
}
/// A Boolean value indicating whether the scalar is permanently reserved
/// for internal use.
///
/// This property corresponds to the "Noncharacter_Code_Point" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isNoncharacterCodePoint: Bool {
_binaryProperties.contains(.isNoncharacterCodePoint)
}
/// A Boolean value indicating whether the scalar is one that is used in
/// writing to surround quoted text.
///
/// This property corresponds to the "Quotation_Mark" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isQuotationMark: Bool {
_binaryProperties.contains(.isQuotationMark)
}
/// A Boolean value indicating whether the scalar is a radical component of
/// CJK characters, Tangut characters, or Yi syllables.
///
/// These scalars are often the components of ideographic description
/// sequences, as defined by the `isIDSBinaryOperator` and
/// `isIDSTrinaryOperator` properties.
///
/// This property corresponds to the "Radical" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isRadical: Bool {
_binaryProperties.contains(.isRadical)
}
/// A Boolean value indicating whether the scalar has a "soft dot" that
/// disappears when a diacritic is placed over the scalar.
///
/// For example, "i" is soft dotted because the dot disappears when adding an
/// accent mark, as in "í".
///
/// This property corresponds to the "Soft_Dotted" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isSoftDotted: Bool {
_binaryProperties.contains(.isSoftDotted)
}
/// A Boolean value indicating whether the scalar is a punctuation symbol
/// that typically marks the end of a textual unit.
///
/// This property corresponds to the "Terminal_Punctuation" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isTerminalPunctuation: Bool {
_binaryProperties.contains(.isTerminalPunctuation)
}
/// A Boolean value indicating whether the scalar is one of the unified
/// CJK ideographs in the Unicode Standard.
///
/// This property is false for CJK punctuation and symbols, as well as for
/// compatibility ideographs (which canonically decompose to unified
/// ideographs).
///
/// This property corresponds to the "Unified_Ideograph" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isUnifiedIdeograph: Bool {
_binaryProperties.contains(.isUnifiedIdeograph)
}
/// A Boolean value indicating whether the scalar's letterform is
/// considered uppercase.
///
/// This property corresponds to the "Uppercase" and the "Other_Uppercase"
/// properties in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isUppercase: Bool {
_binaryProperties.contains(.isUppercase)
}
/// A Boolean value indicating whether the scalar is a whitespace
/// character.
///
/// This property is `true` for scalars that are spaces, separator characters,
/// and other control characters that should be treated as whitespace for the
/// purposes of parsing text elements.
///
/// This property corresponds to the "White_Space" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isWhitespace: Bool {
_binaryProperties.contains(.isWhitespace)
}
/// A Boolean value indicating whether the scalar is one which is
/// recommended to be allowed to appear in a non-starting position in a
/// programming language identifier, with adjustments made for NFKC normalized
/// form.
///
/// The set of scalars `[:XID_Continue:]` closes the set `[:ID_Continue:]`
/// under NFKC normalization by removing any scalars whose normalized form is
/// not of the form `[:ID_Continue:]*`.
///
/// This property corresponds to the "XID_Continue" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isXIDContinue: Bool {
_binaryProperties.contains(.isXIDContinue)
}
/// A Boolean value indicating whether the scalar is one which is
/// recommended to be allowed to appear in a starting position in a
/// programming language identifier, with adjustments made for NFKC normalized
/// form.
///
/// The set of scalars `[:XID_Start:]` closes the set `[:ID_Start:]` under
/// NFKC normalization by removing any scalars whose normalized form is not of
/// the form `[:ID_Start:] [:ID_Continue:]*`.
///
/// This property corresponds to the "XID_Start" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isXIDStart: Bool {
_binaryProperties.contains(.isXIDStart)
}
/// A Boolean value indicating whether the scalar is a punctuation mark
/// that generally marks the end of a sentence.
///
/// This property corresponds to the "Sentence_Terminal" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isSentenceTerminal: Bool {
_binaryProperties.contains(.isSentenceTerminal)
}
/// A Boolean value indicating whether the scalar is a variation selector.
///
/// Variation selectors allow rendering engines that support them to choose
/// different glyphs to display for a particular code point.
///
/// This property corresponds to the "Variation_Selector" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isVariationSelector: Bool {
_binaryProperties.contains(.isVariationSelector)
}
/// A Boolean value indicating whether the scalar is recommended to have
/// syntactic usage in patterns represented in source code.
///
/// This property corresponds to the "Pattern_Syntax" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isPatternSyntax: Bool {
_binaryProperties.contains(.isPatternSyntax)
}
/// A Boolean value indicating whether the scalar is recommended to be
/// treated as whitespace when parsing patterns represented in source code.
///
/// This property corresponds to the "Pattern_White_Space" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isPatternWhitespace: Bool {
_binaryProperties.contains(.isPatternWhitespace)
}
/// A Boolean value indicating whether the scalar is considered to be
/// either lowercase, uppercase, or titlecase.
///
/// Though similar in name, this property is *not* equivalent to
/// `changesWhenCaseMapped`. The set of scalars for which `isCased` is `true`
/// is a superset of those for which `changesWhenCaseMapped` is `true`. For
/// example, the Latin small capitals that are used by the International
/// Phonetic Alphabet have a case, but do not change when they are mapped to
/// any of the other cases.
///
/// This property corresponds to the "Cased" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isCased: Bool {
_binaryProperties.contains(.isCased)
}
/// A Boolean value indicating whether the scalar is ignored for casing
/// purposes.
///
/// This property corresponds to the "Case_Ignorable" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isCaseIgnorable: Bool {
_binaryProperties.contains(.isCaseIgnorable)
}
/// A Boolean value indicating whether the scalar's normalized form differs
/// from the `lowercaseMapping` of each constituent scalar.
///
/// This property corresponds to the "Changes_When_Lowercased" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var changesWhenLowercased: Bool {
_binaryProperties.contains(.changesWhenLowercased)
}
/// A Boolean value indicating whether the scalar's normalized form differs
/// from the `uppercaseMapping` of each constituent scalar.
///
/// This property corresponds to the "Changes_When_Uppercased" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var changesWhenUppercased: Bool {
_binaryProperties.contains(.changesWhenUppercased)
}
/// A Boolean value indicating whether the scalar's normalized form differs
/// from the `titlecaseMapping` of each constituent scalar.
///
/// This property corresponds to the "Changes_When_Titlecased" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var changesWhenTitlecased: Bool {
_binaryProperties.contains(.changesWhenTitlecased)
}
/// A Boolean value indicating whether the scalar's normalized form differs
/// from the case-fold mapping of each constituent scalar.
///
/// This property corresponds to the "Changes_When_Casefolded" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var changesWhenCaseFolded: Bool {
_binaryProperties.contains(.changesWhenCaseFolded)
}
/// A Boolean value indicating whether the scalar may change when it
/// undergoes case mapping.
///
/// This property is `true` whenever one or more of `changesWhenLowercased`,
/// `changesWhenUppercased`, or `changesWhenTitlecased` are `true`.
///
/// This property corresponds to the "Changes_When_Casemapped" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var changesWhenCaseMapped: Bool {
_binaryProperties.contains(.changesWhenCaseMapped)
}
/// A Boolean value indicating whether the scalar is one that is not
/// identical to its NFKC case-fold mapping.
///
/// This property corresponds to the "Changes_When_NFKC_Casefolded" property
/// in the [Unicode Standard](http://www.unicode.org/versions/latest/).
public var changesWhenNFKCCaseFolded: Bool {
_binaryProperties.contains(.changesWhenNFKCCaseFolded)
}
/// A Boolean value indicating whether the scalar has an emoji
/// presentation, whether or not it is the default.
///
/// This property is true for scalars that are rendered as emoji by default
/// and also for scalars that have a non-default emoji rendering when followed
/// by U+FE0F VARIATION SELECTOR-16. This includes some scalars that are not
/// typically considered to be emoji:
///
/// let scalars: [Unicode.Scalar] = ["😎", "$", "0"]
/// for s in scalars {
/// print(s, "-->", s.properties.isEmoji)
/// }
/// // 😎 --> true
/// // $ --> false
/// // 0 --> true
///
/// The final result is true because the ASCII digits have non-default emoji
/// presentations; some platforms render these with an alternate appearance.
///
/// Because of this behavior, testing `isEmoji` alone on a single scalar is
/// insufficient to determine if a unit of text is rendered as an emoji; a
/// correct test requires inspecting multiple scalars in a `Character`. In
/// addition to checking whether the base scalar has `isEmoji == true`, you
/// must also check its default presentation (see `isEmojiPresentation`) and
/// determine whether it is followed by a variation selector that would modify
/// the presentation.
///
/// This property corresponds to the "Emoji" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
@available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *)
public var isEmoji: Bool {
_binaryProperties.contains(.isEmoji)
}
/// A Boolean value indicating whether the scalar is one that should be
/// rendered with an emoji presentation, rather than a text presentation, by
/// default.
///
/// Scalars that have default to emoji presentation can be followed by
/// U+FE0E VARIATION SELECTOR-15 to request the text presentation of the
/// scalar instead. Likewise, scalars that default to text presentation can
/// be followed by U+FE0F VARIATION SELECTOR-16 to request the emoji
/// presentation.
///
/// This property corresponds to the "Emoji_Presentation" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
@available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *)
public var isEmojiPresentation: Bool {
_binaryProperties.contains(.isEmojiPresentation)
}
/// A Boolean value indicating whether the scalar is one that can modify
/// a base emoji that precedes it.
///
/// The Fitzpatrick skin types are examples of emoji modifiers; they change
/// the appearance of the preceding emoji base (that is, a scalar for which
/// `isEmojiModifierBase` is true) by rendering it with a different skin tone.
///
/// This property corresponds to the "Emoji_Modifier" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
@available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *)
public var isEmojiModifier: Bool {
_binaryProperties.contains(.isEmojiModifier)
}
/// A Boolean value indicating whether the scalar is one whose appearance
/// can be changed by an emoji modifier that follows it.
///
/// This property corresponds to the "Emoji_Modifier_Base" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
@available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *)
public var isEmojiModifierBase: Bool {
_binaryProperties.contains(.isEmojiModifierBase)
}
}
/// Case mapping properties.
extension Unicode.Scalar.Properties {
fileprivate struct _CaseMapping {
let rawValue: UInt8
static let uppercase = _CaseMapping(rawValue: 0)
static let lowercase = _CaseMapping(rawValue: 1)
static let titlecase = _CaseMapping(rawValue: 2)
}
fileprivate func _getMapping(_ mapping: _CaseMapping) -> String {
// First, check if our scalar has a special mapping where it's mapped to
// more than 1 scalar.
var specialMappingLength = 0
let specialMappingPtr = _swift_stdlib_getSpecialMapping(
_scalar.value,
mapping.rawValue,
&specialMappingLength
)
if let specialMapping = specialMappingPtr, specialMappingLength != 0 {
let buffer = UnsafeBufferPointer<UInt8>(
start: specialMapping,
count: specialMappingLength
)
return String._uncheckedFromUTF8(buffer, isASCII: false)
}
// If we did not have a special mapping, check if we have a direct scalar
// to scalar mapping.
let mappingDistance = _swift_stdlib_getMapping(
_scalar.value,
mapping.rawValue
)
if mappingDistance != 0 {
let scalar = Unicode.Scalar(
_unchecked: UInt32(Int(_scalar.value) &+ Int(mappingDistance))
)
return String(scalar)
}
// We did not have any mapping. Return the scalar as is.
return String(_scalar)
}
/// The lowercase mapping of the scalar.
///
/// This property is a `String`, not a `Unicode.Scalar` or `Character`,
/// because some mappings may transform a scalar into multiple scalars or
/// graphemes. For example, the character "İ" (U+0130 LATIN CAPITAL LETTER I
/// WITH DOT ABOVE) becomes two scalars (U+0069 LATIN SMALL LETTER I, U+0307
/// COMBINING DOT ABOVE) when converted to lowercase.
///
/// This property corresponds to the "Lowercase_Mapping" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var lowercaseMapping: String {
_getMapping(.lowercase)
}
/// The titlecase mapping of the scalar.
///
/// This property is a `String`, not a `Unicode.Scalar` or `Character`,
/// because some mappings may transform a scalar into multiple scalars or
/// graphemes. For example, the ligature "fi" (U+FB01 LATIN SMALL LIGATURE FI)
/// becomes "Fi" (U+0046 LATIN CAPITAL LETTER F, U+0069 LATIN SMALL LETTER I)
/// when converted to titlecase.
///
/// This property corresponds to the "Titlecase_Mapping" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var titlecaseMapping: String {
_getMapping(.titlecase)
}
/// The uppercase mapping of the scalar.
///
/// This property is a `String`, not a `Unicode.Scalar` or `Character`,
/// because some mappings may transform a scalar into multiple scalars or
/// graphemes. For example, the German letter "ß" (U+00DF LATIN SMALL LETTER
/// SHARP S) becomes "SS" (U+0053 LATIN CAPITAL LETTER S, U+0053 LATIN CAPITAL
/// LETTER S) when converted to uppercase.
///
/// This property corresponds to the "Uppercase_Mapping" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var uppercaseMapping: String {
_getMapping(.uppercase)
}
}
extension Unicode {
/// A version of the Unicode Standard represented by its major and minor
/// components.
public typealias Version = (major: Int, minor: Int)
}
extension Unicode.Scalar.Properties {
/// The earliest version of the Unicode Standard in which the scalar was
/// assigned.
///
/// This value is `nil` for code points that have not yet been assigned.
///
/// This property corresponds to the "Age" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var age: Unicode.Version? {
let age: UInt16 = _swift_stdlib_getAge(_scalar.value)
if age == .max {
return nil
}
let major = age & 0xFF
let minor = (age & 0xFF00) >> 8
return (major: Int(major), minor: Int(minor))
}
}
extension Unicode {
/// The most general classification of a Unicode scalar.
///
/// The general category of a scalar is its "first-order, most usual
/// categorization". It does not attempt to cover multiple uses of some
/// scalars, such as the use of letters to represent Roman numerals.
public enum GeneralCategory: Sendable {
/// An uppercase letter.
///
/// This value corresponds to the category `Uppercase_Letter` (abbreviated
/// `Lu`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case uppercaseLetter
/// A lowercase letter.
///
/// This value corresponds to the category `Lowercase_Letter` (abbreviated
/// `Ll`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case lowercaseLetter
/// A digraph character whose first part is uppercase.
///
/// This value corresponds to the category `Titlecase_Letter` (abbreviated
/// `Lt`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case titlecaseLetter
/// A modifier letter.
///
/// This value corresponds to the category `Modifier_Letter` (abbreviated
/// `Lm`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case modifierLetter
/// Other letters, including syllables and ideographs.
///
/// This value corresponds to the category `Other_Letter` (abbreviated
/// `Lo`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case otherLetter
/// A non-spacing combining mark with zero advance width (abbreviated Mn).
///
/// This value corresponds to the category `Nonspacing_Mark` (abbreviated
/// `Mn`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case nonspacingMark
/// A spacing combining mark with positive advance width.
///
/// This value corresponds to the category `Spacing_Mark` (abbreviated `Mc`)
/// in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case spacingMark
/// An enclosing combining mark.
///
/// This value corresponds to the category `Enclosing_Mark` (abbreviated
/// `Me`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case enclosingMark
/// A decimal digit.
///
/// This value corresponds to the category `Decimal_Number` (abbreviated
/// `Nd`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case decimalNumber
/// A letter-like numeric character.
///
/// This value corresponds to the category `Letter_Number` (abbreviated
/// `Nl`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case letterNumber
/// A numeric character of another type.
///
/// This value corresponds to the category `Other_Number` (abbreviated `No`)
/// in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case otherNumber
/// A connecting punctuation mark, like a tie.
///
/// This value corresponds to the category `Connector_Punctuation`
/// (abbreviated `Pc`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case connectorPunctuation
/// A dash or hyphen punctuation mark.
///
/// This value corresponds to the category `Dash_Punctuation` (abbreviated
/// `Pd`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case dashPunctuation
/// An opening punctuation mark of a pair.
///
/// This value corresponds to the category `Open_Punctuation` (abbreviated
/// `Ps`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case openPunctuation
/// A closing punctuation mark of a pair.
///
/// This value corresponds to the category `Close_Punctuation` (abbreviated
/// `Pe`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case closePunctuation
/// An initial quotation mark.
///
/// This value corresponds to the category `Initial_Punctuation`
/// (abbreviated `Pi`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case initialPunctuation
/// A final quotation mark.
///
/// This value corresponds to the category `Final_Punctuation` (abbreviated
/// `Pf`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case finalPunctuation
/// A punctuation mark of another type.
///
/// This value corresponds to the category `Other_Punctuation` (abbreviated
/// `Po`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case otherPunctuation
/// A symbol of mathematical use.
///
/// This value corresponds to the category `Math_Symbol` (abbreviated `Sm`)
/// in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case mathSymbol
/// A currency sign.
///
/// This value corresponds to the category `Currency_Symbol` (abbreviated
/// `Sc`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case currencySymbol
/// A non-letterlike modifier symbol.
///
/// This value corresponds to the category `Modifier_Symbol` (abbreviated
/// `Sk`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case modifierSymbol
/// A symbol of another type.
///
/// This value corresponds to the category `Other_Symbol` (abbreviated
/// `So`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case otherSymbol
/// A space character of non-zero width.
///
/// This value corresponds to the category `Space_Separator` (abbreviated
/// `Zs`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case spaceSeparator
/// A line separator, which is specifically (and only) U+2028 LINE
/// SEPARATOR.
///
/// This value corresponds to the category `Line_Separator` (abbreviated
/// `Zl`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case lineSeparator
/// A paragraph separator, which is specifically (and only) U+2029 PARAGRAPH
/// SEPARATOR.
///
/// This value corresponds to the category `Paragraph_Separator`
/// (abbreviated `Zp`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case paragraphSeparator
/// A C0 or C1 control code.
///
/// This value corresponds to the category `Control` (abbreviated `Cc`) in
/// the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case control
/// A format control character.
///
/// This value corresponds to the category `Format` (abbreviated `Cf`) in
/// the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case format
/// A surrogate code point.
///
/// This value corresponds to the category `Surrogate` (abbreviated `Cs`) in
/// the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case surrogate
/// A private-use character.
///
/// This value corresponds to the category `Private_Use` (abbreviated `Co`)
/// in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case privateUse
/// A reserved unassigned code point or a non-character.
///
/// This value corresponds to the category `Unassigned` (abbreviated `Cn`)
/// in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case unassigned
internal init(rawValue: UInt8) {
switch rawValue {
case 0: self = .uppercaseLetter
case 1: self = .lowercaseLetter
case 2: self = .titlecaseLetter
case 3: self = .modifierLetter
case 4: self = .otherLetter
case 5: self = .nonspacingMark
case 6: self = .spacingMark
case 7: self = .enclosingMark
case 8: self = .decimalNumber
case 9: self = .letterNumber
case 10: self = .otherNumber
case 11: self = .connectorPunctuation
case 12: self = .dashPunctuation
case 13: self = .openPunctuation
case 14: self = .closePunctuation
case 15: self = .initialPunctuation
case 16: self = .finalPunctuation
case 17: self = .otherPunctuation
case 18: self = .mathSymbol
case 19: self = .currencySymbol
case 20: self = .modifierSymbol
case 21: self = .otherSymbol
case 22: self = .spaceSeparator
case 23: self = .lineSeparator
case 24: self = .paragraphSeparator
case 25: self = .control
case 26: self = .format
case 27: self = .surrogate
case 28: self = .privateUse
case 29: self = .unassigned
default: fatalError("Unknown general category \(rawValue)")
}
}
}
}
// Internal helpers
extension Unicode.GeneralCategory {
internal var _isSymbol: Bool {
switch self {
case .mathSymbol, .currencySymbol, .modifierSymbol, .otherSymbol:
return true
default: return false
}
}
internal var _isPunctuation: Bool {
switch self {
case .connectorPunctuation, .dashPunctuation, .openPunctuation,
.closePunctuation, .initialPunctuation, .finalPunctuation,
.otherPunctuation:
return true
default: return false
}
}
}
extension Unicode.Scalar.Properties {
/// The general category (most usual classification) of the scalar.
///
/// This property corresponds to the "General_Category" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var generalCategory: Unicode.GeneralCategory {
let rawValue = _swift_stdlib_getGeneralCategory(_scalar.value)
return Unicode.GeneralCategory(rawValue: rawValue)
}
}
extension Unicode.Scalar.Properties {
internal func _hangulName() -> String {
// T = Hangul tail consonants
let T: (base: UInt32, count: UInt32) = (base: 0x11A7, count: 28)
// N = Number of precomposed Hangul syllables that start with the same
// leading consonant. (There is no base for N).
let N: (base: UInt32, count: UInt32) = (base: 0x0, count: 588)
// S = Hangul precomposed syllables
let S: (base: UInt32, count: UInt32) = (base: 0xAC00, count: 11172)
let hangulLTable = ["G", "GG", "N", "D", "DD", "R", "M", "B", "BB", "S",
"SS", "", "J", "JJ", "C", "K", "T", "P", "H"]
let hangulVTable = ["A", "AE", "YA", "YAE", "EO", "E", "YEO", "YE", "O",
"WA", "WAE", "OE", "YO", "U", "WEO", "WE", "WI", "YU",
"EU", "YI", "I"]
let hangulTTable = ["", "G", "GG", "GS", "N", "NJ", "NH", "D", "L", "LG",
"LM", "LB", "LS", "LT", "LP", "LH", "M", "B", "BS", "S",
"SS", "NG", "J", "C", "K", "T", "P", "H"]
let sIdx = _scalar.value &- S.base
let lIdx = Int(sIdx / N.count)
let vIdx = Int((sIdx % N.count) / T.count)
let tIdx = Int(sIdx % T.count)
let scalarName = hangulLTable[lIdx] + hangulVTable[vIdx] + hangulTTable[tIdx]
return "HANGUL SYLLABLE \(scalarName)"
}
// Used to potentially return a name who can either be represented in a large
// range or algorithmically. A good example are the Hangul names. Instead of
// storing those names, we can define an algorithm to generate the name.
internal func _fastScalarName() -> String? {
// Define a couple algorithmic names below.
let scalarName = String(_scalar.value, radix: 16, uppercase: true)
switch _scalar.value {
// Hangul Syllable *
case (0xAC00 ... 0xD7A3):
return _hangulName()
// Variation Selector-17 through Variation Selector-256
case (0xE0100 ... 0xE01EF):
return "VARIATION SELECTOR-\(_scalar.value - 0xE0100 + 17)"
case (0x3400 ... 0x4DBF),
(0x4E00 ... 0x9FFF),
(0x20000 ... 0x2A6DF),
(0x2A700 ... 0x2B738),
(0x2B740 ... 0x2B81D),
(0x2B820 ... 0x2CEA1),
(0x2CEB0 ... 0x2EBE0),
(0x30000 ... 0x3134A):
return "CJK UNIFIED IDEOGRAPH-\(scalarName)"
case (0xF900 ... 0xFA6D),
(0xFA70 ... 0xFAD9),
(0x2F800 ... 0x2FA1D):
return "CJK COMPATIBILITY IDEOGRAPH-\(scalarName)"
case (0x17000 ... 0x187F7),
(0x18D00 ... 0x18D08):
return "TANGUT IDEOGRAPH-\(scalarName)"
case (0x18B00 ... 0x18CD5):
return "KHITAN SMALL SCRIPT CHARACTER-\(scalarName)"
case (0x1B170 ... 0x1B2FB):
return "NUSHU CHARACTER-\(scalarName)"
// Otherwise, go look it up.
default:
return nil
}
}
/// The published name of the scalar.
///
/// Some scalars, such as control characters, do not have a value for this
/// property in the Unicode Character Database. For such scalars, this
/// property is `nil`.
///
/// This property corresponds to the "Name" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var name: String? {
if let fastName = _fastScalarName() {
return fastName
}
// The longest name that Unicode defines is 88 characters long.
let largestCount = Int(SWIFT_STDLIB_LARGEST_NAME_COUNT)
let name = String(_uninitializedCapacity: largestCount) { buffer in
_swift_stdlib_getScalarName(
_scalar.value,
buffer.baseAddress,
buffer.count
)
}
return name.isEmpty ? nil : name
}
/// The normative formal alias of the scalar.
///
/// The name of a scalar is immutable and never changed in future versions of
/// the Unicode Standard. The `nameAlias` property is provided to issue
/// corrections if a name was issued erroneously. For example, the `name` of
/// U+FE18 is "PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRACKET"
/// (note that "BRACKET" is misspelled). The `nameAlias` property then
/// contains the corrected name.
///
/// If a scalar has no alias, this property is `nil`.
///
/// This property corresponds to the "Name_Alias" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var nameAlias: String? {
guard let nameAliasPtr = _swift_stdlib_getNameAlias(_scalar.value) else {
return nil
}
return String(cString: nameAliasPtr)
}
}
extension Unicode {
/// The classification of a scalar used in the Canonical Ordering Algorithm
/// defined by the Unicode Standard.
///
/// Canonical combining classes are used by the ordering algorithm to
/// determine if two sequences of combining marks should be considered
/// canonically equivalent (that is, identical in interpretation). Two
/// sequences are canonically equivalent if they are equal when sorting the
/// scalars in ascending order by their combining class.
///
/// For example, consider the sequence `"\u{0041}\u{0301}\u{0316}"` (LATIN
/// CAPITAL LETTER A, COMBINING ACUTE ACCENT, COMBINING GRAVE ACCENT BELOW).
/// The combining classes of these scalars have the numeric values 0, 230, and
/// 220, respectively. Sorting these scalars by their combining classes yields
/// `"\u{0041}\u{0316}\u{0301}"`, so two strings that differ only by the
/// ordering of those scalars would compare as equal:
///
/// let aboveBeforeBelow = "\u{0041}\u{0301}\u{0316}"
/// let belowBeforeAbove = "\u{0041}\u{0316}\u{0301}"
/// print(aboveBeforeBelow == belowBeforeAbove)
/// // Prints "true"
///
/// Named and Unnamed Combining Classes
/// ===================================
///
/// Canonical combining classes are defined in the Unicode Standard as
/// integers in the range `0...254`. For convenience, the standard assigns
/// symbolic names to a subset of these combining classes.
///
/// The `CanonicalCombiningClass` type conforms to `RawRepresentable` with a
/// raw value of type `UInt8`. You can create instances of the type by using
/// the static members named after the symbolic names, or by using the
/// `init(rawValue:)` initializer.
///
/// let overlayClass = Unicode.CanonicalCombiningClass(rawValue: 1)
/// let overlayClassIsOverlay = overlayClass == .overlay
/// // overlayClassIsOverlay == true
public struct CanonicalCombiningClass:
Comparable, Hashable, RawRepresentable, Sendable
{
/// Base glyphs that occupy their own space and do not combine with others.
public static let notReordered = CanonicalCombiningClass(rawValue: 0)
/// Marks that overlay a base letter or symbol.
public static let overlay = CanonicalCombiningClass(rawValue: 1)
/// Diacritic nukta marks in Brahmi-derived scripts.
public static let nukta = CanonicalCombiningClass(rawValue: 7)
/// Combining marks that are attached to hiragana and katakana to indicate
/// voicing changes.
public static let kanaVoicing = CanonicalCombiningClass(rawValue: 8)
/// Diacritic virama marks in Brahmi-derived scripts.
public static let virama = CanonicalCombiningClass(rawValue: 9)
/// Marks attached at the bottom left.
public static let attachedBelowLeft = CanonicalCombiningClass(rawValue: 200)
/// Marks attached directly below.
public static let attachedBelow = CanonicalCombiningClass(rawValue: 202)
/// Marks attached directly above.
public static let attachedAbove = CanonicalCombiningClass(rawValue: 214)
/// Marks attached at the top right.
public static let attachedAboveRight =
CanonicalCombiningClass(rawValue: 216)
/// Distinct marks at the bottom left.
public static let belowLeft = CanonicalCombiningClass(rawValue: 218)
/// Distinct marks directly below.
public static let below = CanonicalCombiningClass(rawValue: 220)
/// Distinct marks at the bottom right.
public static let belowRight = CanonicalCombiningClass(rawValue: 222)
/// Distinct marks to the left.
public static let left = CanonicalCombiningClass(rawValue: 224)
/// Distinct marks to the right.
public static let right = CanonicalCombiningClass(rawValue: 226)
/// Distinct marks at the top left.
public static let aboveLeft = CanonicalCombiningClass(rawValue: 228)
/// Distinct marks directly above.
public static let above = CanonicalCombiningClass(rawValue: 230)
/// Distinct marks at the top right.
public static let aboveRight = CanonicalCombiningClass(rawValue: 232)
/// Distinct marks subtending two bases.
public static let doubleBelow = CanonicalCombiningClass(rawValue: 233)
/// Distinct marks extending above two bases.
public static let doubleAbove = CanonicalCombiningClass(rawValue: 234)
/// Greek iota subscript only (U+0345 COMBINING GREEK YPOGEGRAMMENI).
public static let iotaSubscript = CanonicalCombiningClass(rawValue: 240)
/// The raw integer value of the canonical combining class.
public let rawValue: UInt8
/// Creates a new canonical combining class with the given raw integer
/// value.
///
/// - Parameter rawValue: The raw integer value of the canonical combining
/// class.
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
public static func == (
lhs: CanonicalCombiningClass,
rhs: CanonicalCombiningClass
) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func < (
lhs: CanonicalCombiningClass,
rhs: CanonicalCombiningClass
) -> Bool {
return lhs.rawValue < rhs.rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
}
}
extension Unicode.Scalar.Properties {
/// The canonical combining class of the scalar.
///
/// This property corresponds to the "Canonical_Combining_Class" property in
/// the [Unicode Standard](http://www.unicode.org/versions/latest/).
public var canonicalCombiningClass: Unicode.CanonicalCombiningClass {
let normData = Unicode._NormData(_scalar)
return Unicode.CanonicalCombiningClass(rawValue: normData.ccc)
}
}
extension Unicode {
/// The numeric type of a scalar.
///
/// Scalars with a non-nil numeric type include numbers, fractions, numeric
/// superscripts and subscripts, and circled or otherwise decorated number
/// glyphs.
///
/// Some letterlike scalars used in numeric systems, such as Greek or Latin
/// letters, do not have a non-nil numeric type, in order to prevent programs
/// from incorrectly interpreting them as numbers in non-numeric contexts.
public enum NumericType: Sendable {
/// A digit that is commonly understood to form base-10 numbers.
///
/// Specifically, scalars have this numeric type if they occupy a contiguous
/// range of code points representing numeric values `0...9`.
case decimal
/// A digit that does not meet the requirements of the `decimal` numeric
/// type.
///
/// Scalars with this numeric type are often those that represent a decimal
/// digit but would not typically be used to write a base-10 number, such
/// as "④" (U+2463 CIRCLED DIGIT FOUR).
///
/// As of Unicode 6.3, any new scalars that represent numbers but do not
/// meet the requirements of `decimal` will have numeric type `numeric`,
/// and programs can treat `digit` and `numeric` equivalently.
case digit
/// A digit that does not meet the requirements of the `decimal` numeric
/// type or a non-digit numeric value.
///
/// This numeric type includes fractions such as "⅕" (U+2155 VULGAR
/// FRACTION ONE FIFTH), numerical CJK ideographs like "兆" (U+5146 CJK
/// UNIFIED IDEOGRAPH-5146), and other scalars that are not decimal digits
/// used positionally in the writing of base-10 numbers.
///
/// As of Unicode 6.3, any new scalars that represent numbers but do not
/// meet the requirements of `decimal` will have numeric type `numeric`,
/// and programs can treat `digit` and `numeric` equivalently.
case numeric
internal init(rawValue: UInt8) {
switch rawValue {
case 0:
self = .numeric
case 1:
self = .digit
case 2:
self = .decimal
default:
fatalError("Unknown numeric type \(rawValue)")
}
}
}
}
/// Numeric properties of scalars.
extension Unicode.Scalar.Properties {
/// The numeric type of the scalar.
///
/// For scalars that represent a number, `numericType` is the numeric type
/// of the scalar. For all other scalars, this property is `nil`.
///
/// let scalars: [Unicode.Scalar] = ["4", "④", "⅕", "X"]
/// for scalar in scalars {
/// print(scalar, "-->", scalar.properties.numericType)
/// }
/// // 4 --> Optional(Swift.Unicode.NumericType.decimal)
/// // ④ --> Optional(Swift.Unicode.NumericType.digit)
/// // ⅕ --> Optional(Swift.Unicode.NumericType.numeric)
/// // X --> nil
///
/// This property corresponds to the "Numeric_Type" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var numericType: Unicode.NumericType? {
let rawValue = _swift_stdlib_getNumericType(_scalar.value)
guard rawValue != .max else {
return nil
}
return Unicode.NumericType(rawValue: rawValue)
}
/// The numeric value of the scalar.
///
/// For scalars that represent a numeric value, `numericValue` is the whole
/// or fractional value. For all other scalars, this property is `nil`.
///
/// let scalars: [Unicode.Scalar] = ["4", "④", "⅕", "X"]
/// for scalar in scalars {
/// print(scalar, "-->", scalar.properties.numericValue)
/// }
/// // 4 --> Optional(4.0)
/// // ④ --> Optional(4.0)
/// // ⅕ --> Optional(0.2)
/// // X --> nil
///
/// This property corresponds to the "Numeric_Value" property in the [Unicode
/// Standard](http://www.unicode.org/versions/latest/).
public var numericValue: Double? {
guard numericType != nil else {
return nil
}
return _swift_stdlib_getNumericValue(_scalar.value)
}
}
| apache-2.0 |
bay2/LetToDo | LetToDo/Home/Controller/HomeGroupViewController.swift | 1 | 3465 | //
// HomeGroupViewController.swift
// LetToDo
//
// Created by xuemincai on 2016/10/7.
// Copyright © 2016年 xuemincai. All rights reserved.
//
import UIKit
import EZSwiftExtensions
import IBAnimatable
import RxSwift
import SnapKit
import RxDataSources
fileprivate let reuseIdentifier = "HomeGroupCollectionViewCell"
fileprivate let reusableViewIdentifier = "HomeGroupCollectionReusableView"
class HomeGroupViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
private lazy var dataSources = RxCollectionViewSectionedAnimatedDataSource<GroupSectionViewModel>()
private var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
registerCell()
configNavigationBar()
dataSources.configureCell = {(data, collectionView, indexPath, item) in
let cell: HomeGroupCollectionViewCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
cell.groupTitle.text = item.groupTitle
cell.groupTitle.textColor = item.TitleColor
cell.itemLab.text = "Item \(item.taskNum)"
cell.groupID = item.groupID
return cell
}
dataSources.supplementaryViewFactory = { (data, collectionView, kind, indexPath) in
return collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: reusableViewIdentifier, for: indexPath)
}
Observable.from(realm.objects(GroupModel.self))
.map { (results) -> [GroupViewModel] in
results.flatMap { model -> GroupViewModel in
GroupViewModel(model: model)
}
}
.map { (items) -> [GroupSectionViewModel] in
[GroupSectionViewModel(sectionID: "", groups: items)]
}
.bindTo(collectionView.rx.items(dataSource: dataSources))
.addDisposableTo(disposeBag)
collectionView
.rx
.setDelegate(self)
.addDisposableTo(disposeBag)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// register Cell
func registerCell() {
self.collectionView.register(UINib(nibName: reuseIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView.register(UINib(nibName: reusableViewIdentifier, bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: reusableViewIdentifier)
}
}
// MARK: UICollectionViewDelegateFlowLayout
extension HomeGroupViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: ez.screenWidth * 0.5, height: ez.screenWidth * 0.5 * 0.88)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: ez.screenWidth, height: 104)
}
}
| mit |
austinzheng/swift | validation-test/compiler_crashers_fixed/01349-swift-typebase-operator.swift | 65 | 558 | // 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
<T, let a {
class A.c) -> : a {
}
protocol a {
func b, U) -> String {
func b: String {
}
}
case C) + seq: T>) {
}
typealias b in return { }
func c<A> : b : NSO
| apache-2.0 |
netguru/inbbbox-ios | Unit Tests/ShotCollectionViewCellSpec.swift | 1 | 27321 | //
// Copyright (c) 2015 Netguru Sp. z o.o. All rights reserved.
//
import Quick
import Nimble
import Dobby
@testable import Inbbbox
class ShotCollectionViewCellSpec: QuickSpec {
override func spec() {
var sut: ShotCollectionViewCell!
beforeEach {
sut = ShotCollectionViewCell(frame: CGRect.zero)
}
afterEach {
sut = nil
}
describe("shot container view") {
var shotContainer: UIView!
beforeEach {
shotContainer = sut.shotContainer
}
it("should not translate autoresizing mask into constraints") {
expect(shotContainer.translatesAutoresizingMaskIntoConstraints).to(beFalsy())
}
it("should be added to cell content view subviews") {
expect(sut.contentView.subviews).to(contain(shotContainer))
}
}
describe("like image view") {
var likeImageView: DoubleImageView!
beforeEach {
likeImageView = sut.likeImageView
}
it("should not translate autoresizing mask into constraints") {
expect(likeImageView.translatesAutoresizingMaskIntoConstraints).to(beFalsy())
}
it("should be added to cell content view subviews") {
expect(sut.shotContainer.subviews).to(contain(likeImageView))
}
it("should have proper first image") {
expect(UIImagePNGRepresentation(likeImageView.firstImageView.image!)).to(equal(UIImagePNGRepresentation(UIImage(named: "ic-like-swipe")!)))
}
it("should have proper second image") {
expect(UIImagePNGRepresentation(likeImageView.secondImageView.image!)).to(equal(UIImagePNGRepresentation(UIImage(named: "ic-like-swipe-filled")!)))
}
}
describe("bucket image view") {
var bucketImageView: DoubleImageView!
beforeEach {
bucketImageView = sut.bucketImageView
}
it("should not translate autoresizing mask into constraints") {
expect(bucketImageView.translatesAutoresizingMaskIntoConstraints).to(beFalsy())
}
it("should be added to cell content view subviews") {
expect(sut.shotContainer.subviews).to(contain(bucketImageView))
}
it("should have proper first image") {
expect(UIImagePNGRepresentation(bucketImageView.firstImageView.image!)).to(equal(UIImagePNGRepresentation(UIImage(named: "ic-bucket-swipe")!)))
}
it("should have proper second image") {
expect(UIImagePNGRepresentation(bucketImageView.secondImageView.image!)).to(equal(UIImagePNGRepresentation(UIImage(named: "ic-bucket-swipe-filled")!)))
}
}
describe("comment image view") {
var commentImageView: DoubleImageView!
beforeEach {
commentImageView = sut.commentImageView
}
it("should not translate autoresizing mask into constraints") {
expect(commentImageView.translatesAutoresizingMaskIntoConstraints).to(beFalsy())
}
it("should be added to cell content view subviews") {
expect(sut.shotContainer.subviews).to(contain(commentImageView))
}
it("should have proper first image") {
expect(UIImagePNGRepresentation(commentImageView.firstImageView.image!)).to(equal(UIImagePNGRepresentation(UIImage(named: "ic-comment")!)))
}
it("should have proper second image") {
expect(UIImagePNGRepresentation(commentImageView.secondImageView.image!)).to(equal(UIImagePNGRepresentation(UIImage(named: "ic-comment-filled")!)))
}
}
describe("shot image view") {
var shotImageView: UIImageView!
beforeEach {
shotImageView = sut.shotImageView
}
it("should not translate autoresizing mask into constraints") {
expect(shotImageView.translatesAutoresizingMaskIntoConstraints).to(beFalsy())
}
it("should be added to cell content view subviews") {
expect(sut.shotContainer.subviews).to(contain(shotImageView))
}
}
describe("requires constraint based layout") {
var requiresConstraintBasedLayout: Bool!
beforeEach {
requiresConstraintBasedLayout = ShotCollectionViewCell.requiresConstraintBasedLayout
}
it("should require constraint based layout") {
expect(requiresConstraintBasedLayout).to(beTruthy())
}
}
pending("randomly crashes bitrise, works locally; check with Xcode 8 and Swift 3 after conversion") {
describe("swiping cell") {
var panGestureRecognizer: UIPanGestureRecognizer!
beforeEach {
panGestureRecognizer = sut.contentView.gestureRecognizers!.filter{ $0 is UIPanGestureRecognizer }.first as! UIPanGestureRecognizer!
}
context("when swipe began") {
var delegateMock: ShotCollectionViewCellDelegateMock!
var didInformDelegateCellDidStartSwiping: Bool!
beforeEach {
delegateMock = ShotCollectionViewCellDelegateMock()
didInformDelegateCellDidStartSwiping = false
delegateMock.shotCollectionViewCellDidStartSwipingStub.on(any()) { _ in
didInformDelegateCellDidStartSwiping = true
}
sut.delegate = delegateMock
let panGestureRecognizerMock = PanGestureRecognizerMock()
panGestureRecognizerMock.stateStub.on(any()) {
return .began
}
panGestureRecognizer!.specRecognize(with: panGestureRecognizerMock)
}
it("should inform delegate that cell did start swiping") {
expect(didInformDelegateCellDidStartSwiping).to(beTruthy())
}
}
context("when swipe ended") {
var panGestureRecognizerMock: PanGestureRecognizerMock!
var viewClassMock: ViewMock.Type!
var capturedRestoreInitialStateDuration: TimeInterval!
var capturedRestoreInitialStateDelay: TimeInterval!
var capturedRestoreInitialStateDamping: CGFloat!
var capturedRestoreInitialStateVelocity: CGFloat!
var capturedRestoreInitialStateOptions: UIViewAnimationOptions!
var capturedRestoreInitialStateAnimations: (() -> Void)!
var capturedRestoreInitialStateCompletion: ((Bool) -> Void)!
beforeEach {
viewClassMock = ViewMock.self
viewClassMock.springAnimationStub.on(any()) { duration, delay, damping, velocity, options, animations, completion in
capturedRestoreInitialStateDuration = duration
capturedRestoreInitialStateDelay = delay
capturedRestoreInitialStateDamping = damping
capturedRestoreInitialStateVelocity = velocity
capturedRestoreInitialStateOptions = options
capturedRestoreInitialStateAnimations = animations
capturedRestoreInitialStateCompletion = completion
}
sut.viewClass = viewClassMock
panGestureRecognizerMock = PanGestureRecognizerMock()
panGestureRecognizerMock.stateStub.on(any()) {
return .ended
}
}
sharedExamples("returning to initial cell state animation") { (sharedExampleContext: @escaping SharedExampleContext) in
it("should animate returning to initial cell state with duration 0.3") {
expect(capturedRestoreInitialStateDuration).to(equal(0.3))
}
it("should animate returning to initial cell state without delay") {
expect(capturedRestoreInitialStateDelay).to(equal(sharedExampleContext()["expectedDelay"] as? TimeInterval))
}
it("should animate returning to initial cell state with damping 0.6") {
expect(capturedRestoreInitialStateDamping).to(equal(0.6))
}
it("should animate returning to initial cell state with velocity 0.9") {
expect(capturedRestoreInitialStateVelocity).to(equal(0.9))
}
it("should animate returning to initial cell state with ease in out option") {
expect(capturedRestoreInitialStateOptions == UIViewAnimationOptions.curveEaseInOut).to(beTruthy())
}
describe("restore initial state animations block") {
beforeEach {
sut.shotImageView.transform = CGAffineTransform.identity.translatedBy(x: 100, y: 0)
capturedRestoreInitialStateAnimations()
}
it("should restore shot image view identity tranform") {
expect(sut.shotImageView.transform).to(equal(CGAffineTransform.identity))
}
}
describe("restore initial state completion block") {
var delegateMock: ShotCollectionViewCellDelegateMock!
var didInformDelegateCellDidEndSwiping: Bool!
var capturedAction: ShotCollectionViewCell.Action!
beforeEach {
sut.swipeCompletion = { action in
capturedAction = action
}
delegateMock = ShotCollectionViewCellDelegateMock()
didInformDelegateCellDidEndSwiping = false
delegateMock.shotCollectionViewCellDidEndSwipingStub.on(any()) { _ in
didInformDelegateCellDidEndSwiping = true
}
sut.delegate = delegateMock
sut.bucketImageView.isHidden = true
sut.commentImageView.isHidden = true
sut.likeImageView.firstImageView.alpha = 0
sut.likeImageView.secondImageView.alpha = 1
capturedRestoreInitialStateCompletion(true)
}
it("should invoke swipe completion with Comment action") {
let actionWrapper = sharedExampleContext()["expectedAction"] as! ShotCollectionViewCellActionWrapper
expect(capturedAction).to(equal(actionWrapper.action))
}
it("should inform delegate that cell did end swiping") {
expect(didInformDelegateCellDidEndSwiping).to(beTruthy())
}
it("show bucket image view") {
expect(sut.bucketImageView.isHidden).to(beFalsy())
}
it("show comment image view") {
expect(sut.commentImageView.isHidden).to(beFalsy())
}
describe("like image view") {
var likeImageView: DoubleImageView!
beforeEach {
likeImageView = sut.likeImageView
}
it("should display first image view") {
expect(likeImageView.firstImageView.alpha).to(equal(0))
}
it("should hide second image view") {
expect(likeImageView.secondImageView.alpha).to(equal(1))
}
}
}
}
context("when user swiped") {
var capturedActionDuration: TimeInterval!
var capturedActionDelay: TimeInterval!
var capturedActionOptions: UIViewAnimationOptions!
var capturedActionAnimations: (() -> Void)!
var capturedActionCompletion: ((Bool) -> Void)!
beforeEach {
viewClassMock.animationStub.on(any()) { duration, delay, options, animations, completion in
capturedActionDuration = duration
capturedActionDelay = delay
capturedActionOptions = options
capturedActionAnimations = animations
capturedActionCompletion = completion
}
}
context("slightly right") {
beforeEach {
panGestureRecognizerMock.translationInViewStub.on(any()) { _ in
return CGPoint(x: 50, y:0)
}
panGestureRecognizer!.specRecognize(with: panGestureRecognizerMock)
}
it("should animate like action with duration 0.3") {
expect(capturedActionDuration).to(equal(0.3))
}
it("should animate like action without delay") {
expect(capturedActionDelay).to(equal(0))
}
it("should animate like action without options") {
expect(capturedActionOptions).to(equal([]))
}
describe("like action animations block") {
beforeEach {
sut.contentView.bounds = CGRect(x: 0, y: 0, width: 100, height: 0)
sut.likeImageView.alpha = 0
capturedActionAnimations()
}
it("should set shot image view tranform") {
expect(sut.shotImageView.transform).to(equal(CGAffineTransform.identity.translatedBy(x: 100, y: 0)))
}
describe("like image view") {
var likeImageView: DoubleImageView!
beforeEach {
likeImageView = sut.likeImageView
}
it("should have alpha 1") {
expect(likeImageView.alpha).to(equal(1.0))
}
it("should display second image view") {
expect(likeImageView.secondImageView.alpha).to(equal(1))
}
it("should hide first image view") {
expect(likeImageView.firstImageView.alpha).to(equal(0))
}
}
}
describe("like action completion block") {
beforeEach {
capturedActionCompletion(true)
}
itBehavesLike("returning to initial cell state animation") {
["expectedDelay": 0.2,
"expectedAction": ShotCollectionViewCellActionWrapper(action: ShotCollectionViewCell.Action.like)]
}
}
}
context("considerably right") {
beforeEach {
panGestureRecognizerMock.translationInViewStub.on(any()) { _ in
return CGPoint(x: 150, y:0)
}
panGestureRecognizer!.specRecognize(with: panGestureRecognizerMock)
}
it("should animate bucket action with duration 0.3") {
expect(capturedActionDuration).to(equal(0.3))
}
it("should animate bucket action without delay") {
expect(capturedActionDelay).to(equal(0))
}
it("should animate bucket action without options") {
expect(capturedActionOptions).to(equal([]))
}
describe("bucket action animations block") {
beforeEach {
sut.contentView.bounds = CGRect(x: 0, y: 0, width: 100, height: 0)
sut.bucketImageView.alpha = 0
capturedActionAnimations()
}
it("should set shot image view tranform") {
expect(sut.shotImageView.transform).to(equal(CGAffineTransform.identity.translatedBy(x: 100, y: 0)))
}
}
describe("bucket action completion block") {
beforeEach {
capturedActionCompletion(true)
}
itBehavesLike("returning to initial cell state animation") {
["expectedDelay": 0.2,
"expectedAction": ShotCollectionViewCellActionWrapper(action: ShotCollectionViewCell.Action.bucket)]
}
}
}
context("slightly left") {
beforeEach {
panGestureRecognizerMock.translationInViewStub.on(any()) { _ in
return CGPoint(x: -50, y:0)
}
panGestureRecognizer!.specRecognize(with: panGestureRecognizerMock)
}
it("should animate comment action with duration 0.3") {
expect(capturedActionDuration).to(equal(0.3))
}
it("should animate comment action without delay") {
expect(capturedActionDelay).to(equal(0))
}
it("should animate comment action without options") {
expect(capturedActionOptions).to(equal([]))
}
describe("comment action animations block") {
beforeEach {
sut.contentView.bounds = CGRect(x: 0, y: 0, width: 100, height: 0)
sut.commentImageView.alpha = 0
capturedActionAnimations()
}
it("should set shot image view tranform") {
expect(sut.shotImageView.transform).to(equal(CGAffineTransform.identity.translatedBy(x: -100, y: 0)))
}
}
describe("comment action completion block") {
beforeEach {
capturedActionCompletion(true)
}
itBehavesLike("returning to initial cell state animation") {
["expectedDelay": 0.2,
"expectedAction": ShotCollectionViewCellActionWrapper(action: ShotCollectionViewCell.Action.comment)]
}
}
}
}
}
}
describe("gesture recognizer should begin") {
context("when gesture recognizer is pan gesture recognizer") {
context("when user is scrolling with higher horizontal velocity") {
var gestureRecognizerShouldBegin: Bool!
beforeEach {
let panGestureRecognize = PanGestureRecognizerMock()
panGestureRecognize.velocityInViewStub.on(any()) { _ in
return CGPoint(x:100, y:0)
}
gestureRecognizerShouldBegin = sut.gestureRecognizerShouldBegin(panGestureRecognize)
}
it("should begin gesture recognizer") {
expect(gestureRecognizerShouldBegin).to(beTruthy())
}
}
context("when user is scrolling with higher vertical velocity") {
var gestureRecognizerShouldBegin: Bool!
beforeEach {
let panGestureRecognize = PanGestureRecognizerMock()
panGestureRecognize.velocityInViewStub.on(any()) { _ in
return CGPoint(x:0, y:100)
}
gestureRecognizerShouldBegin = sut.gestureRecognizerShouldBegin(panGestureRecognize)
}
it("should not begin gesture recognizer") {
expect(gestureRecognizerShouldBegin).to(beFalsy())
}
}
}
}
}
describe("reusable") {
describe("reuse identifier") {
var reuseIdentifier: String?
beforeEach {
reuseIdentifier = ShotCollectionViewCell.identifier
}
it("should have proper reuse identifier") {
expect(reuseIdentifier).to(equal("ShotCollectionViewCell.Type"))
}
}
}
describe("gesture recognizer delegate") {
describe("gesture recognize should should recognize simultaneously") {
var shouldRecognizeSimultaneously: Bool!
beforeEach {
shouldRecognizeSimultaneously = sut.gestureRecognizer(UIGestureRecognizer(), shouldRecognizeSimultaneouslyWith: UIGestureRecognizer())
}
it("should alwawys block other gesture recognizers") {
expect(shouldRecognizeSimultaneously).to(beFalsy())
}
}
}
}
}
| gpl-3.0 |
zhangjk4859/MyWeiBoProject | sinaWeibo/sinaWeibo/Classes/Message/JKMessageTableViewController.swift | 1 | 2951 | //
// JKMessageTableViewController.swift
// sinaWeibo
//
// Created by 张俊凯 on 16/6/5.
// Copyright © 2016年 张俊凯. All rights reserved.
//
import UIKit
class JKMessageTableViewController: JKBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 1.如果没有登录, 就设置未登录界面的信息
if !userLogin
{
visitView?.setupVisitInfo(false, imageName: "visitordiscover_image_message", message: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
hejunbinlan/Carlos | Sample/DataCacheSampleViewController.swift | 3 | 467 | import Foundation
import UIKit
import Carlos
class DataCacheSampleViewController: BaseCacheViewController {
private var cache: BasicCache<NSURL, NSData>!
override func fetchRequested() {
super.fetchRequested()
cache.get(NSURL(string: urlKeyField?.text ?? "")!)
}
override func titleForScreen() -> String {
return "Data cache"
}
override func setupCache() {
super.setupCache()
cache = CacheProvider.dataCache()
}
} | mit |
loudnate/Loop | LoopCore/Result.swift | 1 | 167 | //
// Result.swift
// Loop
//
// Copyright © 2017 LoopKit Authors. All rights reserved.
//
public enum Result<T> {
case success(T)
case failure(Error)
}
| apache-2.0 |
orta/RxSwift | RxSwift/RxSwift/Observables/Observable+Single.swift | 1 | 5128 | //
// Observable+Single.swift
// Rx
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// as observable
public func asObservable<E>
(source: Observable<E>) -> Observable<E> {
if let asObservable = source as? AsObservable<E> {
return asObservable.omega()
}
else {
return AsObservable(source: source)
}
}
// distinct until changed
public func distinctUntilChangedOrDie<E: Equatable>(source: Observable<E>)
-> Observable<E> {
return distinctUntilChangedOrDie({ success($0) }, { success($0 == $1) })(source)
}
public func distinctUntilChangedOrDie<E, K: Equatable>
(keySelector: (E) -> Result<K>)
-> (Observable<E> -> Observable<E>) {
return { source in
return distinctUntilChangedOrDie(keySelector, { success($0 == $1) })(source)
}
}
public func distinctUntilChangedOrDie<E>
(comparer: (lhs: E, rhs: E) -> Result<Bool>)
-> (Observable<E> -> Observable<E>) {
return { source in
return distinctUntilChangedOrDie({ success($0) }, comparer)(source)
}
}
public func distinctUntilChangedOrDie<E, K>
(keySelector: (E) -> Result<K>, comparer: (lhs: K, rhs: K) -> Result<Bool>)
-> (Observable<E> -> Observable<E>) {
return { source in
return DistinctUntilChanged(source: source, selector: keySelector, comparer: comparer)
}
}
public func distinctUntilChanged<E: Equatable>(source: Observable<E>)
-> Observable<E> {
return distinctUntilChanged({ $0 }, { ($0 == $1) })(source)
}
public func distinctUntilChanged<E, K: Equatable>
(keySelector: (E) -> K)
-> (Observable<E> -> Observable<E>) {
return { source in
return distinctUntilChanged(keySelector, { ($0 == $1) })(source)
}
}
public func distinctUntilChanged<E>
(comparer: (lhs: E, rhs: E) -> Bool)
-> (Observable<E> -> Observable<E>) {
return { source in
return distinctUntilChanged({ ($0) }, comparer)(source)
}
}
public func distinctUntilChanged<E, K>
(keySelector: (E) -> K, comparer: (lhs: K, rhs: K) -> Bool)
-> (Observable<E> -> Observable<E>) {
return { source in
return DistinctUntilChanged(source: source, selector: {success(keySelector($0)) }, comparer: { success(comparer(lhs: $0, rhs: $1))})
}
}
// do
public func doOrDie<E>
(eventHandler: (Event<E>) -> Result<Void>)
-> (Observable<E> -> Observable<E>) {
return { source in
return Do(source: source, eventHandler: eventHandler)
}
}
public func `do`<E>
(eventHandler: (Event<E>) -> Void)
-> (Observable<E> -> Observable<E>) {
return { source in
return Do(source: source, eventHandler: { success(eventHandler($0)) })
}
}
// doOnNext
public func doOnNext<E>
(actionOnNext: E -> Void)
-> (Observable<E> -> Observable<E>) {
return { source in
return source >- `do` { event in
switch event {
case .Next(let boxedValue):
let value = boxedValue.value
actionOnNext(value)
default:
break
}
}
}
}
// map aka select
public func mapOrDie<E, R>
(selector: E -> Result<R>)
-> (Observable<E> -> Observable<R>) {
return { source in
return selectOrDie(selector)(source)
}
}
public func map<E, R>
(selector: E -> R)
-> (Observable<E> -> Observable<R>) {
return { source in
return select(selector)(source)
}
}
public func mapWithIndexOrDie<E, R>
(selector: (E, Int) -> Result<R>)
-> (Observable<E> -> Observable<R>) {
return { source in
return selectWithIndexOrDie(selector)(source)
}
}
public func mapWithIndex<E, R>
(selector: (E, Int) -> R)
-> (Observable<E> -> Observable<R>) {
return { source in
return selectWithIndex(selector)(source)
}
}
// select
public func selectOrDie<E, R>
(selector: (E) -> Result<R>)
-> (Observable<E> -> Observable<R>) {
return { source in
return Select(source: source, selector: selector)
}
}
public func select<E, R>
(selector: (E) -> R)
-> (Observable<E> -> Observable<R>) {
return { source in
return Select(source: source, selector: {success(selector($0)) })
}
}
public func selectWithIndexOrDie<E, R>
(selector: (E, Int) -> Result<R>)
-> (Observable<E> -> Observable<R>) {
return { source in
return Select(source: source, selector: selector)
}
}
public func selectWithIndex<E, R>
(selector: (E, Int) -> R)
-> (Observable<E> -> Observable<R>) {
return { source in
return Select(source: source, selector: {success(selector($0, $1)) })
}
}
// Prefixes observable sequence with `firstElement` element.
// The same functionality could be achieved using `concat([returnElement(prefix), source])`,
// but this is significantly more efficient implementation.
public func startWith<E>
(firstElement: E)
-> (Observable<E> -> Observable<E>) {
return { source in
return StartWith(source: source, element: firstElement)
}
}
| mit |
bolivarbryan/Cappacitate2015-Cartagena | SwiftMenu/SwiftMenu/View/CellTableViewCell.swift | 1 | 684 | //
// CellTableViewCell.swift
// SwiftMenu
//
// Created by Bryan A Bolivar M on 5/9/15.
// Copyright (c) 2015 Bolivar. All rights reserved.
//
import UIKit
class CellTableViewCell: UITableViewCell {
@IBOutlet weak var cellImage: UIImageView!
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var details: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
jpedrosa/sua_nc | Sources/ascii.swift | 2 | 830 |
public class Ascii {
public static func toLowerCase(c: UInt8) -> UInt8 {
if c >= 65 && c <= 90 {
return c + 32
}
return c
}
public static func toLowerCase(bytes: [UInt8]) -> [UInt8] {
var a = bytes
let len = a.count
for i in 0..<len {
let c = a[i]
if c >= 65 && c <= 90 {
a[i] = c + 32
}
}
return a
}
public static func toLowerCase(bytes: [[UInt8]]) -> [[UInt8]] {
var a = bytes
let len = a.count
for i in 0..<len {
let b = a[i]
let blen = b.count
for bi in 0..<blen {
let c = b[bi]
if c >= 65 && c <= 90 {
a[i][bi] = c + 32
}
}
}
return a
}
public static func toLowerCase(string: String) -> String? {
return String.fromCharCodes(toLowerCase(string.bytes))
}
}
| apache-2.0 |
dalu93/SwiftHelpSet | Sources/Utilities/ConnectionStatus.swift | 1 | 1681 | //
// ConnectionStatus.swift
// SwiftHelpSet
//
// Created by Luca D'Alberti on 7/15/16.
// Copyright © 2016 dalu93. All rights reserved.
//
import Foundation
/**
The enum describes the connection status with backend.
- notStarted: The connection is not started yet
- inProgress: The connection is in progress. The associated value is a generic
`Request`
- completed: The connection is completed. See `Completion` to know what the associated value
- SeeAlso: `Completion` enum
*/
public enum ConnectionStatus<Request, Value> {
case notStarted
case inProgress(Request)
case completed(Completion<Value>)
/// The associated request, if the status is `inProgress`, otherwise `nil`
public var request: Request? {
switch self {
case .inProgress(let request): return request
default: return nil
}
}
/// The associated value if the connection was completed with success, otherwise `nil`
public var value: Value? {
switch self {
case .completed(let completion):
switch completion {
case .success(let value): return value
case .failed(_): return nil
}
default: return nil
}
}
/// The associated error if the connection was completed with error, otherwise `nil`
public var error: NSError? {
switch self {
case .completed(let completion):
switch completion {
case .success(_): return nil
case .failed(let error): return error
}
default: return nil
}
}
}
| mit |
alvesmarcel/ios-nanodegree-meme-me | MemeMe/AppDelegate.swift | 1 | 2135 | //
// AppDelegate.swift
// MemeMe
//
// Created by Marcel Oliveira Alves on 5/23/15.
// Copyright (c) 2015 Marcel Oliveira Alves. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// TODO: Remove this array from here
var memes = [Meme]()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/FeatureWithdrawalLocks/Sources/FeatureWithdrawalLocksUI/Localization/LocalizationConstants+WithdrawalLock.swift | 1 | 2496 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Localization
extension LocalizationConstants {
enum WithdrawalLocks {
static let onHoldTitle = NSLocalizedString(
"On Hold",
comment: "Withdrawal Locks: On Hold Title"
)
static let onHoldAmountTitle = NSLocalizedString(
"%@ On Hold",
comment: "Withdrawal Locks: On Hold Title with the amount"
)
// swiftlint:disable line_length
static let holdingPeriodDescription = NSLocalizedString(
"Newly added funds are subject to a holding period. You can transfer between your Trading, Rewards, and Exchange accounts in the meantime.",
comment: "Withdrawal Locks: Holding period description"
)
static let doesNotLookRightDescription = NSLocalizedString(
"See that something doesn't look right?",
comment: "Withdrawal Locks: Something doesn't look right question"
)
static let contactSupportTitle = NSLocalizedString(
"Contact support",
comment: "Withdrawal Locks: Contact support title"
)
static let noLocks = NSLocalizedString(
"You do not have any pending withdrawal locks.",
comment: "Withdrawal Locks: Held Until section title"
)
static let heldUntilTitle = NSLocalizedString(
"Held Until",
comment: "Withdrawal Locks: Held Until section title"
)
static let amountTitle = NSLocalizedString(
"Amount",
comment: "Withdrawal Locks: Amount section title"
)
static let availableToWithdrawTitle = NSLocalizedString(
"Available to Withdraw",
comment: "Withdrawal Locks: Available to Withdraw title"
)
static let learnMoreButtonTitle = NSLocalizedString(
"Learn More",
comment: "Withdrawal Locks: Learn More button title"
)
static let learnMoreTitle = NSLocalizedString(
"Learn more ->",
comment: "Withdrawal Locks: Learn More title"
)
static let seeDetailsButtonTitle = NSLocalizedString(
"See Details",
comment: "Withdrawal Locks: See Details button title"
)
static let confirmButtonTitle = NSLocalizedString(
"I Understand",
comment: "Withdrawal Locks: I Understand button title"
)
}
}
| lgpl-3.0 |
blue42u/swift-t | stc/tests/560-file-1.swift | 4 | 450 | import assert;
main {
file infile = input_file("alice.txt");
file outfile <"bob.txt"> = infile;
assertEqual(filename(infile), "alice.txt", "filename infile");
assertEqual(filename(outfile), "bob.txt", "filename outfile");
}
file infile = input_file("alice.txt");
file outfile <"bob2.txt"> = infile;
assertEqual(filename(infile), "alice.txt", "filename infile");
assertEqual(filename(outfile), "bob2.txt", "filename outfile");
| apache-2.0 |
pepaslabs/TODOApp | TODOApp/Array+get.swift | 1 | 384 | //
// Array+get.swift
// TODOApp
//
// Created by Pepas Personal on 7/26/15.
// Copyright (c) 2015 Pepas Personal. All rights reserved.
//
import Foundation
extension Array
{
func get(index: Int) -> Element?
{
if index < 0 || index >= self.count
{
return nil
}
else
{
return self[index]
}
}
}
| mit |
xcbakery/xcbakery | Sources/CookingKit/Recipe/Util/RecipeParser.swift | 1 | 626 | //
// XCBRecipeParser.swift
// xcbakery
//
// Created by Nam Seok Hyeon on 5/19/17.
// Copyright © 2017 Nimbl3. All rights reserved.
//
import Foundation
import SwiftyJSON
public struct RecipeParser {
public func parse(_ templateURL: URL) throws -> Recipe {
let recipeURL = templateURL.appendingPathComponent(recipeFileName)
let jsonString = try String(contentsOf: recipeURL, encoding: .utf8)
if let recipe = Recipe(json: JSON(parseJSON: jsonString), templateURL: templateURL) {
return recipe
} else {
throw RecipeParserError.invalidFormat
}
}
}
| mit |
apple/swift-nio-http2 | Sources/NIOHTTP2PerformanceTester/main.swift | 1 | 5440 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import Dispatch
// MARK: Test Harness
var warning: String = ""
assert({
print("======================================================")
print("= YOU ARE RUNNING NIOPerformanceTester IN DEBUG MODE =")
print("======================================================")
warning = " <<< DEBUG MODE >>>"
return true
}())
public func measure(_ fn: () throws -> Int) rethrows -> [TimeInterval] {
func measureOne(_ fn: () throws -> Int) rethrows -> TimeInterval {
let start = Date()
_ = try fn()
let end = Date()
return end.timeIntervalSince(start)
}
_ = try measureOne(fn) /* pre-heat and throw away */
var measurements = Array(repeating: 0.0, count: 10)
for i in 0..<10 {
measurements[i] = try measureOne(fn)
}
return measurements
}
let limitSet = CommandLine.arguments.dropFirst()
public func measureAndPrint(desc: String, fn: () throws -> Int) rethrows -> Void {
#if CACHEGRIND
// When CACHEGRIND is set we only run a single requested test, and we only run it once. No printing or other mess.
if limitSet.contains(desc) {
_ = try fn()
}
#else
if limitSet.count == 0 || limitSet.contains(desc) {
print("measuring\(warning): \(desc): ", terminator: "")
let measurements = try measure(fn)
print(measurements.reduce("") { $0 + "\($1), " })
} else {
print("skipping '\(desc)', limit set = \(limitSet)")
}
#endif
}
func measureAndPrint<B: Benchmark>(desc: String, benchmark bench: @autoclosure () -> B) throws {
// Avoids running setUp/tearDown when we don't want that benchmark.
guard limitSet.count == 0 || limitSet.contains(desc) else {
return
}
let bench = bench()
try bench.setUp()
defer {
bench.tearDown()
}
try measureAndPrint(desc: desc) {
return try bench.run()
}
}
// MARK: Utilities
try measureAndPrint(desc: "1_conn_10k_reqs", benchmark: Bench1Conn10kRequests())
try measureAndPrint(desc: "encode_100k_header_blocks_indexable", benchmark: HPACKHeaderEncodingBenchmark(headers: .indexable, loopCount: 100_000))
try measureAndPrint(desc: "encode_100k_header_blocks_nonindexable", benchmark: HPACKHeaderEncodingBenchmark(headers: .nonIndexable, loopCount: 100_000))
try measureAndPrint(desc: "encode_100k_header_blocks_neverIndexed", benchmark: HPACKHeaderEncodingBenchmark(headers: .neverIndexed, loopCount: 100_000))
try measureAndPrint(desc: "decode_100k_header_blocks_indexable", benchmark: HPACKHeaderDecodingBenchmark(headers: .indexable, loopCount: 100_000))
try measureAndPrint(desc: "decode_100k_header_blocks_nonindexable", benchmark: HPACKHeaderDecodingBenchmark(headers: .nonIndexable, loopCount: 100_000))
try measureAndPrint(desc: "decode_100k_header_blocks_neverIndexed", benchmark: HPACKHeaderDecodingBenchmark(headers: .neverIndexed, loopCount: 100_000))
try measureAndPrint(desc: "hpackheaders_canonical_form", benchmark: HPACKHeaderCanonicalFormBenchmark(.noTrimming))
try measureAndPrint(desc: "hpackheaders_canonical_form_trimming_whitespace", benchmark: HPACKHeaderCanonicalFormBenchmark(.trimmingWhitespace))
try measureAndPrint(desc: "hpackheaders_canonical_form_trimming_whitespace_short_strings", benchmark: HPACKHeaderCanonicalFormBenchmark(.trimmingWhitespaceFromShortStrings))
try measureAndPrint(desc: "hpackheaders_canonical_form_trimming_whitespace_long_strings", benchmark: HPACKHeaderCanonicalFormBenchmark(.trimmingWhitespaceFromLongStrings))
try measureAndPrint(desc: "hpackheaders_normalize_httpheaders_removing_10k_conn_headers", benchmark: HPACKHeadersNormalizationOfHTTPHeadersBenchmark(headersKind: .manyUniqueConnectionHeaderValues(10_000), iterations: 10))
try measureAndPrint(desc: "hpackheaders_normalize_httpheaders_keeping_10k_conn_headers", benchmark: HPACKHeadersNormalizationOfHTTPHeadersBenchmark(headersKind: .manyConnectionHeaderValuesWhichAreNotRemoved(10_000), iterations: 10))
try measureAndPrint(desc: "huffman_encode_basic", benchmark: HuffmanEncodingBenchmark(huffmanString: .basicHuffmanString, loopCount: 100))
try measureAndPrint(desc: "huffman_encode_complex", benchmark: HuffmanEncodingBenchmark(huffmanString: .complexHuffmanString, loopCount: 100))
try measureAndPrint(desc: "huffman_decode_basic", benchmark: HuffmanDecodingBenchmark(huffmanBytes: .basicHuffmanBytes, loopCount: 25))
try measureAndPrint(desc: "huffman_decode_complex", benchmark: HuffmanDecodingBenchmark(huffmanBytes: .complexHuffmanBytes, loopCount: 10))
try measureAndPrint(desc: "server_only_10k_requests_1_concurrent", benchmark: ServerOnly10KRequestsBenchmark(concurrentStreams: 1))
try measureAndPrint(desc: "server_only_10k_requests_100_concurrent", benchmark: ServerOnly10KRequestsBenchmark(concurrentStreams: 100))
try measureAndPrint(desc: "stream_teardown_10k_requests_100_concurrent", benchmark: StreamTeardownBenchmark(concurrentStreams: 100))
| apache-2.0 |
HotCatLX/SwiftStudy | 17-BasicGesture/BasicGesture/ViewController.swift | 1 | 1863 | //
// ViewController.swift
// BasicGesture
//
// Created by suckerl on 2017/5/22.
// Copyright © 2017年 suckel. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
fileprivate lazy var image :UIImageView = {
let image = UIImageView()
image.image = UIImage(named: "one")
image.isUserInteractionEnabled = true
return image
}()
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
self.swipe()
}
}
extension ViewController {
func setupUI() {
view.addSubview(image)
image.frame = view.bounds
}
/*
UITapGestureRecognizer 轻拍手势
UISwipeGestureRecognizer 轻扫手势
UILongPressGestureRecognizer 长按手势
UIPanGestureRecognizer 平移手势
UIPinchGestureRecognizer 捏合(缩放)手势
UIRotationGestureRecognizer 旋转手势
UIScreenEdgePanGestureRecognizer 屏幕边缘平移
*/
func swipe() {
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swipeSelector(swipe:)))
swipeLeft.direction = UISwipeGestureRecognizerDirection.left
self.image.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action:#selector(ViewController.swipeSelector(swipe:)))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.image.addGestureRecognizer(swipeRight)
}
func swipeSelector(swipe:UISwipeGestureRecognizer) {
if swipe.direction == UISwipeGestureRecognizerDirection.left {
let twoVC = TwoController()
self.show(twoVC, sender: nil)
}else {
let threeVC = ThreeController()
self.show(threeVC, sender: nil)
}
}
}
| mit |
Cloudage/XWebView | XWebViewTests/XWVScriptingTest.swift | 1 | 2947 | /*
Copyright 2015 XWebView
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import XCTest
import XWebView
class XWVScriptingTest : XWVTestCase {
class Plugin : NSObject, XWVScripting {
let expectation: XCTestExpectation?
init(expectation: XCTestExpectation?) {
self.expectation = expectation
}
func rewriteGeneratedStub(stub: String, forKey key: String) -> String {
switch key {
case ".global": return stub + "window.stub = true;\n"
case ".local": return stub + "exports.abc = true;\n"
default: return stub
}
}
func finalizeForScript() {
expectation?.fulfill()
}
class func isSelectorExcludedFromScript(selector: Selector) -> Bool {
return selector == Selector("initWithExpectation:")
}
class func isKeyExcludedFromScript(name: UnsafePointer<Int8>) -> Bool {
return String(UTF8String: name) == "expectation"
}
}
let namespace = "xwvtest"
func testRewriteGeneratedStub() {
let desc = "javascriptStub"
let script = "if (window.stub && \(namespace).abc) fulfill('\(desc)');"
_ = expectationWithDescription(desc)
loadPlugin(Plugin(expectation: nil), namespace: namespace, script: script)
waitForExpectationsWithTimeout(2, handler: nil)
}
func testFinalizeForScript() {
let desc = "finalizeForScript"
let script = "\(namespace).dispose()"
let expectation = expectationWithDescription(desc)
loadPlugin(Plugin(expectation: expectation), namespace: namespace, script: script)
waitForExpectationsWithTimeout(2, handler: nil)
}
func testIsSelectorExcluded() {
let desc = "isSelectorExcluded"
let script = "if (\(namespace).initWithExpectation == undefined) fulfill('\(desc)')"
_ = expectationWithDescription(desc)
loadPlugin(Plugin(expectation: nil), namespace: namespace, script: script)
waitForExpectationsWithTimeout(2, handler: nil)
}
func testIsKeyExcluded() {
let desc = "isKeyExcluded"
let script = "if (!\(namespace).hasOwnProperty('expectation')) fulfill('\(desc)')"
_ = expectationWithDescription(desc)
loadPlugin(Plugin(expectation: nil), namespace: namespace, script: script)
waitForExpectationsWithTimeout(2, handler: nil)
}
}
| apache-2.0 |
uasys/swift | stdlib/public/core/Reverse.swift | 1 | 17839 | //===--- Reverse.swift - Sequence and collection reversal -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension MutableCollection where Self : BidirectionalCollection {
/// Reverses the elements of the collection in place.
///
/// The following example reverses the elements of an array of characters:
///
/// var characters: [Character] = ["C", "a", "f", "é"]
/// characters.reverse()
/// print(characters)
/// // Prints "["é", "f", "a", "C"]
///
/// - Complexity: O(*n*), where *n* is the number of elements in the
/// collection.
public mutating func reverse() {
if isEmpty { return }
var f = startIndex
var l = index(before: endIndex)
while f < l {
swapAt(f, l)
formIndex(after: &f)
formIndex(before: &l)
}
}
}
/// An iterator that can be much faster than the iterator of a reversed slice.
// TODO: See about using this in more places
@_fixed_layout
public struct _ReverseIndexingIterator<
Elements : BidirectionalCollection
> : IteratorProtocol, Sequence {
@_inlineable
@inline(__always)
/// Creates an iterator over the given collection.
public /// @testable
init(_elements: Elements, _position: Elements.Index) {
self._elements = _elements
self._position = _position
}
@_inlineable
@inline(__always)
public mutating func next() -> Elements.Element? {
guard _fastPath(_position != _elements.startIndex) else { return nil }
_position = _elements.index(before: _position)
return _elements[_position]
}
@_versioned
internal let _elements: Elements
@_versioned
internal var _position: Elements.Index
}
// FIXME(ABI)#59 (Conditional Conformance): we should have just one type,
// `ReversedCollection`, that has conditional conformances to
// `RandomAccessCollection`, and possibly `MutableCollection` and
// `RangeReplaceableCollection`.
// rdar://problem/17144340
// FIXME: swift-3-indexing-model - should gyb ReversedXxx & ReversedRandomAccessXxx
/// An index that traverses the same positions as an underlying index,
/// with inverted traversal direction.
@_fixed_layout
public struct ReversedIndex<Base : Collection> : Comparable {
/// Creates a new index into a reversed collection for the position before
/// the specified index.
///
/// When you create an index into a reversed collection using `base`, an
/// index from the underlying collection, the resulting index is the
/// position of the element *before* the element referenced by `base`. The
/// following example creates a new `ReversedIndex` from the index of the
/// `"a"` character in a string's character view.
///
/// let name = "Horatio"
/// let aIndex = name.index(of: "a")!
/// // name[aIndex] == "a"
///
/// let reversedName = name.reversed()
/// let i = ReversedIndex<String>(aIndex)
/// // reversedName[i] == "r"
///
/// The element at the position created using `ReversedIndex<...>(aIndex)` is
/// `"r"`, the character before `"a"` in the `name` string.
///
/// - Parameter base: The position after the element to create an index for.
@_inlineable
public init(_ base: Base.Index) {
self.base = base
}
/// The position after this position in the underlying collection.
///
/// To find the position that corresponds with this index in the original,
/// underlying collection, use that collection's `index(before:)` method
/// with the `base` property.
///
/// The following example declares a function that returns the index of the
/// last even number in the passed array, if one is found. First, the
/// function finds the position of the last even number as a `ReversedIndex`
/// in a reversed view of the array of numbers. Next, the function calls the
/// array's `index(before:)` method to return the correct position in the
/// passed array.
///
/// func indexOfLastEven(_ numbers: [Int]) -> Int? {
/// let reversedNumbers = numbers.reversed()
/// guard let i = reversedNumbers.index(where: { $0 % 2 == 0 })
/// else { return nil }
///
/// return numbers.index(before: i.base)
/// }
///
/// let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51]
/// if let lastEven = indexOfLastEven(numbers) {
/// print("Last even number: \(numbers[lastEven])")
/// }
/// // Prints "Last even number: 40"
public let base: Base.Index
@_inlineable
public static func == (
lhs: ReversedIndex<Base>,
rhs: ReversedIndex<Base>
) -> Bool {
return lhs.base == rhs.base
}
@_inlineable
public static func < (
lhs: ReversedIndex<Base>,
rhs: ReversedIndex<Base>
) -> Bool {
// Note ReversedIndex has inverted logic compared to base Base.Index
return lhs.base > rhs.base
}
}
/// A collection that presents the elements of its base collection
/// in reverse order.
///
/// - Note: This type is the result of `x.reversed()` where `x` is a
/// collection having bidirectional indices.
///
/// The `reversed()` method is always lazy when applied to a collection
/// with bidirectional indices, but does not implicitly confer
/// laziness on algorithms applied to its result. In other words, for
/// ordinary collections `c` having bidirectional indices:
///
/// * `c.reversed()` does not create new storage
/// * `c.reversed().map(f)` maps eagerly and returns a new array
/// * `c.lazy.reversed().map(f)` maps lazily and returns a `LazyMapCollection`
///
/// - See also: `ReversedRandomAccessCollection`
@_fixed_layout
public struct ReversedCollection<
Base : BidirectionalCollection
> : BidirectionalCollection {
/// Creates an instance that presents the elements of `base` in
/// reverse order.
///
/// - Complexity: O(1)
@_versioned
@_inlineable
internal init(_base: Base) {
self._base = _base
}
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = ReversedIndex<Base>
public typealias IndexDistance = Base.IndexDistance
@_fixed_layout
public struct Iterator : IteratorProtocol, Sequence {
@_inlineable
@inline(__always)
public /// @testable
init(elements: Base, endPosition: Base.Index) {
self._elements = elements
self._position = endPosition
}
@_inlineable
@inline(__always)
public mutating func next() -> Base.Iterator.Element? {
guard _fastPath(_position != _elements.startIndex) else { return nil }
_position = _elements.index(before: _position)
return _elements[_position]
}
@_versioned
internal let _elements: Base
@_versioned
internal var _position: Base.Index
}
@_inlineable
@inline(__always)
public func makeIterator() -> Iterator {
return Iterator(elements: _base, endPosition: _base.endIndex)
}
@_inlineable
public var startIndex: Index {
return ReversedIndex(_base.endIndex)
}
@_inlineable
public var endIndex: Index {
return ReversedIndex(_base.startIndex)
}
@_inlineable
public func index(after i: Index) -> Index {
return ReversedIndex(_base.index(before: i.base))
}
@_inlineable
public func index(before i: Index) -> Index {
return ReversedIndex(_base.index(after: i.base))
}
@_inlineable
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
return ReversedIndex(_base.index(i.base, offsetBy: -n))
}
@_inlineable
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
return _base.index(i.base, offsetBy: -n, limitedBy: limit.base).map { ReversedIndex($0) }
}
@_inlineable
public func distance(from start: Index, to end: Index) -> IndexDistance {
return _base.distance(from: end.base, to: start.base)
}
@_inlineable
public subscript(position: Index) -> Base.Element {
return _base[_base.index(before: position.base)]
}
@_inlineable
public subscript(bounds: Range<Index>) -> BidirectionalSlice<ReversedCollection> {
return BidirectionalSlice(base: self, bounds: bounds)
}
public let _base: Base
}
/// An index that traverses the same positions as an underlying index,
/// with inverted traversal direction.
@_fixed_layout
public struct ReversedRandomAccessIndex<
Base : RandomAccessCollection
> : Comparable {
/// Creates a new index into a reversed collection for the position before
/// the specified index.
///
/// When you create an index into a reversed collection using the index
/// passed as `base`, an index from the underlying collection, the resulting
/// index is the position of the element *before* the element referenced by
/// `base`. The following example creates a new `ReversedIndex` from the
/// index of the `"a"` character in a string's character view.
///
/// let name = "Horatio"
/// let aIndex = name.index(of: "a")!
/// // name[aIndex] == "a"
///
/// let reversedName = name.reversed()
/// let i = ReversedIndex<String>(aIndex)
/// // reversedName[i] == "r"
///
/// The element at the position created using `ReversedIndex<...>(aIndex)` is
/// `"r"`, the character before `"a"` in the `name` string. Viewed from the
/// perspective of the `reversedCharacters` collection, of course, `"r"` is
/// the element *after* `"a"`.
///
/// - Parameter base: The position after the element to create an index for.
@_inlineable
public init(_ base: Base.Index) {
self.base = base
}
/// The position after this position in the underlying collection.
///
/// To find the position that corresponds with this index in the original,
/// underlying collection, use that collection's `index(before:)` method
/// with this index's `base` property.
///
/// The following example declares a function that returns the index of the
/// last even number in the passed array, if one is found. First, the
/// function finds the position of the last even number as a `ReversedIndex`
/// in a reversed view of the array of numbers. Next, the function calls the
/// array's `index(before:)` method to return the correct position in the
/// passed array.
///
/// func indexOfLastEven(_ numbers: [Int]) -> Int? {
/// let reversedNumbers = numbers.reversed()
/// guard let i = reversedNumbers.index(where: { $0 % 2 == 0 })
/// else { return nil }
///
/// return numbers.index(before: i.base)
/// }
///
/// let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51]
/// if let lastEven = indexOfLastEven(numbers) {
/// print("Last even number: \(numbers[lastEven])")
/// }
/// // Prints "Last even number: 40"
public let base: Base.Index
@_inlineable
public static func == (
lhs: ReversedRandomAccessIndex<Base>,
rhs: ReversedRandomAccessIndex<Base>
) -> Bool {
return lhs.base == rhs.base
}
@_inlineable
public static func < (
lhs: ReversedRandomAccessIndex<Base>,
rhs: ReversedRandomAccessIndex<Base>
) -> Bool {
// Note ReversedRandomAccessIndex has inverted logic compared to base Base.Index
return lhs.base > rhs.base
}
}
/// A collection that presents the elements of its base collection
/// in reverse order.
///
/// - Note: This type is the result of `x.reversed()` where `x` is a
/// collection having random access indices.
/// - See also: `ReversedCollection`
@_fixed_layout
public struct ReversedRandomAccessCollection<
Base : RandomAccessCollection
> : RandomAccessCollection {
// FIXME: swift-3-indexing-model: tests for ReversedRandomAccessIndex and
// ReversedRandomAccessCollection.
/// Creates an instance that presents the elements of `base` in
/// reverse order.
///
/// - Complexity: O(1)
@_versioned
@_inlineable
internal init(_base: Base) {
self._base = _base
}
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = ReversedRandomAccessIndex<Base>
public typealias IndexDistance = Base.IndexDistance
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
public typealias Iterator = IndexingIterator<
ReversedRandomAccessCollection
>
@_inlineable
public var startIndex: Index {
return ReversedRandomAccessIndex(_base.endIndex)
}
@_inlineable
public var endIndex: Index {
return ReversedRandomAccessIndex(_base.startIndex)
}
@_inlineable
public func index(after i: Index) -> Index {
return ReversedRandomAccessIndex(_base.index(before: i.base))
}
@_inlineable
public func index(before i: Index) -> Index {
return ReversedRandomAccessIndex(_base.index(after: i.base))
}
@_inlineable
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
// FIXME: swift-3-indexing-model: tests.
return ReversedRandomAccessIndex(_base.index(i.base, offsetBy: -n))
}
@_inlineable
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
// FIXME: swift-3-indexing-model: tests.
return _base.index(i.base, offsetBy: -n, limitedBy: limit.base).map { Index($0) }
}
@_inlineable
public func distance(from start: Index, to end: Index) -> IndexDistance {
// FIXME: swift-3-indexing-model: tests.
return _base.distance(from: end.base, to: start.base)
}
@_inlineable
public subscript(position: Index) -> Base.Element {
return _base[_base.index(before: position.base)]
}
// FIXME: swift-3-indexing-model: the rest of methods.
public let _base: Base
}
extension BidirectionalCollection {
/// Returns a view presenting the elements of the collection in reverse
/// order.
///
/// You can reverse a collection without allocating new space for its
/// elements by calling this `reversed()` method. A `ReversedCollection`
/// instance wraps an underlying collection and provides access to its
/// elements in reverse order. This example prints the characters of a
/// string in reverse order:
///
/// let word = "Backwards"
/// for char in word.reversed() {
/// print(char, terminator: "")
/// }
/// // Prints "sdrawkcaB"
///
/// If you need a reversed collection of the same type, you may be able to
/// use the collection's sequence-based or collection-based initializer. For
/// example, to get the reversed version of a string, reverse its
/// characters and initialize a new `String` instance from the result.
///
/// let reversedWord = String(word.reversed())
/// print(reversedWord)
/// // Prints "sdrawkcaB"
///
/// - Complexity: O(1)
@_inlineable
public func reversed() -> ReversedCollection<Self> {
return ReversedCollection(_base: self)
}
}
extension RandomAccessCollection {
/// Returns a view presenting the elements of the collection in reverse
/// order.
///
/// You can reverse a collection without allocating new space for its
/// elements by calling this `reversed()` method. A
/// `ReversedRandomAccessCollection` instance wraps an underlying collection
/// and provides access to its elements in reverse order. This example
/// prints the elements of an array in reverse order:
///
/// let numbers = [3, 5, 7]
/// for number in numbers.reversed() {
/// print(number)
/// }
/// // Prints "7"
/// // Prints "5"
/// // Prints "3"
///
/// If you need a reversed collection of the same type, you may be able to
/// use the collection's sequence-based or collection-based initializer. For
/// example, to get the reversed version of an array, initialize a new
/// `Array` instance from the result of this `reversed()` method.
///
/// let reversedNumbers = Array(numbers.reversed())
/// print(reversedNumbers)
/// // Prints "[7, 5, 3]"
///
/// - Complexity: O(1)
@_inlineable
public func reversed() -> ReversedRandomAccessCollection<Self> {
return ReversedRandomAccessCollection(_base: self)
}
}
extension LazyCollectionProtocol
where
Self : BidirectionalCollection,
Elements : BidirectionalCollection {
/// Returns the elements of the collection in reverse order.
///
/// - Complexity: O(1)
@_inlineable
public func reversed() -> LazyBidirectionalCollection<
ReversedCollection<Elements>
> {
return ReversedCollection(_base: elements).lazy
}
}
extension LazyCollectionProtocol
where
Self : RandomAccessCollection,
Elements : RandomAccessCollection {
/// Returns the elements of the collection in reverse order.
///
/// - Complexity: O(1)
@_inlineable
public func reversed() -> LazyRandomAccessCollection<
ReversedRandomAccessCollection<Elements>
> {
return ReversedRandomAccessCollection(_base: elements).lazy
}
}
// ${'Local Variables'}:
// eval: (read-only-mode 1)
// End:
| apache-2.0 |
austinzheng/swift | test/multifile/Inputs/external-protocol-conformance/A.swift | 67 | 331 | protocol PHelper {
}
protocol P {
associatedtype Assoc: PHelper // expected-note {{protocol requires nested type 'Assoc'}}
}
struct A : P { // expected-error {{type 'A' does not conform to protocol 'P'}}
typealias Assoc = Int // expected-note {{possibly intended match 'A.Assoc' (aka 'Int') does not conform to 'PHelper'}}
}
| apache-2.0 |
apple/swift | validation-test/StdlibUnittest/ChildProcessShutdown/FailIfChildExitsDuringShutdown.swift | 19 | 887 | // RUN: %target-run-simple-swift 2>&1 | %FileCheck %s
// REQUIRES: executable_test
import StdlibUnittest
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import MSVCRT
#else
#error("Unsupported platform")
#endif
_setTestSuiteFailedCallback() { print("abort()") }
//
// Test that harness aborts when a test crashes if a child process exits with a
// non-zero code after all tests have finished running.
//
var TestSuiteChildExits = TestSuite("TestSuiteChildExits")
TestSuiteChildExits.test("passes") {
atexit {
_exit(1)
}
}
// CHECK: [ RUN ] TestSuiteChildExits.passes
// CHECK: [ OK ] TestSuiteChildExits.passes
// CHECK: TestSuiteChildExits: All tests passed
// CHECK: Abnormal child process termination: Exit(1).
// CHECK: The child process failed during shutdown, aborting.
// CHECK: abort()
runAllTests()
| apache-2.0 |
5lucky2xiaobin0/PandaTV | PandaTV/PandaTV/Classes/Main/VIew/GameCell.swift | 1 | 2082 | //
// GameCell.swift
// PandaTV
//
// Created by 钟斌 on 2017/3/24.
// Copyright © 2017年 xiaobin. All rights reserved.
//
import UIKit
import Kingfisher
class GameCell: UICollectionViewCell {
@IBOutlet weak var nowImage: UIImageView!
@IBOutlet weak var gameTitle: UILabel!
@IBOutlet weak var username: UILabel!
@IBOutlet weak var personNumber: UIButton!
@IBOutlet weak var gamename: UIButton!
var card_type : String?
var gameItem : GameItem? {
didSet {
if let item = gameItem {
var url : URL?
if let urlString = item.img {
url = URL(string: urlString)
}else {
let urlString = item.pictures?["img"] as! String
url = URL(string: urlString)
}
nowImage.kf.setImage(with: ImageResource(downloadURL: url!))
gameTitle.text = item.title ?? item.name
username.text = item.userItem?.nickName
if item.person_num > 10000 {
let number = CGFloat(item.person_num) / 10000.0
personNumber.setTitle(String(format: "%.1f", number) + "万", for: .normal)
}else {
personNumber.setTitle("\(item.person_num)", for: .normal)
}
//1 首页 card_type = cateroomlist 不显示
//2 全部游戏 cart_type = nil 不显示
//3 游戏界面 cart_type = cateroomlist 不显示
//4 娱乐界面 cart_type = cateroomlist 不显示
if card_type == "cateroomlist" || card_type == nil {
gamename.isHidden = true
}else {
gamename.isHidden = false
gamename.setTitle(item.gameType, for: .normal)
}
}
}
}
}
| mit |
See-Ku/SK4Toolkit | SK4Toolkit/core/SK4Dispatch.swift | 1 | 1670 | //
// SK4Dispatch.swift
// SK4Toolkit
//
// Created by See.Ku on 2016/03/24.
// Copyright (c) 2016 AxeRoad. All rights reserved.
//
import Foundation
// /////////////////////////////////////////////////////////////
// MARK: - 同期/非同期関係の処理
/// グローバルキューで非同期処理
public func sk4AsyncGlobal(exec: (()->Void)) {
let global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(global, exec)
}
/// メインキューで非同期処理
public func sk4AsyncMain(exec: (()->Void)) {
let main = dispatch_get_main_queue()
dispatch_async(main, exec)
}
/// 指定した秒数後にメインキューで処理を実行
public func sk4AsyncMain(after: NSTimeInterval, exec: (()->Void)) {
let delta = after * NSTimeInterval(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delta))
let main = dispatch_get_main_queue()
dispatch_after(time, main, exec)
}
/// 同期処理を実行
public func sk4Synchronized(obj: AnyObject, @noescape block: (()->Void)) {
objc_sync_enter(obj)
block()
objc_sync_exit(obj)
}
/// 指定された時間、待機する
public func sk4Sleep(time: NSTimeInterval) {
NSThread.sleepForTimeInterval(time)
}
/// 現在のキューはメインキューか?
public func sk4IsMainQueue() -> Bool {
return NSThread.isMainThread()
}
/*
/// GCDだけで判定する方法
func sk4IsMainQueue() -> Bool {
let main = dispatch_get_main_queue()
let main_label = dispatch_queue_get_label(main)
let current_label = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)
if main_label == current_label {
return true
} else {
return false
}
}
*/
// eof
| mit |
manfengjun/KYMart | Section/Mine/Controller/KYPendToPointViewController.swift | 1 | 3497 | //
// KYBonusToMoneyViewController.swift
// KYMart
//
// Created by JUN on 2017/7/3.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
import IQKeyboardManagerSwift
class KYPendToPointViewController: BaseViewController {
@IBOutlet weak var codeBgView: UIView!
@IBOutlet weak var saveBtn: UIButton!
@IBOutlet weak var bonusL: UILabel!
@IBOutlet weak var amountT: UITextField!
@IBOutlet weak var codeT: UITextField!
@IBOutlet weak var infoView: UIView!
@IBOutlet weak var headH: NSLayoutConstraint!
fileprivate lazy var codeView : PooCodeView = {
let codeView = PooCodeView(frame: CGRect(x: 0, y: 0, width: 70, height: 25), andChange: nil)
return codeView!
}()
fileprivate lazy var headView : KYUserInfoView = {
let headView = KYUserInfoView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH*3/5 + 51 + 51))
headView.userModel = SingleManager.instance.userInfo
return headView
}()
var pay_points:Int?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.subviews[0].alpha = 0
IQKeyboardManager.sharedManager().enable = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.subviews[0].alpha = 1
IQKeyboardManager.sharedManager().enable = false
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() {
setBackButtonInNav()
saveBtn.layer.masksToBounds = true
saveBtn.layer.cornerRadius = 5.0
codeBgView.addSubview(codeView)
bonusL.text = "\(pay_points!)"
headH.constant = SCREEN_WIDTH*3/5 + 51
infoView.addSubview(headView)
headView.titleL.text = "待发放转积分"
headView.userModel = SingleManager.instance.userInfo
}
@IBAction func saveAction(_ sender: UIButton) {
if (amountT.text?.isEmpty)! {
Toast(content: "不能为空")
return
}
let codeText = NSString(string: codeT.text!)
let codeStr = NSString(string: codeView.changeString)
let params = ["money":amountT.text!]
if codeText.caseInsensitiveCompare(codeStr as String).rawValue == 0 {
SJBRequestModel.push_fetchPendToPointData(params: params as [String : AnyObject], completion: { (response, status) in
if status == 1{
self.Toast(content: "申请成功")
self.navigationController?.popViewController(animated: true)
}
else
{
self.Toast(content: response as! String)
}
})
}
else
{
Toast(content: "验证码错误!")
}
}
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 |
Antondomashnev/FBSnapshotsViewer | FBSnapshotsViewerTests/TestLineNumberExtractorSpec.swift | 1 | 3666 | //
// TestLineNumberExtractorSpec.swift
// FBSnapshotsViewerTests
//
// Created by Anton Domashnev on 13.08.17.
// Copyright © 2017 Anton Domashnev. All rights reserved.
//
import Quick
import Nimble
@testable import FBSnapshotsViewer
class TestLineNumberExtractorSpec: QuickSpec {
override func spec() {
var subject: DefaultTestLineNumberExtractor!
beforeEach {
subject = DefaultTestLineNumberExtractor()
}
describe(".extractTestLineNumber") {
var logLine: ApplicationLogLine!
context("given kaleidoscopeCommandMessage") {
beforeEach {
logLine = ApplicationLogLine.kaleidoscopeCommandMessage(line: "foo/bar")
}
it("throws") {
expect { try subject.extractTestLineNumber(from: logLine) }.to(throwError())
}
}
context("given referenceImageSavedMessage") {
beforeEach {
logLine = ApplicationLogLine.referenceImageSavedMessage(line: "foo/bar")
}
it("throws") {
expect { try subject.extractTestLineNumber(from: logLine) }.to(throwError())
}
}
context("given applicationNameMessage") {
beforeEach {
logLine = ApplicationLogLine.applicationNameMessage(line: "foo/bar")
}
it("throws") {
expect { try subject.extractTestLineNumber(from: logLine) }.to(throwError())
}
}
context("given fbReferenceImageDirMessage") {
beforeEach {
logLine = ApplicationLogLine.fbReferenceImageDirMessage(line: "foo/bar")
}
it("throws") {
expect { try subject.extractTestLineNumber(from: logLine) }.to(throwError())
}
}
context("given snapshotTestErrorMessage") {
context("with valid line") {
beforeEach {
logLine = ApplicationLogLine.snapshotTestErrorMessage(line: "/Users/antondomashnev/Work/FBSnapshotsViewerExample/FBSnapshotsViewerExampleTests/FBSnapshotsViewerExampleTests.m:38: error: -[FBSnapshotsViewerExampleTests testRecord] : ((noErrors) is true) failed - Snapshot comparison failed: (null)")
}
it("returns valid test line number") {
let testLineNumber = try? subject.extractTestLineNumber(from: logLine)
expect(testLineNumber).to(equal(38))
}
}
context("with invalid line") {
beforeEach {
logLine = ApplicationLogLine.snapshotTestErrorMessage(line: "lalala lalala foo bar")
}
it("throws") {
expect { try subject.extractTestLineNumber(from: logLine) }.to(throwError())
}
}
}
context("given unknown") {
beforeEach {
logLine = ApplicationLogLine.unknown
}
it("throws") {
expect { try subject.extractTestLineNumber(from: logLine) }.to(throwError())
}
}
}
}
}
| mit |
Ribeiro/PapersPlease | Classes/ValidationTypes/ValidatorType.swift | 1 | 947 | //
// ValidatorType.swift
// PapersPlease
//
// Created by Brett Walker on 7/2/14.
// Copyright (c) 2014 Poet & Mountain, LLC. All rights reserved.
//
import Foundation
class ValidationStatus {
let valid = "ValidationStatusValid"
let invalid = "ValidationStatusInvalid"
}
let ValidatorUpdateNotification:String = "ValidatorUpdateNotification"
class ValidatorType {
var status = ValidationStatus()
var valid:Bool = false
var sendsUpdates:Bool = false
var identifier:NSString = ""
var validationStates:[String] = []
init () {
self.validationStates = [self.status.invalid]
}
func isTextValid(text:String) -> Bool {
self.valid = true
self.validationStates.removeAll()
self.validationStates.append(self.status.valid)
return self.valid
}
class func type() -> String {
return "ValidationTypeBase"
}
} | mit |
BellAppLab/SequencePlayer | Example/Example/ViewController.swift | 1 | 1800 | import UIKit
class ViewController: UIViewController, SequencePlayerDataSource, SequencePlayerDelegate {
var player: SequencePlayer!
lazy var urls: [URL] = {
var result = [URL]()
["http://media0.giphy.com/media/Wqhdoubttqizu/giphy.mp4",
"http://media0.giphy.com/media/3UvKSHiEspIKQ/200w.mp4",
"http://media0.giphy.com/media/mfmLlxkQn6eTS/200.mp4"].forEach
{ string in
if let url = URL(string: string) {
result.append(url)
}
}
return result
}()
@IBOutlet weak var playerView: SequencePlayerView!
@IBOutlet weak var spinningThing: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
self.player = SequencePlayer(withDataSource: self,
andDelegate: self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.player.play()
}
//MARK: Player Delegate
func sequencePlayerStateDidChange(_ player: SequencePlayer) {
switch player.state {
case .loading:
self.spinningThing.startAnimating()
default:
self.spinningThing.stopAnimating()
}
}
func sequencePlayerDidEnd(_ player: SequencePlayer) {
//Noop
}
//MARK: Player Data Source
func numberOfItemsInSequencePlayer(_ player: SequencePlayer) -> Int {
return self.urls.count
}
func sequencePlayer(_ player: SequencePlayer, itemURLAtIndex index: Int) -> URL {
return self.urls[index]
}
func sequencePlayerView(forSequencePlayer player: SequencePlayer) -> SequencePlayerView {
return self.playerView
}
}
| mit |
TedMore/FoodTracker | FoodTracker/MealViewController.swift | 1 | 4614 | //
// MealViewController.swift
// FoodTracker
//
// Created by TedChen on 10/15/15.
// Copyright © 2015 LEON. All rights reserved.
//
import UIKit
class MealViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var ratingControl: RatingControl!
@IBOutlet weak var saveButton: UIBarButtonItem!
/*
This value is either passed by `MealTableViewController` in `prepareForSegue(_:sender:)`
or constructed as part of adding a new meal.
*/
var meal: Meal?
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field’s user input through delegate callbacks.
nameTextField.delegate = self
// Set up views if editing an existing Meal.
if let meal = meal {
navigationItem.title = meal.name
nameTextField.text = meal.name
photoImageView.image = meal.photo
ratingControl.rating = meal.rating
}
// Enable the Save button only if the text field has a valid Meal name.
checkValidMealName()
}
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
// Dismiss the picker.
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: Navigation
// This method lets you configure a view controller before it's presented.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if saveButton === sender {
let name = nameTextField.text ?? ""
let photo = photoImageView.image
let rating = ratingControl.rating
// Set the meal to be passed to MealTableViewController after the unwind segue.
meal = Meal(name: name, photo: photo, rating: rating)
}
}
// MARK: Actions
@IBAction func cancel(sender: UIBarButtonItem) {
// Depending on style of presentation (modal or push presentation), this view controller needs to be dismissed in two different ways
let isPresentingInAddMealMode = presentingViewController is UINavigationController
if isPresentingInAddMealMode {
dismissViewControllerAnimated(true, completion: nil)
}
else {
navigationController!.popViewControllerAnimated(true)
}
}
@IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
// Hide the keyboard
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .PhotoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidBeginEditing(textField: UITextField) {
// Disable the Save button while editing.
saveButton.enabled = false
}
func checkValidMealName() {
// Disable the Save button if the text field is empty.
let txt = nameTextField.text ?? ""
saveButton.enabled = !txt.isEmpty
}
func textFieldDidEndEditing(textField: UITextField) {
checkValidMealName()
navigationItem.title = nameTextField.text
}
}
| apache-2.0 |
teambition/RefreshView | Sources/UIScrollView+Extension.swift | 2 | 2202 | //
// UIScrollView+Extension.swift
// RefreshDemo
//
// Created by ZouLiangming on 16/1/25.
// Copyright © 2016年 ZouLiangming. All rights reserved.
//
import UIKit
extension UIScrollView {
var insetTop: CGFloat {
get {
return self.contentInset.top
}
set(newValue) {
var inset = self.contentInset
inset.top = newValue
self.contentInset = inset
}
}
var insetBottom: CGFloat {
get {
return self.contentInset.bottom
}
set(newValue) {
var inset = self.contentInset
inset.bottom = newValue
self.contentInset = inset
}
}
var insetLeft: CGFloat {
get {
return self.contentInset.left
}
set(newValue) {
var inset = self.contentInset
inset.left = newValue
self.contentInset = inset
}
}
var insetRight: CGFloat {
get {
return self.contentInset.right
}
set(newValue) {
var inset = self.contentInset
inset.right = newValue
self.contentInset = inset
}
}
var offsetX: CGFloat {
get {
return self.contentOffset.x
}
set(newValue) {
var inset = self.contentOffset
inset.x = newValue
self.contentOffset = inset
}
}
var offsetY: CGFloat {
get {
return self.contentOffset.y
}
set(newValue) {
var inset = self.contentOffset
inset.y = newValue
self.contentOffset = inset
}
}
var contentWidth: CGFloat {
get {
return self.contentSize.width
}
set(newValue) {
var inset = self.contentSize
inset.width = newValue
self.contentSize = inset
}
}
var contentHeight: CGFloat {
get {
return self.contentSize.height
}
set(newValue) {
var inset = self.contentSize
inset.height = newValue
self.contentSize = inset
}
}
}
| mit |
SomeSimpleSolutions/MemorizeItForever | MemorizeItForeverCore/MemorizeItForeverCoreTests/ManagersTests/WordFlowsServiceTests.swift | 1 | 17913 | //
// WordFlowsTests.swift
// MemorizeItForeverCore
//
// Created by Hadi Zamani on 10/23/16.
// Copyright © 2016 SomeSimpleSolutions. All rights reserved.
//
import XCTest
import BaseLocalDataAccess
@testable import MemorizeItForeverCore
class WordFlowsTests: XCTestCase {
var wordFlowService: WordFlowServiceProtocol!
var wordDataAccess: WordDataAccessProtocol!
var wordInProgressDataAccess: WordInProgressDataAccessProtocol!
var wordHistoryDataAccess: WordHistoryDataAccessProtocol!
var setModel: SetModel!
override func setUp() {
super.setUp()
wordDataAccess = FakeWordDataAccess()
wordInProgressDataAccess = FakeWordInProgressDataAccess()
wordHistoryDataAccess = FakeWordHistoryDataAccess()
wordFlowService = WordFlowService(wordDataAccess: wordDataAccess, wordInProgressDataAccess: wordInProgressDataAccess, wordHistoryDataAccess: wordHistoryDataAccess)
setModel = SetModel()
setModel.setId = UUID()
setModel.name = "Default"
}
override func tearDown() {
wordDataAccess = nil
wordFlowService = nil
wordInProgressDataAccess = nil
wordHistoryDataAccess = nil
setModel = nil
super.tearDown()
}
func testPutWordInPreColumn(){
let word = newWordModel()
do{
try wordFlowService.putWordInPreColumn(word)
}
catch{
XCTFail("should save wordInProgress")
}
if let column = objc_getAssociatedObject(wordInProgressDataAccess, &columnKey) as? Int16{
XCTAssertEqual(column, 0 ,"shoud put word in 0 column")
}
else{
XCTFail("should save wordInProgress")
}
if let date = objc_getAssociatedObject(wordInProgressDataAccess, &dateKey) as? Date{
XCTAssertEqual(date.getDate()!.compare(Date().addingTimeInterval(24 * 60 * 60).getDate()!), ComparisonResult.orderedSame ,"shoud set tomorrow")
}
else{
XCTFail("should save wordInProgress")
}
if let wordId = objc_getAssociatedObject(wordInProgressDataAccess, &wordIdKey) as? UUID{
XCTAssertEqual(wordId, word.wordId ,"shoud set word in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
}
func testAnswerCorrectlyPreColumn(){
let word = newWordModel()
let wordInprogress = WordInProgressModel(word: word, date: Date().addingTimeInterval(1 * 24 * 60 * 60), column: 0, wordInProgressId: UUID())
wordFlowService.answerCorrectly(wordInprogress)
if let column = objc_getAssociatedObject(wordInProgressDataAccess, &columnKey) as? Int16{
XCTAssertEqual(column, 1 ,"shoud put word in 1 column")
}
else{
XCTFail("should save wordInProgress")
}
if let date = objc_getAssociatedObject(wordInProgressDataAccess, &dateKey) as? Date{
XCTAssertEqual(date.getDate()!.compare(Date().addingTimeInterval(2 * 24 * 60 * 60).getDate()!), ComparisonResult.orderedSame ,"shoud set 2 days later")
}
else{
XCTFail("should progress word")
}
if let wordId = objc_getAssociatedObject(wordInProgressDataAccess, &wordIdKey) as? UUID{
XCTAssertEqual(wordId, word.wordId ,"shoud word not changed in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
if let wordInProgressId = objc_getAssociatedObject(wordInProgressDataAccess, &wordIdInProgressKey) as? UUID{
XCTAssertEqual(wordInProgressId, wordInprogress.wordInProgressId ,"shoud wordInprogressId not changed in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
}
func testAnswerCorrectlyFirstColumn(){
let word = newWordModel()
let wordInprogress = WordInProgressModel(word: word, date: Date().addingTimeInterval(2 * 24 * 60 * 60), column: 1, wordInProgressId: UUID())
wordFlowService.answerCorrectly(wordInprogress)
if let column = objc_getAssociatedObject(wordInProgressDataAccess, &columnKey) as? Int16{
XCTAssertEqual(column, 2 ,"shoud put word in 2 column")
}
else{
XCTFail("should save wordInProgress")
}
if let date = objc_getAssociatedObject(wordInProgressDataAccess, &dateKey) as? Date{
XCTAssertEqual(date.getDate()!.compare(Date().addingTimeInterval(4 * 24 * 60 * 60).getDate()!), ComparisonResult.orderedSame ,"shoud set 4 days later")
}
else{
XCTFail("should progress word")
}
if let wordId = objc_getAssociatedObject(wordInProgressDataAccess, &wordIdKey) as? UUID{
XCTAssertEqual(wordId, word.wordId ,"shoud word not changed in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
if let wordInProgressId = objc_getAssociatedObject(wordInProgressDataAccess, &wordIdInProgressKey) as? UUID{
XCTAssertEqual(wordInProgressId, wordInprogress.wordInProgressId ,"shoud wordInprogressId not changed in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
}
func testAnswerCorrectlySecondColumn(){
let word = newWordModel()
let wordInprogress = WordInProgressModel(word: word, date: Date().addingTimeInterval(4 * 24 * 60 * 60), column: 2, wordInProgressId: UUID())
wordFlowService.answerCorrectly(wordInprogress)
if let column = objc_getAssociatedObject(wordInProgressDataAccess, &columnKey) as? Int16{
XCTAssertEqual(column, 3 ,"shoud put word in 3 column")
}
else{
XCTFail("should save wordInProgress")
}
if let date = objc_getAssociatedObject(wordInProgressDataAccess, &dateKey) as? Date{
XCTAssertEqual(date.getDate()!.compare(Date().addingTimeInterval(8 * 24 * 60 * 60).getDate()!), ComparisonResult.orderedSame ,"shoud set 8 days later")
}
else{
XCTFail("should progress word")
}
if let wordId = objc_getAssociatedObject(wordInProgressDataAccess, &wordIdKey) as? UUID{
XCTAssertEqual(wordId, word.wordId ,"shoud word not changed in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
if let wordInProgressId = objc_getAssociatedObject(wordInProgressDataAccess, &wordIdInProgressKey) as? UUID{
XCTAssertEqual(wordInProgressId, wordInprogress.wordInProgressId ,"shoud wordInprogressId not changed in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
}
func testAnswerCorrectlyThirdColumn(){
let word = newWordModel()
let wordInprogress = WordInProgressModel(word: word, date: Date().addingTimeInterval(8 * 24 * 60 * 60), column: 3, wordInProgressId: UUID())
wordFlowService.answerCorrectly(wordInprogress)
if let column = objc_getAssociatedObject(wordInProgressDataAccess, &columnKey) as? Int16{
XCTAssertEqual(column, 4 ,"shoud put word in 4 column")
}
else{
XCTFail("should save wordInProgress")
}
if let date = objc_getAssociatedObject(wordInProgressDataAccess, &dateKey) as? Date{
XCTAssertEqual(date.getDate()!.compare(Date().addingTimeInterval(16 * 24 * 60 * 60).getDate()!), ComparisonResult.orderedSame ,"shoud set 8 days later")
}
else{
XCTFail("should progress word")
}
if let wordId = objc_getAssociatedObject(wordInProgressDataAccess, &wordIdKey) as? UUID{
XCTAssertEqual(wordId, word.wordId ,"shoud word not changed in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
if let wordInProgressId = objc_getAssociatedObject(wordInProgressDataAccess, &wordIdInProgressKey) as? UUID{
XCTAssertEqual(wordInProgressId, wordInprogress.wordInProgressId ,"shoud wordInprogressId not changed in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
}
func testAnswerCorrectlyFourthColumn(){
let word = newWordModel()
let wordInprogress = WordInProgressModel(word: word, date: Date().addingTimeInterval(16 * 24 * 60 * 60), column: 4, wordInProgressId: UUID())
wordFlowService.answerCorrectly(wordInprogress)
if let column = objc_getAssociatedObject(wordInProgressDataAccess, &columnKey) as? Int16{
XCTAssertEqual(column, 5 ,"shoud put word in 5 column")
}
else{
XCTFail("should save wordInProgress")
}
if let date = objc_getAssociatedObject(wordInProgressDataAccess, &dateKey) as? Date{
XCTAssertEqual(date.getDate()!.compare(Date().addingTimeInterval(32 * 24 * 60 * 60).getDate()!), ComparisonResult.orderedSame ,"shoud set 8 days later")
}
else{
XCTFail("should progress word")
}
if let wordId = objc_getAssociatedObject(wordInProgressDataAccess, &wordIdKey) as? UUID{
XCTAssertEqual(wordId, word.wordId ,"shoud word not changed in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
if let wordInProgressId = objc_getAssociatedObject(wordInProgressDataAccess, &wordIdInProgressKey) as? UUID{
XCTAssertEqual(wordInProgressId, wordInprogress.wordInProgressId ,"shoud wordInprogressId not changed in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
}
func testAnswerCorrectlyFifthColumn(){
let word = newWordModel()
let wordInprogress = WordInProgressModel(word: word, date: Date().addingTimeInterval(32 * 24 * 60 * 60), column: 5, wordInProgressId: UUID())
wordFlowService.answerCorrectly(wordInprogress)
if let status = objc_getAssociatedObject(wordDataAccess, &statusKey) as? Int16{
XCTAssertEqual(status, WordStatus.done.rawValue ,"shoud set word status as Done")
}
else{
XCTFail("shoud set word status as Done")
}
if let enumResult = objc_getAssociatedObject(wordInProgressDataAccess, &resultKey) as? FakeWordInProgressDataAccessEnum{
XCTAssertEqual(enumResult, .delete ,"should delete wordInProgress")
}
else{
XCTFail("should delete wordInProgress")
}
}
func testAnswerWronglyInMiddleColumns(){
let word = newWordModel()
let wordInprogress = WordInProgressModel(word: word, date: Date().addingTimeInterval(8 * 24 * 60 * 60), column: 3, wordInProgressId: UUID())
wordFlowService.answerWrongly(wordInprogress)
if let columnNO = objc_getAssociatedObject(wordHistoryDataAccess, &columnNoKey) as? Int16{
XCTAssertEqual(columnNO, 3 ,"shoud set correct column No")
}
else{
XCTFail("should save wordInProgress")
}
if let wordId = objc_getAssociatedObject(wordHistoryDataAccess, &wordIdKey) as? UUID{
XCTAssertEqual(wordId, word.wordId ,"shoud word not changed in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
if let date = objc_getAssociatedObject(wordInProgressDataAccess, &dateKey) as? Date{
XCTAssertEqual(date.getDate()!.compare(Date().addingTimeInterval(1 * 24 * 60 * 60).getDate()!), ComparisonResult.orderedSame ,"shoud set 1 days later")
}
else{
XCTFail("should progress word")
}
if let column = objc_getAssociatedObject(wordInProgressDataAccess, &columnKey) as? Int16{
XCTAssertEqual(column, 0 ,"shoud put word in 0 column")
}
else{
XCTFail("should save wordInProgress")
}
}
func testAddDayExtension(){
let now = Date(timeIntervalSinceReferenceDate: 0)
let tomorrow = Date(timeIntervalSinceReferenceDate: 60*60*24)
XCTAssertEqual(now.addDay(1), tomorrow, "AddDay extension should work fine")
}
func testFetchWordsForPuttingInPreColumn(){
UserDefaults.standard.setValue(10, forKey: Settings.newWordsCount.rawValue)
UserDefaults.standard.setValue(setModel.toDic(), forKey: Settings.defaultSet.rawValue)
do{
try wordFlowService.fetchNewWordsToPutInPreColumn()
}
catch{
XCTFail("should be able to fetch words in pre column")
}
if let column = objc_getAssociatedObject(wordInProgressDataAccess, &columnKey) as? Int16{
XCTAssertEqual(column, 0 ,"shoud put word in 0 column")
}
else{
XCTFail("should save wordInProgress")
}
if let date = objc_getAssociatedObject(wordInProgressDataAccess, &dateKey) as? Date{
XCTAssertEqual(date.getDate()!.compare(Date().addingTimeInterval(24 * 60 * 60).getDate()!), ComparisonResult.orderedSame ,"shoud set tomorrow")
}
else{
XCTFail("should save wordInProgress")
}
if let wordId = objc_getAssociatedObject(wordInProgressDataAccess, &wordIdKey) as? UUID{
XCTAssertNotNil(wordId ,"shoud set word in wordInprogress")
}
else{
XCTFail("should save wordInProgress")
}
if let status = objc_getAssociatedObject(wordDataAccess, &statusKey) as? Int16{
XCTAssertEqual(status, WordStatus.inProgress.rawValue ,"shoud status word set to InProgress")
}
else{
XCTFail("shou set word status as InProgress")
}
}
func testDoNotFetchWordsForPuttingInPreColumnIfAlreadyFetched(){
UserDefaults.standard.setValue(setModel.toDic(), forKey: Settings.defaultSet.rawValue)
let word = newWordModel()
objc_setAssociatedObject(wordDataAccess, &wordKey, word, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
do{
try wordFlowService.fetchNewWordsToPutInPreColumn()
}
catch{
XCTFail("should be able to fetch words in pre column")
}
let column = objc_getAssociatedObject(wordInProgressDataAccess, &columnKey) as? Int16
XCTAssertNil(column, "Should not put progress in column 0")
}
func testShouldWordsForPuttingInPreColumnIfAnsweredAlreadyWrongly(){
UserDefaults.standard.setValue(setModel.toDic(), forKey: Settings.defaultSet.rawValue)
let word = newWordModel()
objc_setAssociatedObject(wordDataAccess, &wordKey, word, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_setAssociatedObject(wordHistoryDataAccess, &wordHistoryCountKey, 1, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
do{
try wordFlowService.fetchNewWordsToPutInPreColumn()
}
catch{
XCTFail("should be able to fetch words in pre column")
}
if let column = objc_getAssociatedObject(wordInProgressDataAccess, &columnKey) as? Int16{
XCTAssertEqual(column, 0 ,"shoud put word in 0 column")
}
else{
XCTFail("should save wordInProgress")
}
}
func testFetchWordsForReview(){
UserDefaults.standard.setValue(setModel.toDic(), forKey: Settings.defaultSet.rawValue)
do{
let words = try wordFlowService.fetchWordsForReview()
XCTAssertGreaterThanOrEqual(words.count, 0, "should return words for review")
}
catch{
XCTFail("Should be able to fetch words for review")
}
if let column = objc_getAssociatedObject(wordInProgressDataAccess, &columnKey) as? Int16{
XCTAssertEqual(column, 0 ,"shoud filter with 0 column")
}
else{
XCTFail("shoud filter with 0 column")
}
if let date = objc_getAssociatedObject(wordInProgressDataAccess, &dateKey) as? Date{
XCTAssertEqual(date.getDate()!.compare(Date().addingTimeInterval(24 * 60 * 60).getDate()!), ComparisonResult.orderedSame ,"shoud filter with tomorrow date")
}
else{
XCTFail("shoud filter with tomorrow date")
}
}
func testFetchWordsToExamine(){
// it should fetch words for today and all words that belongs to past
UserDefaults.standard.setValue(setModel.toDic(), forKey: Settings.defaultSet.rawValue)
do{
let wordInProgressLists = try wordFlowService.fetchWordsToExamin()
XCTAssertEqual(wordInProgressLists[0].column, 3,"should sort wordInprogress list")
}
catch{
XCTFail("Should be able to fetch words for examin")
}
if let date = objc_getAssociatedObject(wordInProgressDataAccess, &dateKey) as? Date{
XCTAssertEqual(date.getDate()!.compare(Date().getDate()!), ComparisonResult.orderedSame ,"shoud filter with today date")
}
else{
XCTFail("shoud filter with today date")
}
}
private func newWordModel() -> WordModel{
var wordModel = WordModel()
wordModel.wordId = UUID()
wordModel.phrase = "Livre"
wordModel.meaning = "Book"
wordModel.order = 1
wordModel.setId = UUID()
wordModel.status = WordStatus.notStarted.rawValue
return wordModel
}
}
| mit |
roambotics/swift | test/stdlib/Bundle.swift | 2 | 776 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
import StdlibUnittest
var BundleTests = TestSuite("BundleTests")
BundleTests.test("Bundle.bundleForNilClass") {
// Ensure that bundleForClass: tolerates a nil parameter. The
// Foundation implementation does. The patched version from
// ObjCRuntimeGetImageNameFromClass did not.
//
// https://github.com/apple/swift/issues/51679
typealias BundleForClassFunc =
@convention(c) (AnyObject, Selector, AnyObject?) -> Bundle
let sel = #selector(Bundle.init(for:))
let imp = unsafeBitCast(Bundle.method(for: sel), to: BundleForClassFunc.self)
let bundleForNil = imp(Bundle.self, sel, nil);
expectEqual(Bundle.main, bundleForNil)
}
runAllTests()
| apache-2.0 |
alexhillc/AXPhotoViewer | Source/Integrations/SimpleNetworkIntegration.swift | 1 | 7546 | //
// SimpleNetworkIntegration.swift
// AXPhotoViewer
//
// Created by Alex Hill on 6/11/17.
// Copyright © 2017 Alex Hill. All rights reserved.
//
open class SimpleNetworkIntegration: NSObject, AXNetworkIntegrationProtocol, SimpleNetworkIntegrationURLSessionWrapperDelegate {
fileprivate var urlSessionWrapper = SimpleNetworkIntegrationURLSessionWrapper()
public weak var delegate: AXNetworkIntegrationDelegate?
fileprivate var dataTasks = NSMapTable<AXPhotoProtocol, URLSessionDataTask>(keyOptions: .strongMemory, valueOptions: .strongMemory)
fileprivate var photos = [Int: AXPhotoProtocol]()
public override init() {
super.init()
self.urlSessionWrapper.delegate = self
}
deinit {
self.urlSessionWrapper.invalidate()
}
public func loadPhoto(_ photo: AXPhotoProtocol) {
if photo.imageData != nil || photo.image != nil {
AXDispatchUtils.executeInBackground { [weak self] in
guard let `self` = self else { return }
self.delegate?.networkIntegration(self, loadDidFinishWith: photo)
}
return
}
guard let url = photo.url else { return }
let dataTask = self.urlSessionWrapper.dataTask(with: url)
self.dataTasks.setObject(dataTask, forKey: photo)
self.photos[dataTask.taskIdentifier] = photo
dataTask.resume()
}
public func cancelLoad(for photo: AXPhotoProtocol) {
guard let dataTask = self.dataTasks.object(forKey: photo) else { return }
dataTask.cancel()
}
public func cancelAllLoads() {
let enumerator = self.dataTasks.objectEnumerator()
while let dataTask = enumerator?.nextObject() as? URLSessionDataTask {
dataTask.cancel()
}
self.dataTasks.removeAllObjects()
self.photos.removeAll()
}
// MARK: - SimpleNetworkIntegrationURLSessionWrapperDelegate
fileprivate func urlSessionWrapper(_ urlSessionWrapper: SimpleNetworkIntegrationURLSessionWrapper,
dataTask: URLSessionDataTask,
didUpdateProgress progress: CGFloat) {
guard let photo = self.photos[dataTask.taskIdentifier] else { return }
AXDispatchUtils.executeInBackground { [weak self] in
guard let `self` = self else { return }
self.delegate?.networkIntegration?(self,
didUpdateLoadingProgress: progress,
for: photo)
}
}
fileprivate func urlSessionWrapper(_ urlSessionWrapper: SimpleNetworkIntegrationURLSessionWrapper,
task: URLSessionTask,
didCompleteWithError error: Error?,
object: Any?) {
guard let photo = self.photos[task.taskIdentifier] else { return }
weak var weakSelf = self
func removeDataTask() {
weakSelf?.photos.removeValue(forKey: task.taskIdentifier)
weakSelf?.dataTasks.removeObject(forKey: photo)
}
if let error = error {
removeDataTask()
AXDispatchUtils.executeInBackground { [weak self] in
guard let `self` = self else { return }
self.delegate?.networkIntegration(self, loadDidFailWith: error, for: photo)
}
return
}
guard let data = object as? Data else { return }
if data.containsGIF() {
photo.imageData = data
} else {
photo.image = UIImage(data: data)
}
removeDataTask()
AXDispatchUtils.executeInBackground { [weak self] in
guard let `self` = self else { return }
self.delegate?.networkIntegration(self, loadDidFinishWith: photo)
}
}
}
// This wrapper abstracts the `URLSession` away from `SimpleNetworkIntegration` in order to prevent a retain cycle
// between the `URLSession` and its delegate
fileprivate class SimpleNetworkIntegrationURLSessionWrapper: NSObject, URLSessionDataDelegate, URLSessionTaskDelegate {
weak var delegate: SimpleNetworkIntegrationURLSessionWrapperDelegate?
fileprivate var urlSession: URLSession!
fileprivate var receivedData = [Int: Data]()
fileprivate var receivedContentLength = [Int: Int64]()
override init() {
super.init()
self.urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
}
func dataTask(with url: URL) -> URLSessionDataTask {
return self.urlSession.dataTask(with: url)
}
func invalidate() {
self.urlSession.invalidateAndCancel()
}
// MARK: - URLSessionDataDelegate
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
self.receivedData[dataTask.taskIdentifier]?.append(data)
guard let receivedData = self.receivedData[dataTask.taskIdentifier],
let expectedContentLength = self.receivedContentLength[dataTask.taskIdentifier] else {
return
}
self.delegate?.urlSessionWrapper(self,
dataTask: dataTask,
didUpdateProgress: CGFloat(receivedData.count) / CGFloat(expectedContentLength))
}
func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
self.receivedContentLength[dataTask.taskIdentifier] = response.expectedContentLength
self.receivedData[dataTask.taskIdentifier] = Data()
completionHandler(.allow)
}
// MARK: - URLSessionTaskDelegate
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
weak var weakSelf = self
func removeData() {
weakSelf?.receivedData.removeValue(forKey: task.taskIdentifier)
weakSelf?.receivedContentLength.removeValue(forKey: task.taskIdentifier)
}
if let error = error {
self.delegate?.urlSessionWrapper(self, task: task, didCompleteWithError: error, object: nil)
removeData()
return
}
guard let data = self.receivedData[task.taskIdentifier] else {
self.delegate?.urlSessionWrapper(self, task: task, didCompleteWithError: nil, object: nil)
removeData()
return
}
self.delegate?.urlSessionWrapper(self, task: task, didCompleteWithError: nil, object: data)
removeData()
}
}
fileprivate protocol SimpleNetworkIntegrationURLSessionWrapperDelegate: NSObjectProtocol, AnyObject {
func urlSessionWrapper(_ urlSessionWrapper: SimpleNetworkIntegrationURLSessionWrapper,
dataTask: URLSessionDataTask,
didUpdateProgress progress: CGFloat)
func urlSessionWrapper(_ urlSessionWrapper: SimpleNetworkIntegrationURLSessionWrapper,
task: URLSessionTask,
didCompleteWithError error: Error?,
object: Any?)
}
| mit |
Nirma/UIFontComplete | Sources/UIFont+Extension.swift | 1 | 2115 | // UIFont+Extension.swift
// Copyright (c) 2016-2019 Nicholas Maccharoli
//
// 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
extension UIFont {
/// Create a UIFont object with a `Font` enum
public convenience init?(font: BuiltInFont, size: CGFloat) {
let fontIdentifier: String = font.rawValue
self.init(name: fontIdentifier, size: size)
}
/// Creates a scaleable `UIFont` from a given `BuiltInFont`.
///
/// Make sure that labels using this scaleable font have `adjustsFontForContentSizeCategory` set to `true`.
/// - Parameters:
/// - font: The font to use.
/// - textStyle: The text style to use.
/// - Returns: A scaleable font object.
@available(iOS 11.0, *)
public static func scaled(font: BuiltInFont, textStyle: UIFont.TextStyle = .body) -> UIFont? {
let defaultSize = UIFont.preferredFont(forTextStyle: textStyle).pointSize
guard let font = UIFont(font: font, size: defaultSize) else { return nil }
return UIFontMetrics(forTextStyle: textStyle).scaledFont(for: font)
}
}
| mit |
JBerkvens/SmartMobile-iOS-2016 | Practica/json_test/json_test/Pirate.swift | 1 | 535 | //
// Pirate.swift
// json_test
//
// Created by Jeroen Berkvens on 06/04/16.
// Copyright © 2016 Fontys Universities. All rights reserved.
//
import Foundation
class Pirate {
let name:String!;
var yearsActive:Int?;
var notes:String?;
init (name:String) {
self.name = name;
}
func getInfo()->String {
let yearsActive:Int! = self.yearsActive;
let notes:String! = self.notes;
return "Name:\t\t\t\(name)\nYears Active:\t\(yearsActive)\nNotes:\t\t\t\(notes)";
}
} | gpl-3.0 |
collegboi/MBaaSKit | MBaaSKit/Classes/Protocols/LabelLoad.swift | 1 | 3073 | //
// LabelLoad.swift
// Remote Config
//
// Created by Timothy Barnard on 23/10/2016.
// Copyright © 2016 Timothy Barnard. All rights reserved.
//
import UIKit
public protocol LabelLoad {}
public extension LabelLoad where Self: UILabel {
public func setupLabelView( className: UIViewController, name: String = "") {
self.setup(className: String(describing: type(of: className)), tagValue: name)
}
public func setupLabelView( className: UIView, name: String = "") {
self.setup(className: String(describing: type(of: className)), tagValue: name)
}
private func setup( className: String, tagValue : String ) {
var viewName = tagValue
if tagValue.isEmpty {
viewName = String(self.tag)
}
let dict = RCConfigManager.getObjectProperties(className: className, objectName: viewName)
var fontName: String = ""
var size : CGFloat = 0.0
for (key, value) in dict {
switch key {
case "text" where dict.tryConvert(forKey: key) != "":
self.text = RCConfigManager.getTranslation(name: viewName)
break
case "textAlignment" where dict.tryConvert(forKey: key) != "":
self.textAlignment = NSTextAlignment(rawValue: (value as! Int))!
case "backgroundColor" where dict.tryConvert(forKey: key) != "":
self.backgroundColor = RCConfigManager.getColor(name: (value as! String), defaultColor: .white)
break
case "font" where dict.tryConvert(forKey: key) != "":
fontName = (value as! String)
break
case "fontSize" where dict.tryConvert(forKey: key) != "":
size = value as! CGFloat
break
case "textColor" where dict.tryConvert(forKey: key) != "":
self.textColor = RCConfigManager.getColor(name: (value as! String), defaultColor: .black)
break
case "isEnabled" where dict.tryConvert(forKey: key) != "":
self.isEnabled = ((value as! Int) == 1) ? true : false
break
case "isHidden" where dict.tryConvert(forKey: key) != "":
self.isHidden = ((value as! Int) == 1) ? true : false
break
case "isUserInteractionEnabled" where dict.tryConvert(forKey: key) != "":
self.isUserInteractionEnabled = ((value as! Int) == 1) ? true : false
break
default: break
}
}
if !fontName.isEmpty && size != 0.0 {
self.font = UIFont(name: fontName, size: size)
}
}
func readFromJSON() -> UIColor {
//print("readFromJSON")
//print(MyFileManager.readJSONFile(parseKey: "maps", keyVal: "id"))
let defaultColor = UIColor(red: 38/255, green: 154/255, blue: 208/255, alpha: 1)
return RCConfigManager.getColor(name: "navColor", defaultColor: defaultColor)
}
}
| mit |
iOSDevLog/iOSDevLog | 228. NestedXib/228. NestedXib/ViewController.swift | 1 | 515 | //
// ViewController.swift
// 228. NestedXib
//
// Created by iOS Dev Log on 2017/12/19.
// Copyright © 2017年 iOSDevLog. 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 |
softdevstory/yata | yata/Sources/ViewControllers/MainSplitViewController.swift | 1 | 2920 | //
// MainSplitViewController.swift
// yata
//
// Created by HS Song on 2017. 7. 14..
// Copyright © 2017년 HS Song. All rights reserved.
//
import AppKit
class MainSplitViewController: NSSplitViewController {
@IBOutlet weak var pageListSplitViewItem: NSSplitViewItem!
@IBOutlet weak var pageEditSplitViewItem: NSSplitViewItem!
override func viewDidLoad() {
super.viewDidLoad()
}
override func toggleSidebar(_ sender: Any?) {
guard let menuItem = sender as? NSMenuItem else {
return
}
super.toggleSidebar(sender)
if pageListSplitViewItem.isCollapsed {
menuItem.title = "Show Sidebar".localized
} else {
menuItem.title = "Hide Sidebar".localized
}
}
}
// MARK: support menu, toolbar
extension MainSplitViewController {
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
guard let tag = MenuTag(rawValue: menuItem.tag) else {
return false
}
switch tag {
case .fileNewPage, .fileReload:
break
case .fileOpenInWebBrowser:
if let vc = pageListSplitViewItem.viewController as? PageListViewController {
return vc.isSelected()
}
case .viewToggleSideBar:
if pageListSplitViewItem.isCollapsed {
menuItem.title = "Show Sidebar".localized
} else {
menuItem.title = "Hide Sidebar".localized
}
default:
return false
}
return true
}
override func validateToolbarItem(_ item: NSToolbarItem) -> Bool {
guard let tag = ToolbarTag(rawValue: item.tag) else {
return false
}
guard let _ = AccessTokenStorage.loadAccessToken() else {
return false
}
switch tag {
case .newPage, .reloadPageList:
return true
case .viewInWebBrowser:
if let vc = pageListSplitViewItem.viewController as? PageListViewController {
return vc.isSelected()
}
default:
return false
}
return true
}
@IBAction func reloadPageList(_ sender: Any?) {
if let vc = pageListSplitViewItem.viewController as? PageListViewController {
vc.reloadList(sender)
}
}
@IBAction func editNewPage(_ sender: Any?) {
if let vc = pageListSplitViewItem.viewController as? PageListViewController {
vc.editNewPage(sender)
}
}
@IBAction func viewInWebBrowser(_ sender: Any?) {
if let vc = pageListSplitViewItem.viewController as? PageListViewController {
vc.openInWebBrowser(sender)
}
}
}
| mit |
michaelarmstrong/SuperRecord | SuperRecordDemo/SuperRecordDemo/Entity/Pokemon+CoreDataProperties.swift | 2 | 494 | //
// Pokemon+CoreDataProperties.swift
// SuperRecordDemo
//
// Created by Piergiuseppe Longo on 23/10/15.
// Copyright © 2015 SuperRecord. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension Pokemon {
@NSManaged var name: String
@NSManaged var national_id: Int16
@NSManaged var types: Set<Type>
}
| mit |
neoreeps/rest-tester | REST Tester/AppDelegate.swift | 1 | 4615 | //
// AppDelegate.swift
// REST Tester
//
// Created by Kenny Speer on 10/3/16.
// Copyright © 2016 Kenny Speer. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Model")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| apache-2.0 |
airspeedswift/swift | test/Constraints/optional.swift | 3 | 13739 | // RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
func markUsed<T>(_ t: T) {}
class A {
@objc func do_a() {}
@objc(do_b_2:) func do_b(_ x: Int) {}
@objc func do_b(_ x: Float) {}
@objc func do_c(x: Int) {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(x:)')}}
@objc func do_c(y: Int) {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(y:)')}}
}
func test0(_ a: AnyObject) {
a.do_a?()
a.do_b?(1)
a.do_b?(5.0)
a.do_c?(1) // expected-error {{no exact matches in call to instance method 'do_c'}}
a.do_c?(x: 1)
}
func test1(_ a: A) {
a?.do_a() // expected-error {{cannot use optional chaining on non-optional value of type 'A'}} {{4-5=}}
a!.do_a() // expected-error {{cannot force unwrap value of non-optional type 'A'}} {{4-5=}}
// Produce a specialized diagnostic here?
a.do_a?() // expected-error {{cannot use optional chaining on non-optional value of type '() -> ()'}} {{9-10=}}
}
// <rdar://problem/15508756>
extension Optional {
func bind<U>(_ f: (Wrapped) -> U?) -> U? {
switch self {
case .some(let x):
return f(x)
case .none:
return .none
}
}
}
var c: String? = Optional<Int>(1)
.bind {(x: Int) in markUsed("\(x)!"); return "two" }
func test4() {
func foo() -> Int { return 0 }
func takes_optfn(_ f : () -> Int?) -> Int? { return f() }
_ = takes_optfn(foo)
func takes_objoptfn(_ f : () -> AnyObject?) -> AnyObject? { return f() }
func objFoo() -> AnyObject { return A() }
_ = takes_objoptfn(objFoo) // okay
func objBar() -> A { return A() }
_ = takes_objoptfn(objBar) // okay
}
func test5() -> Int? {
return nil
}
func test6<T>(_ x : T) {
// FIXME: this code should work; T could be Int? or Int??
// or something like that at runtime. rdar://16374053
_ = x as? Int? // expected-error {{cannot downcast from 'T' to a more optional type 'Int?'}}
}
class B : A { }
func test7(_ x : A) {
_ = x as? B? // expected-error{{cannot downcast from 'A' to a more optional type 'B?'}}
}
func test8(_ x : AnyObject?) {
let _ : A = x as! A
}
// Partial ordering with optionals
func test9_helper<T: P>(_ x: T) -> Int { }
func test9_helper<T: P>(_ x: T?) -> Double { }
func test9_helper2<T>(_ x: T) -> Int { }
func test9_helper2<T>(_ x: T?) -> Double { }
func test9(_ i: Int, io: Int?) {
let result = test9_helper(i)
var _: Int = result
let result2 = test9_helper(io)
let _: Double = result2
let result3 = test9_helper2(i)
var _: Int = result3
let result4 = test9_helper2(io)
let _: Double = result4
}
protocol P { }
func test10_helper<T : P>(_ x: T) -> Int { }
func test10_helper<T : P>(_ x: T?) -> Double { }
extension Int : P { }
func test10(_ i: Int, io: Int?) {
let result = test10_helper(i)
var _: Int = result
let result2 = test10_helper(io)
var _: Double = result2
}
var z: Int? = nil
z = z ?? 3
var fo: Float? = 3.14159
func voidOptional(_ handler: () -> ()?) {}
func testVoidOptional() {
let noop: () -> Void = {}
voidOptional(noop)
let optNoop: (()?) -> ()? = { return $0 }
voidOptional(optNoop)
}
protocol Proto1 {}
protocol Proto2 {}
struct Nilable: ExpressibleByNilLiteral {
init(nilLiteral: ()) {}
}
func testTernaryWithNil<T>(b: Bool, s: String, i: Int, a: Any, t: T, m: T.Type, p: Proto1 & Proto2, arr: [Int], opt: Int?, iou: Int!, n: Nilable) {
let t1 = b ? s : nil
let _: Double = t1 // expected-error{{value of type 'String?'}}
let t2 = b ? nil : i
let _: Double = t2 // expected-error{{value of type 'Int?'}}
let t3 = b ? "hello" : nil
let _: Double = t3 // expected-error{{value of type 'String?'}}
let t4 = b ? nil : 1
let _: Double = t4 // expected-error{{value of type 'Int?'}}
let t5 = b ? (s, i) : nil
let _: Double = t5 // expected-error{{value of type '(String, Int)?}}
let t6 = b ? nil : (i, s)
let _: Double = t6 // expected-error{{value of type '(Int, String)?}}
let t7 = b ? ("hello", 1) : nil
let _: Double = t7 // expected-error{{value of type '(String, Int)?}}
let t8 = b ? nil : (1, "hello")
let _: Double = t8 // expected-error{{value of type '(Int, String)?}}
let t9 = b ? { $0 * 2 } : nil
let _: Double = t9 // expected-error{{value of type '((Int) -> Int)?}}
let t10 = b ? nil : { $0 * 2 }
let _: Double = t10 // expected-error{{value of type '((Int) -> Int)?}}
let t11 = b ? a : nil
let _: Double = t11 // expected-error{{value of type 'Any?'}}
let t12 = b ? nil : a
let _: Double = t12 // expected-error{{value of type 'Any?'}}
let t13 = b ? t : nil
let _: Double = t13 // expected-error{{value of type 'T?'}}
let t14 = b ? nil : t
let _: Double = t14 // expected-error{{value of type 'T?'}}
let t15 = b ? m : nil
let _: Double = t15 // expected-error{{value of type 'T.Type?'}}
let t16 = b ? nil : m
let _: Double = t16 // expected-error{{value of type 'T.Type?'}}
let t17 = b ? p : nil
let _: Double = t17 // expected-error{{value of type '(Proto1 & Proto2)?'}}
let t18 = b ? nil : p
let _: Double = t18 // expected-error{{value of type '(Proto1 & Proto2)?'}}
let t19 = b ? arr : nil
let _: Double = t19 // expected-error{{value of type '[Int]?'}}
let t20 = b ? nil : arr
let _: Double = t20 // expected-error{{value of type '[Int]?'}}
let t21 = b ? opt : nil
let _: Double = t21 // expected-error{{value of type 'Int?'}}
let t22 = b ? nil : opt
let _: Double = t22 // expected-error{{value of type 'Int?'}}
let t23 = b ? iou : nil
let _: Double = t23 // expected-error{{value of type 'Int?'}}
let t24 = b ? nil : iou
let _: Double = t24 // expected-error{{value of type 'Int?'}}
let t25 = b ? n : nil
let _: Double = t25 // expected-error{{value of type 'Nilable'}}
let t26 = b ? nil : n
let _: Double = t26 // expected-error{{value of type 'Nilable'}}
}
// inference with IUOs
infix operator ++++
protocol PPPP {
static func ++++(x: Self, y: Self) -> Bool
}
func compare<T: PPPP>(v: T, u: T!) -> Bool {
return v ++++ u
}
func sr2752(x: String?, y: String?) {
_ = x.map { xx in
y.map { _ in "" } ?? "\(xx)"
}
}
// SR-3248 - Invalid diagnostic calling implicitly unwrapped closure
var sr3248 : ((Int) -> ())!
sr3248?(a: 2) // expected-error {{extraneous argument label 'a:' in call}}
sr3248!(a: 2) // expected-error {{extraneous argument label 'a:' in call}}
sr3248(a: 2) // expected-error {{extraneous argument label 'a:' in call}}
struct SR_3248 {
var callback: (([AnyObject]) -> Void)!
}
SR_3248().callback?("test") // expected-error {{cannot convert value of type 'String' to expected argument type '[AnyObject]'}}
SR_3248().callback!("test") // expected-error {{cannot convert value of type 'String' to expected argument type '[AnyObject]'}}
SR_3248().callback("test") // expected-error {{cannot convert value of type 'String' to expected argument type '[AnyObject]'}}
_? = nil // expected-error {{'nil' requires a contextual type}}
_?? = nil // expected-error {{'nil' requires a contextual type}}
// rdar://problem/29993596
func takeAnyObjects(_ lhs: AnyObject?, _ rhs: AnyObject?) { }
infix operator !====
func !====(_ lhs: AnyObject?, _ rhs: AnyObject?) -> Bool { return false }
func testAnyObjectImplicitForce(lhs: AnyObject?!, rhs: AnyObject?) {
if lhs !==== rhs { }
takeAnyObjects(lhs, rhs)
}
// SR-4056
protocol P1 { }
class C1: P1 { }
protocol P2 {
var prop: C1? { get }
}
class C2 {
var p1: P1?
var p2: P2?
var computed: P1? {
return p1 ?? p2?.prop
}
}
// rdar://problem/31779785
class X { }
class Bar {
let xOpt: X?
let b: Bool
init() {
let result = b ? nil : xOpt
let _: Int = result // expected-error{{cannot convert value of type 'X?' to specified type 'Int'}}
}
}
// rdar://problem/37508855
func rdar37508855(_ e1: X?, _ e2: X?) -> [X] {
return [e1, e2].filter { $0 == nil }.map { $0! }
}
func se0213() {
struct Q: ExpressibleByStringLiteral {
typealias StringLiteralType = String
var foo: String
init?(_ possibleQ: StringLiteralType) {
return nil
}
init(stringLiteral str: StringLiteralType) {
self.foo = str
}
}
_ = Q("why")?.foo // Ok
_ = Q("who")!.foo // Ok
_ = Q?("how") // Ok
}
func rdar45218255(_ i: Int) {
struct S<T> {
init(_:[T]) {}
}
_ = i! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{8-9=}}
_ = [i!] // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{9-10=}}
_ = S<Int>([i!]) // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{16-17=}}
}
// rdar://problem/47967277 - cannot assign through '!': '$0' is immutable
func sr_9893_1() {
func foo<T : Equatable>(_: @autoclosure () throws -> T,
_: @autoclosure () throws -> T) {}
class A {
var bar: String?
}
let r1 = A()
let r2 = A()
let arr1: [A] = []
foo(Set(arr1.map { $0.bar! }), Set([r1, r2].map { $0.bar! })) // Ok
}
func sr_9893_2(cString: UnsafePointer<CChar>) {
struct S {
var a: Int32 = 0
var b = ContiguousArray<CChar>(repeating: 0, count: 10)
}
var s = S()
withUnsafeMutablePointer(to: &s.a) { ptrA in
s.b.withUnsafeMutableBufferPointer { bufferB in
withVaList([ptrA, bufferB.baseAddress!]) { ptr in } // Ok
}
}
}
// rdar://problem/47776586 - Diagnostic refers to '&' which is not present in the source code
func rdar47776586() {
func foo(_: inout Int) {}
var x: Int? = 0
foo(&x) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{7-7=(}} {{9-9=)!}}
var dict = [1: 2]
dict[1] += 1 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{10-10=!}}
}
struct S {
var foo: Optional<() -> Int?> = nil
var bar: Optional<() -> Int?> = nil
mutating func test(_ clj: @escaping () -> Int) {
if let fn = foo {
bar = fn // Ok
bar = clj // Ok
}
}
}
// rdar://problem/53238058 - Crash in getCalleeLocator while trying to produce a diagnostic about missing optional unwrap
// associated with an argument to a call
func rdar_53238058() {
struct S {
init(_: Double) {}
init<T>(_ value: T) where T : BinaryFloatingPoint {}
}
func test(_ str: String) {
_ = S(Double(str)) // expected-error {{value of optional type 'Double?' must be unwrapped to a value of type 'Double'}}
// expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
}
// SR-8411 - Inconsistent ambiguity with optional and non-optional inout-to-pointer
func sr8411() {
struct S {
init(_ x: UnsafeMutablePointer<Int>) {}
init(_ x: UnsafeMutablePointer<Int>?) {}
static func foo(_ x: UnsafeMutablePointer<Int>) {}
static func foo(_ x: UnsafeMutablePointer<Int>?) {}
static func bar(_ x: UnsafeMutablePointer<Int>, _ y: Int) {}
static func bar(_ x: UnsafeMutablePointer<Int>?, _ y: Int) {}
}
var foo = 0
_ = S(&foo) // Ok
_ = S.init(&foo) // Ok
S.foo(&foo) // Ok
S.bar(&foo, 42) // Ok
}
// SR-11104 - Slightly misleading diagnostics for contextual failures with multiple fixes
func sr_11104() {
func bar(_: Int) {}
bar(["hello"].first)
// expected-error@-1 {{cannot convert value of type 'String?' to expected argument type 'Int'}}
}
// rdar://problem/57668873 - Too eager force optional unwrap fix
@objc class Window {}
@objc protocol WindowDelegate {
@objc optional var window: Window? { get set }
}
func test_force_unwrap_not_being_too_eager() {
struct WindowContainer {
unowned(unsafe) var delegate: WindowDelegate? = nil
}
let obj: WindowContainer = WindowContainer()
if let _ = obj.delegate?.window { // Ok
}
}
// rdar://problem/57097401
func invalidOptionalChaining(a: Any) {
a == "="? // expected-error {{binary operator '==' cannot be applied to operands of type 'Any' and 'String?'}}
// expected-note@-1 {{overloads for '==' exist with these partially matching parameter lists: (CodingUserInfoKey, CodingUserInfoKey), (FloatingPointSign, FloatingPointSign), (String, String), (Unicode.CanonicalCombiningClass, Unicode.CanonicalCombiningClass)}}
}
// SR-12309 - Force unwrapping 'nil' compiles without warning
func sr_12309() {
struct S {
var foo: Int
}
_ = S(foo: nil!) // expected-error {{'nil' literal cannot be force unwrapped}}
_ = nil! // expected-error {{'nil' literal cannot be force unwrapped}}
_ = (nil!) // expected-error {{'nil' literal cannot be force unwrapped}}
_ = (nil)! // expected-error {{'nil' literal cannot be force unwrapped}}
_ = ((nil))! // expected-error {{'nil' literal cannot be force unwrapped}}
_ = nil? // expected-error {{'nil' requires a contextual type}}
_ = ((nil?)) // expected-error {{'nil' requires a contextual type}}
_ = ((nil))? // expected-error {{'nil' requires a contextual type}}
_ = ((nil)?) // expected-error {{'nil' requires a contextual type}}
_ = nil // expected-error {{'nil' requires a contextual type}}
_ = (nil) // expected-error {{'nil' requires a contextual type}}
_ = ((nil)) // expected-error {{'nil' requires a contextual type}}
_ = (((nil))) // expected-error {{'nil' requires a contextual type}}
_ = ((((((nil)))))) // expected-error {{'nil' requires a contextual type}}
_ = (((((((((nil))))))))) // expected-error {{'nil' requires a contextual type}}
}
| apache-2.0 |
vhbit/MastodonKit | Tests/MastodonKitTests/Models/InstanceTests.swift | 1 | 586 | import XCTest
@testable import MastodonKit
class InstanceTests: XCTestCase {
func testInstanceFromJSON() {
let fixture = try? Fixture.load(fileName: "Fixtures/Instance.json")
let dictionary = fixture as! JSONDictionary
let instance = Instance(from: dictionary)
XCTAssertEqual(instance?.uri, "instance's uri")
XCTAssertEqual(instance?.title, "nice title")
XCTAssertEqual(instance?.description, "sweet description")
XCTAssertEqual(instance?.email, "wunderbar email")
XCTAssertEqual(instance?.version, "1.2.3")
}
}
| mit |
neoneye/SwiftyFORM | Source/FormItems/MetaFormItem.swift | 1 | 420 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import Foundation
/// This is an invisible field, that is submitted along with the json
public class MetaFormItem: FormItem {
override func accept(visitor: FormItemVisitor) {
visitor.visit(object: self)
}
public var value: AnyObject?
@discardableResult
public func value(_ value: AnyObject?) -> Self {
self.value = value
return self
}
}
| mit |
tyleryouk11/space-hero | Stick-Hero/GameViewController.swift | 1 | 2862 | //
// GameViewController.swift
// Stick-Hero
//
// Created by 顾枫 on 15/6/19.
// Copyright (c) 2015年 koofrank. All rights reserved.
//
import UIKit
import SpriteKit
import AVFoundation
import GoogleMobileAds
class GameViewController: UIViewController {
var musicPlayer:AVAudioPlayer!
var interstitial: GADInterstitial?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override func viewDidLoad() {
super.viewDidLoad()
let scene = StickHeroGameScene(size:CGSizeMake(DefinedScreenWidth, DefinedScreenHeight))
//ADMOB STUFFFF
interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
let request = GADRequest()
// Requests test ads on test devices.
request.testDevices = ["2077ef9a63d2b398840261c8221a0c9b"]
interstitial!.loadRequest(request)
// Configure the view.
let skView = self.view as! SKView
// skView.showsFPS = true
// skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
self.interstitial = createAndLoadInterstitial()
}
func createAndLoadInterstitial() -> GADInterstitial {
let interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
//interstitial.delegate = self <--- ERROR
interstitial.loadRequest(GADRequest())
return interstitial
}
func interstitialDidDismissScreen (interstitial: GADInterstitial) {
self.interstitial = createAndLoadInterstitial()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
musicPlayer = setupAudioPlayerWithFile("bg_country", type: "mp3")
musicPlayer.numberOfLoops = -1
musicPlayer.play()
}
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer {
let url = NSBundle.mainBundle().URLForResource(file as String, withExtension: type as String)
var audioPlayer:AVAudioPlayer?
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url!)
} catch {
print("NO AUDIO PLAYER")
}
return audioPlayer!
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return .Portrait
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit |
c1moore/deckstravaganza | Deckstravaganza/Card.swift | 1 | 7803 | //
// Card.swift
// Deckstravaganza
//
// Created by Calvin Moore on 9/20/15.
// Copyright © 2015 University of Florida. All rights reserved.
//
import UIKit
class Card {
// Enumeration of legal card suits.
enum CardSuit : Int {
case Clubs = 1;
case Diamonds = 2;
case Hearts = 3;
case Spades = 4;
static let numberOfSuits = 4;
}
// Enumeration of legal card ranks and rank value.
enum CardRank : Int {
case Ace = 1;
case Two = 2;
case Three = 3;
case Four = 4;
case Five = 5;
case Six = 6;
case Seven = 7;
case Eight = 8;
case Nine = 9;
case Ten = 10;
case Jack = 11;
case Queen = 12;
case King = 13;
case Joker = 14;
static let numberOfRanks = 13;
}
// Enumeration of legal card colors.
enum CardColor : Int {
case Red = 1;
case Black = 2;
}
// All card properties are immutable and private.
private let suit : CardSuit;
private let rank : CardRank;
// The color of the card is determined by the suit.
private var color : CardColor {
get {
if(self.suit == .Clubs || self.suit == .Spades) {
return CardColor.Black;
} else {
return CardColor.Red;
}
}
}
init(suit : CardSuit, rank : CardRank) {
self.suit = suit;
self.rank = rank;
}
/**
* Return this card's suit.
*
* @return CardSuit - this card's suit
*/
func getSuit() -> CardSuit {
return self.suit;
}
/**
* Return this card's rank.
*
* @return CardRank - this card's rank
*/
func getRank() -> CardRank {
return self.rank;
}
/**
* Return this card's color.
*
* @return CardColor - this card's color
*/
func getColor() -> CardColor {
return self.color;
}
/**
* Return true if and only if this card matches the specified card's rank.
*
* @param card : Card - The card with which to compare this card.
* @return Bool - true if both cards have the same rank
*/
func hasSameRankAs(card : Card) -> Bool {
return (self.rank == card.getRank());
}
/**
* Return true if and only if this card matches the specified card's suit.
*
* @param card : Card - The card with which to compare this card.
* @return Bool - true if both cards have the same suit
*/
func hasSameSuitAs(card : Card) -> Bool {
return (self.suit == card.getSuit());
}
/**
* Return true if and only if this card matches the specified card's color.
*
* @param card : Card - The card with which to compare this card.
* @return Bool - true if both cards have the same color
*/
func hasSameColorAs(card : Card) -> Bool {
return (self.color == card.getColor());
}
/**
* Return true if and only if this card does not match the specified card's color.
*
* @param card : Card - The card with which to compare this card.
* @return Bool - true if this card has the opposite color of the specified card
*/
func hasOppositeColorThan(card : Card) -> Bool {
return (self.color != card.getColor());
}
/**
* Return true if and only if this card has a higher rank than the specified card.
*
* @param card : Card - The card with which to compare this card.
* @param acesLow : Bool - True if Aces should be considered low.
* @return Bool - true if this card has a higher rank than the specified card
*/
func isHigherThan(card : Card, acesLow : Bool) -> Bool {
if(acesLow || (!acesLow && self.rank != .Ace && card.getRank() != .Ace)) {
return (self.rank.rawValue < card.getRank().rawValue);
} else {
if(self.rank == .Ace && card.getRank() != .Ace) {
return true;
} else if(self.rank != .Ace && card.getRank() == .Ace) {
return false;
} else {
return false;
}
}
}
/**
* Return true if and only if this card has a lower rank than the specified card.
*
* @param card : Card - The card with which to compare this card.
* @param acesLow : Bool - True if Aces should be considered low.
* @return Bool - true if this card has a lower rank than the specified card
*/
func isLowerThan(card : Card, acesLow : Bool) -> Bool {
if(acesLow || (!acesLow && self.rank != .Ace && card.getRank() != .Ace)) {
return (self.rank.rawValue > card.getRank().rawValue);
} else {
if(self.rank == .Ace && card.getRank() != .Ace) {
return false;
} else if(self.rank != .Ace && card.getRank() == .Ace) {
return true;
} else {
return false;
}
}
}
/**
* If ignoreSuit is true or not specified, return true if and only if this card's
* rank matches the specified card's rank. If ignoreSuit is false, return true if
* and only if this card's rank and suit matches the specified card's rank and
* suit.
*
* @param card : Card - The card with which to compare this card.
* @param ignoreSuit : Bool (default true) - True if suit should not be considered; false otherwise.
* @return Bool - true if this card is equal to the specified card
*/
func isEqualTo(card : Card, ignoreSuit : Bool = true) -> Bool {
if(ignoreSuit) {
return (self.rank == card.getRank());
} else {
return (self.rank == card.getRank() && self.suit == card.getSuit());
}
}
/**
* Returns the face of this card.
*
* @param deckChoice : DeckFronts - the deck front being used by this deck to which this card belongs
* @return UIImage? - the face of this card if found
*/
func getCardFace(deckChoice : Deck.DeckFronts) -> UIImage? {
let cardRank : String;
let cardSuit : String;
var cardOption : Deck.DeckFronts = deckChoice;
switch(self.suit) {
case .Clubs:
cardSuit = "clubs";
case .Diamonds:
cardSuit = "diamonds";
case .Hearts:
cardSuit = "hearts";
case .Spades:
cardSuit = "spades";
}
switch(self.rank) {
case .Ace:
cardRank = "ace";
case .Jack:
cardRank = "jack";
case .Queen:
cardRank = "queen";
case .King:
cardRank = "king";
default:
cardRank = String(self.rank.rawValue);
}
// The only difference between Deck1 and Deck2 are the Kings, Queens, and Jacks.
if(self.rank.rawValue <= CardRank.Ten.rawValue && cardOption == Deck.DeckFronts.Deck3 && !(self.rank
== .Ace && self.suit == .Spades)) {
cardOption = Deck.DeckFronts.Deck2;
}
let imageName = cardRank + "_" + cardSuit + "_" + cardOption.rawValue;
return UIImage(named: imageName);
}
/**
* Returns the back of this card.
*
* @param deckChoice : DeckBacks - the deck back being used by the deck to which this card belongs
* @return UIImage? - the back of this card if found
*/
func getCardBack(deckChoice : Deck.DeckBacks) -> UIImage? {
let imageName = "back_" + deckChoice.rawValue;
return UIImage(named: imageName);
}
} | mit |
smizy/DemoWebviewApsalar_ios | DemoAppWebview/AppDelegate.swift | 1 | 6464 | //
// AppDelegate.swift
// DemoAppWebview
//
// Created by usr0300789 on 2014/11/14.
// Copyright (c) 2014年 smizy. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
// added
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
Apsalar.startSession("<API KEY>", withKey: "<SECRET>", andURL:url)
return true
}
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.
Apsalar.startSession("<API KEY>", withKey: "<SECRET>")
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "jp.koukoku.DemoAppWebview" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("DemoAppWebview", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("DemoAppWebview.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit |
russelhampton05/MenMew | App Prototypes/Menu_Server_App_Prototype_001/Menu_Server_App_Prototype_001/Models.swift | 1 | 9263 | //
// Models.swift
// App_Prototype_Alpha_001
//
// Created by Jon Calanio on 10/3/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import Foundation
import Firebase
//User Class
class User {
var ID: String
var name: String?
var theme: String?
var email: String?
var ticket: Ticket?
var image: String?
init(id: String, email: String?, name: String?, ticket:Ticket?, theme: String?, image: String?){
self.ID = id
self.theme = theme
self.email = email
self.name = name
self.ticket = ticket
self.image = image
}
}
//Server Class
class Server {
var ID: String
var name: String?
var email: String?
var theme: String?
var image: String?
var restaurants: [String]?
var tables: [String]?
var notifications = true
init (id: String, name: String?, email: String?, restaurants: [String]?, tables: [String]?, theme: String?, image: String?, notifications: Bool) {
self.ID = id
self.theme = theme
self.name = name
self.email = email
self.restaurants = restaurants
self.tables = tables
self.image = image
self.notifications = notifications
}
}
//Details Class
//need to look at maybe changing this
struct Details {
var sides: [String]
var cookType: [String]
}
//Menu Class
class Menu{
var rest_id : String?
var title : String?
var cover_picture : String?
var menu_groups : [MenuGroup]? = []
init(id:String, title:String, cover_picture:String?, groups: [MenuGroup]){
self.rest_id = id
self.title = title
self.cover_picture = cover_picture
self.menu_groups = groups
}
init(){
}
convenience init(id:String, title:String, groups: [MenuGroup] ) {
self.init(id:id, title:title, cover_picture:nil, groups:groups)
}
}
//Menu Group Class
class MenuGroup{
var cover_picture: String?
var desc: String?
var title: String?
var items: [MenuItem]?
init(){
}
init(desc: String,items: [MenuItem], title: String?, cover_picture:String?){
self.cover_picture = cover_picture
self.desc = desc
self.title = title
self.items = items
}
convenience init(desc: String,items: [MenuItem], title: String?){
self.init(desc:desc,items:items, title:title, cover_picture:nil)
}
convenience init(desc: String,items: [MenuItem], cover_picture:String?) {
self.init(desc:desc,items:items, title:nil, cover_picture:cover_picture)
}
convenience init(desc: String,items: [MenuItem]) {
self.init(desc:desc, items:items, title:nil, cover_picture:nil)
}
}
//menu item objects and menus are for UI purposes only.
//Menu item will have a member called "item", which will tie it in to the actaul
//details necessary for order tracking.
//Menu Item Class
class MenuItem {
//will eventually point to an actual item (if we care to implement that, possibly not)
//for now just UI facing fields and those needed for ordering/pricing
var item_ID: String?
var title: String?
var price: Double?
//var sides: [String]?
var image: String?
var desc: String?
init(){
}
init(item_ID: String?, title:String, price:Double, image: String, desc: String) {
self.item_ID = item_ID
self.title = title
self.image = image
self.price = price
// self.sides = sides
self.desc = desc
}
//convenience init(title:String, price:Double, image: String, desc: String){
// self.init(title : title, price : price, image : image, desc: desc, sides:nil)
//}
}
//Restaurant Class
class Restaurant {
var restaurant_ID: String?
var title: String?
var location: String?
//We can also reference tables and servers here
init() {
self.restaurant_ID = ""
self.title = ""
self.location = ""
}
init(restaurant_ID: String, title: String, location: String?) {
self.restaurant_ID = restaurant_ID
self.title = title
self.location = location
}
}
//Ticket Class
class Ticket {
var ticket_ID: String?
var user_ID: String?
var restaurant_ID: String?
var tableNum: String?
var timestamp: String?
var paid: Bool?
var itemsOrdered: [MenuItem]?
var desc: String?
var confirmed: Bool?
var status: String?
var total: Double?
var tip: Double?
var message_ID: String?
init() {
self.message_ID = ""
self.ticket_ID = ""
self.user_ID = ""
self.restaurant_ID = ""
self.tableNum = ""
self.paid = false
self.itemsOrdered = []
self.desc = ""
self.confirmed = false
self.status = "Ordering"
self.total = 0.0
self.tip = 0.0
}
init(ticket_ID: String, user_ID: String, restaurant_ID: String, tableNum: String, timestamp: String, paid: Bool, itemsOrdered:[MenuItem]?, desc: String?, confirmed: Bool?, status: String?, total: Double?, tip: Double?, message_ID: String?) {
self.ticket_ID = ticket_ID
self.user_ID = user_ID
self.restaurant_ID = restaurant_ID
self.tableNum = tableNum
self.timestamp = timestamp
self.paid = paid
self.itemsOrdered = itemsOrdered
self.desc = desc
self.confirmed = confirmed
self.status = status
self.total = total
self.tip = tip
self.message_ID = message_ID
if self.message_ID == nil{
self.message_ID = ""
}
}
func generateMessageGUID() {
self.message_ID = UUID().uuidString
}
init(snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as! [String: AnyObject]
self.ticket_ID = snapshot.key
self.user_ID = snapshotValue["user"] as? String
self.restaurant_ID = snapshotValue["restaurant"] as? String
self.tableNum = snapshotValue["table"] as? String
self.timestamp = snapshotValue["timestamp"] as? String
self.paid = snapshotValue["paid"] as? Bool
self.desc = snapshotValue["desc"] as? String
self.confirmed = snapshotValue["confirmed"] as? Bool
self.status = snapshotValue["status"] as? String
self.total = snapshotValue["total"] as? Double
self.tip = snapshotValue["tip"] as? Double
if snapshotValue["message"] != nil{
self.message_ID = snapshotValue["message"] as! String?
}
else{
self.message_ID = ""
}
//MenuItemManager.GetMenuItem(ids: snapshotValue["itemsOrdered"]?.allKeys as! [String]) {
//items in
//self.itemsOrdered = items;
//}
//ItemsOrdered is the array of items ordered for the table
// let menuItems = snapshotValue["itemsOrdered"] as? NSDictionary
}
}
//Message Class
class Message {
var message_ID: String?
var serverMessage: String?
var userMessage: String?
init(snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as! [String: AnyObject]
self.message_ID = snapshot.key
self.serverMessage = snapshotValue["server"] as? String
self.userMessage = snapshotValue["user"] as? String
}
}
class Theme {
var name: String?
var primary: UIColor?
var secondary: UIColor?
var highlight: UIColor?
var invert: UIColor?
init(type: String) {
if type == "Salmon" {
name = "Salmon"
primary = UIColor(red: 255, green: 106, blue: 92)
secondary = UIColor(red: 255, green: 255, blue: 255)
highlight = UIColor(red: 255, green: 255, blue: 255)
invert = UIColor(red: 255, green: 106, blue: 92)
}
else if type == "Light" {
name = "Light"
primary = UIColor(red: 255, green: 255, blue: 255)
secondary = UIColor(red: 255, green: 255, blue: 255)
highlight = UIColor(red: 255, green: 141, blue: 43)
invert = UIColor(red: 255, green: 141, blue: 43)
}
else if type == "Midnight" {
name = "Midnight"
primary = UIColor(red: 55, green: 30, blue: 96)
secondary = UIColor(red: 18, green: 3, blue: 42)
highlight = UIColor(red: 255, green: 255, blue: 255)
invert = UIColor(red: 255, green: 255, blue: 255)
}
else if type == "Slate" {
name = "Slate"
primary = UIColor(red: 27, green: 27, blue: 27)
secondary = UIColor(red: 20, green: 20, blue: 20)
highlight = UIColor(red: 255, green: 255, blue: 255)
invert = UIColor(red: 255, green: 255, blue: 255)
}
}
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
let newRed = CGFloat(red)/255
let newGreen = CGFloat(green)/255
let newBlue = CGFloat(blue)/255
self.init(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
}
}
| mit |
csmulhern/uranus | iOS Example/iOS Example/ViewController.swift | 1 | 4896 | import UIKit
import Uranus
class ViewController: UIViewController {
var componentsView: ComponentsScrollView!
var layout: View!
var alternateLayout: View!
var showingNormalLayout = true
var switchLayoutBarButtonItem: UIBarButtonItem!
var layoutDirectionBarButtonItem: UIBarButtonItem?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.switchLayoutBarButtonItem = UIBarButtonItem(title: "Switch Layout", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.toggleLayout))
self.navigationItem.leftBarButtonItem = switchLayoutBarButtonItem
if #available(iOS 9, *) {
self.layoutDirectionBarButtonItem = UIBarButtonItem(title: "Force RTL On", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.toggleRTL))
self.navigationItem.rightBarButtonItem = layoutDirectionBarButtonItem
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func newPostComponents() -> [Component] {
let label = Label(text: "This is a label", font: UIFont.systemFont(ofSize: 20.0))
label.backgroundColor = UIColor.blue.withAlphaComponent(0.2)
label.layoutType = LayoutType.full
let imageView = ImageView(image: UIImage(named: "image"), contentMode: UIViewContentMode.scaleAspectFill)
imageView.layoutType = LayoutType.full
let cancelButton = Button()
cancelButton.backgroundColor = UIColor.red.withAlphaComponent(0.2)
cancelButton.setTitle("Cancel", forState: UIControlState.normal)
cancelButton.setTitleColor(UIColor.black, forState: UIControlState.normal)
cancelButton.addTarget(target: self, action: #selector(cancelButtonSelected), forControlEvents: UIControlEvents.touchUpInside)
cancelButton.padding = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
cancelButton.flexible = true
return [label, imageView, cancelButton, self.newAcceptButtonComponent()]
}
func newAcceptButtonComponent() -> Component {
let acceptButton = Button()
acceptButton.backgroundColor = UIColor.green.withAlphaComponent(0.2)
acceptButton.setTitle("Okay", forState: UIControlState.normal)
acceptButton.setTitleColor(UIColor.black, forState: UIControlState.normal)
acceptButton.addTarget(target: self, action: #selector(acceptButtonSelected), forControlEvents: UIControlEvents.touchUpInside)
acceptButton.padding = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
acceptButton.flexible = true
return acceptButton
}
func newTextViewComponent() -> Component {
let textView = TextView(text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", font: UIFont.systemFont(ofSize: 20.0))
textView.layoutType = LayoutType.full
textView.editable = false
return textView
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.componentsView = ComponentsScrollView(frame: CGRect.zero)
self.componentsView.alwaysBounceVertical = true
self.view.addSubview(self.componentsView)
let components = [self.newPostComponents()].cycle().take(4).joined()
self.layout = View(children: Array(components))
self.alternateLayout = View().children([self.newTextViewComponent(), self.newAcceptButtonComponent()])
self.componentsView.configure(with: self.layout)
}
override func viewDidLayoutSubviews() {
self.componentsView.frame = self.view.bounds
}
@objc func toggleLayout() {
self.showingNormalLayout = !self.showingNormalLayout
if self.showingNormalLayout {
self.componentsView.configure(with: self.layout, animated: true)
}
else {
self.componentsView.configure(with: self.alternateLayout, animated: true)
}
}
@objc @available(iOS 9, *)
func toggleRTL() {
if self.componentsView.semanticContentAttribute == UISemanticContentAttribute.forceRightToLeft {
self.componentsView.semanticContentAttribute = UISemanticContentAttribute.unspecified
self.layoutDirectionBarButtonItem?.title = "Force RTL On"
}
else {
self.componentsView.semanticContentAttribute = UISemanticContentAttribute.forceRightToLeft
self.layoutDirectionBarButtonItem?.title = "Force RTL Off"
}
}
@objc private func cancelButtonSelected() {
print("Cancel selected.")
}
@objc private func acceptButtonSelected() {
print("Accept selected.")
}
}
| unlicense |
lsolniczek/SwiftLint | Source/SwiftLintFrameworkTests/ReporterTests.swift | 1 | 2164 | //
// ReporterTests.swift
// SwiftLint
//
// Created by JP Simard on 9/19/15.
// Copyright © 2015 Realm. All rights reserved.
//
import SwiftLintFramework
import XCTest
class ReporterTests: XCTestCase {
func generateViolations() -> [StyleViolation] {
return [
StyleViolation(type: .Length,
location: Location(file: "filename", line: 1, character: 2),
severity: .Warning,
reason: "Violation Reason."),
StyleViolation(type: .Length,
location: Location(file: "filename", line: 1, character: 2),
severity: .Error,
reason: "Violation Reason.")
]
}
func testXcodeReporter() {
XCTAssertEqual(
XcodeReporter.generateReport(generateViolations()),
"filename:1:2: warning: Length Violation: Violation Reason.\n" +
"filename:1:2: error: Length Violation: Violation Reason."
)
}
func testJSONReporter() {
XCTAssertEqual(
JSONReporter.generateReport(generateViolations()),
"[\n" +
" {\n" +
" \"type\" : \"Length\",\n" +
" \"line\" : 1,\n" +
" \"reason\" : \"Violation Reason.\",\n" +
" \"file\" : \"filename\",\n" +
" \"character\" : 2,\n" +
" \"severity\" : \"Warning\"\n" +
" },\n" +
" {\n" +
" \"type\" : \"Length\",\n" +
" \"line\" : 1,\n" +
" \"reason\" : \"Violation Reason.\",\n" +
" \"file\" : \"filename\",\n" +
" \"character\" : 2,\n" +
" \"severity\" : \"Error\"\n" +
" }\n" +
"]"
)
}
func testCSVReporter() {
XCTAssertEqual(
CSVReporter.generateReport(generateViolations()),
"file,line,character,severity,type,reason," +
"filename,1,2,Warning,Length,Violation Reason.," +
"filename,1,2,Error,Length,Violation Reason."
)
}
}
| mit |
externl/ice | swift/test/Ice/inheritance/Client.swift | 4 | 383 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Ice
import PromiseKit
import TestCommon
public class Client: TestHelperI {
public override func run(args: [String]) throws {
let communicator = try initialize(args)
defer {
communicator.destroy()
}
let initial = try allTests(self)
try initial.shutdown()
}
}
| gpl-2.0 |
UroborosStudios/UOHelpers | UOHelpers/MediaExtensions.swift | 1 | 1734 | //
// MediaExtensions.swift
// UOHelpers
//
// Created by Jonathan Silva on 04/05/17.
// Copyright © 2017 Uroboros Studios. All rights reserved.
//
import Foundation
import UIKit
public extension UIColor {
open convenience init(fromHex: String) {
let hexString:NSString = fromHex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) as NSString
let scanner = Scanner(string: fromHex)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color:UInt32 = 0
scanner.scanHexInt32(&color)
let mask = 0x000000FF
let r = Int(color >> 16) & mask
let g = Int(color >> 8) & mask
let b = Int(color) & mask
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
self.init(red:red, green:green, blue:blue, alpha:1)
}
open convenience init(fromHex: String,withAlpha: CGFloat) {
let hexString:NSString = fromHex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) as NSString
let scanner = Scanner(string: fromHex)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color:UInt32 = 0
scanner.scanHexInt32(&color)
let mask = 0x000000FF
let r = Int(color >> 16) & mask
let g = Int(color >> 8) & mask
let b = Int(color) & mask
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
self.init(red:red, green:green, blue:blue, alpha: withAlpha)
}
}
| mit |
fespinoza/linked-ideas-osx | Playground-iOS.playground/Pages/5. bezier paths.xcplaygroundpage/Contents.swift | 1 | 318 | //: [Previous](@previous)
import Foundation
import UIKit
var str = "Hello, playground"
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 100, y: 0))
bezierPath.addLine(to: CGPoint(x: 100, y: 100))
bezierPath.addLine(to: CGPoint(x: 200, y: 0))
bezierPath.close()
bezierPath.stroke()
//: [Next](@next)
| mit |
rabbah/openwhisk | tests/dat/actions/hello.swift | 11 | 1063 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
/**
* Hello world as a Swift Whisk action.
*/
func main(args: [String:Any]) -> [String:Any] {
if let name = args["name"] as? String {
return [ "greeting" : "Hello \(name)!" ]
} else {
return [ "greeting" : "Hello stranger!" ]
}
}
| apache-2.0 |
peferron/algo | EPI/Stacks and Queues/Implement a queue using stacks/swift/main.swift | 1 | 841 | // Nerfed array to make sure we don't cheat by doing e.g. index-based access.
struct Stack<T> {
var array = [T]()
var count: Int {
return array.count
}
mutating func push(_ element: T) {
array.append(element)
}
mutating func pop() -> T {
return array.removeLast()
}
}
public struct Queue<T> {
var enqueueStack = Stack<T>()
var dequeueStack = Stack<T>()
public var count: Int {
return enqueueStack.count + dequeueStack.count
}
public mutating func enqueue(_ element: T) {
enqueueStack.push(element)
}
public mutating func dequeue() -> T {
if dequeueStack.count == 0 {
while enqueueStack.count > 0 {
dequeueStack.push(enqueueStack.pop())
}
}
return dequeueStack.pop()
}
}
| mit |
rzrasel/iOS-Swift-2016-01 | SwiftTableHeaderOne/SwiftTableHeaderOne/AppDelegate.swift | 2 | 6113 | //
// AppDelegate.swift
// SwiftTableHeaderOne
//
// Created by NextDot on 2/11/16.
// Copyright © 2016 RzRasel. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "rz.rasel.SwiftTableHeaderOne" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("SwiftTableHeaderOne", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| apache-2.0 |
wireapp/wire-ios-sync-engine | Tests/Source/UserSession/BuildTypeTests.swift | 1 | 2861 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
import WireTesting
@testable import WireSyncEngine
final class BuildTypeTests: ZMTBaseTest {
func testThatItParsesKnownBundleIDs() {
// GIVEN
let bundleIdsToTypes: [String: WireSyncEngine.BuildType] = ["com.wearezeta.zclient.ios": .production,
"com.wearezeta.zclient-alpha": .alpha,
"com.wearezeta.zclient.ios-development": .development,
"com.wearezeta.zclient.ios-release": .releaseCandidate,
"com.wearezeta.zclient.ios-internal": .internal]
bundleIdsToTypes.forEach { bundleId, expectedType in
// WHEN
let type = WireSyncEngine.BuildType(bundleID: bundleId)
// THEN
XCTAssertEqual(type, expectedType)
}
}
func testThatItParsesUnknownBundleID() {
// GIVEN
let someBundleId = "com.mycompany.myapp"
// WHEN
let buildType = WireSyncEngine.BuildType(bundleID: someBundleId)
// THEN
XCTAssertEqual(buildType, WireSyncEngine.BuildType.custom(bundleID: someBundleId))
}
func testThatItReturnsTheCertName() {
// GIVEN
let suts: [(BuildType, String)] = [(.alpha, "com.wire.ent"),
(.internal, "com.wire.int.ent"),
(.releaseCandidate, "com.wire.rc.ent"),
(.development, "com.wire.dev.ent")]
suts.forEach { (type, certName) in
// WHEN
let certName = type.certificateName
// THEN
XCTAssertEqual(certName, certName)
}
}
func testThatItReturnsBundleIdForCertNameIfCustom() {
// GIVEN
let type = WireSyncEngine.BuildType.custom(bundleID: "com.mycompany.myapp")
// WHEN
let certName = type.certificateName
// THEN
XCTAssertEqual(certName, "com.mycompany.myapp")
}
}
| gpl-3.0 |
seandavidmcgee/HumanKontactBeta | src/Pods/Hokusai/Classes/Hokusai.swift | 1 | 15917 | //
// Hokusai.swift
// Hokusai
//
// Created by Yuta Akizuki on 2015/07/07.
// Copyright (c) 2015年 ytakzk. All rights reserved.
//
import UIKit
private struct HOKConsts {
let animationDuration:NSTimeInterval = 0.8
let hokusaiTag = 9999
}
// Action Types
public enum HOKAcitonType {
case None, Selector, Closure
}
// Color Types
public enum HOKColorScheme {
case Hokusai, Asagi, Matcha, Tsubaki, Inari, Karasu, Enshu
func getColors() -> HOKColors {
switch self {
case .Asagi:
return HOKColors(
backGroundColor: UIColorHex(0x0bada8),
buttonColor: UIColorHex(0x08827e),
cancelButtonColor: UIColorHex(0x6dcecb),
fontColor: UIColorHex(0xffffff)
)
case .Matcha:
return HOKColors(
backGroundColor: UIColorHex(0x314631),
buttonColor: UIColorHex(0x618c61),
cancelButtonColor: UIColorHex(0x496949),
fontColor: UIColorHex(0xffffff)
)
case .Tsubaki:
return HOKColors(
backGroundColor: UIColorHex(0xe5384c),
buttonColor: UIColorHex(0xac2a39),
cancelButtonColor: UIColorHex(0xc75764),
fontColor: UIColorHex(0xffffff)
)
case .Inari:
return HOKColors(
backGroundColor: UIColorHex(0xdd4d05),
buttonColor: UIColorHex(0xa63a04),
cancelButtonColor: UIColorHex(0xb24312),
fontColor: UIColorHex(0x231e1c)
)
case .Karasu:
return HOKColors(
backGroundColor: UIColorHex(0x180614),
buttonColor: UIColorHex(0x3d303d),
cancelButtonColor: UIColorHex(0x261d26),
fontColor: UIColorHex(0x9b9981)
)
case .Enshu:
return HOKColors(
backGroundColor: UIColorHex(0xccccbe),
buttonColor: UIColorHex(0xffffff),
cancelButtonColor: UIColorHex(0xe5e5d8),
fontColor: UIColorHex(0x9b9981)
)
default: // Hokusai
return HOKColors(
backGroundColor: UIColorHex(0x00AFF0),
buttonColor: UIColorHex(0x197EAD),
cancelButtonColor: UIColorHex(0x1D94CA),
fontColor: UIColorHex(0xffffff)
)
}
}
private func UIColorHex(hex: UInt) -> UIColor {
return UIColor(
red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hex & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
final public class HOKColors: NSObject {
var backgroundColor: UIColor
var buttonColor: UIColor
var cancelButtonColor: UIColor
var fontColor: UIColor
required public init(backGroundColor: UIColor, buttonColor: UIColor, cancelButtonColor: UIColor, fontColor: UIColor) {
self.backgroundColor = backGroundColor
self.buttonColor = buttonColor
self.cancelButtonColor = cancelButtonColor
self.fontColor = fontColor
}
}
final public class HOKButton: UIButton {
var target:AnyObject!
var selector:Selector!
var action:(()->Void)!
var actionType = HOKAcitonType.None
var isCancelButton = false
// Font
let kDefaultFont = "AvenirNext-DemiBold"
let kFontSize:CGFloat = 16.0
func setColor(colors: HOKColors) {
self.setTitleColor(colors.fontColor, forState: .Normal)
self.backgroundColor = (isCancelButton) ? colors.cancelButtonColor : colors.buttonColor
}
func setFontName(fontName: String?) {
let name:String
if let fontName = fontName where !fontName.isEmpty {
name = fontName
} else {
name = kDefaultFont
}
self.titleLabel?.font = UIFont(name: name, size:kFontSize)
}
}
final public class HOKMenuView: UIView {
var colorScheme = HOKColorScheme.Hokusai
public let kDamping: CGFloat = 0.7
public let kInitialSpringVelocity: CGFloat = 0.8
private var displayLink: CADisplayLink?
private let shapeLayer = CAShapeLayer()
private var bendableOffset = UIOffsetZero
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func layoutSubviews() {
super.layoutSubviews()
shapeLayer.frame.origin = frame.origin
shapeLayer.bounds.origin = frame.origin
}
func setShapeLayer(colors: HOKColors) {
self.backgroundColor = UIColor.clearColor()
shapeLayer.fillColor = colors.backgroundColor.CGColor
self.layer.insertSublayer(shapeLayer, atIndex: 0)
}
func positionAnimationWillStart() {
if displayLink == nil {
displayLink = CADisplayLink(target: self, selector: "tick:")
displayLink!.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
}
shapeLayer.bounds = CGRect(origin: CGPointZero, size: self.bounds.size)
}
func updatePath() {
let width = CGRectGetWidth(shapeLayer.bounds)
let height = CGRectGetHeight(shapeLayer.bounds)
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 0, y: 0))
path.addQuadCurveToPoint(CGPoint(x: width, y: 0),
controlPoint:CGPoint(x: width * 0.5, y: 0 + bendableOffset.vertical))
path.addQuadCurveToPoint(CGPoint(x: width, y: height + 100.0),
controlPoint:CGPoint(x: width + bendableOffset.horizontal, y: height * 0.5))
path.addQuadCurveToPoint(CGPoint(x: 0, y: height + 100.0),
controlPoint: CGPoint(x: width * 0.5, y: height + 100.0))
path.addQuadCurveToPoint(CGPoint(x: 0, y: 0),
controlPoint: CGPoint(x: bendableOffset.horizontal, y: height * 0.5))
path.closePath()
shapeLayer.path = path.CGPath
}
func tick(displayLink: CADisplayLink) {
if let presentationLayer = layer.presentationLayer() as? CALayer {
var verticalOffset = self.layer.frame.origin.y - presentationLayer.frame.origin.y
// On dismissing, the offset should not be offend on the buttons.
if verticalOffset > 0 {
verticalOffset *= 0.2
}
bendableOffset = UIOffset(
horizontal: 0.0,
vertical: verticalOffset
)
updatePath()
if verticalOffset == 0 {
self.displayLink!.invalidate()
self.displayLink = nil
}
}
}
}
final public class Hokusai: UIViewController, UIGestureRecognizerDelegate {
// Views
private var menuView = HOKMenuView()
private var buttons = [HOKButton]()
private var instance:Hokusai! = nil
private var kButtonWidth:CGFloat = 250
private let kButtonHeight:CGFloat = 48.0
private let kButtonInterval:CGFloat = 16.0
private var bgColor = UIColor(white: 1.0, alpha: 0.7)
// Variables users can change
public var colorScheme = HOKColorScheme.Hokusai
public var fontName = ""
public var colors:HOKColors! = nil
public var cancelButtonTitle = "Cancel"
public var cancelButtonAction : (()->Void)?
required public init(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
required public init() {
super.init(nibName:nil, bundle:nil)
view.frame = UIScreen.mainScreen().bounds
view.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
view.backgroundColor = UIColor.clearColor()
menuView.frame = view.frame
view.addSubview(menuView)
kButtonWidth = view.frame.width * 0.8
// Gesture Recognizer for tapping outside the menu
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("dismiss"))
tapGesture.numberOfTapsRequired = 1
tapGesture.delegate = self
self.view.addGestureRecognizer(tapGesture)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onOrientationChange:", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
func onOrientationChange(notification: NSNotification){
kButtonWidth = view.frame.width * 0.8
let menuHeight = CGFloat(buttons.count + 2) * kButtonInterval + CGFloat(buttons.count) * kButtonHeight
menuView.frame = CGRect(
x: 0,
y: view.frame.height - menuHeight,
width: view.frame.width,
height: menuHeight
)
menuView.shapeLayer.frame = menuView.frame
menuView.shapeLayer.bounds.origin = menuView.frame.origin
menuView.shapeLayer.layoutIfNeeded()
menuView.layoutIfNeeded()
for var i = 0; i < buttons.count; i++ {
let btn = buttons[i]
btn.frame = CGRect(x: 0.0, y: 0.0, width: kButtonWidth, height: kButtonHeight)
btn.center = CGPoint(x: view.center.x, y: -kButtonHeight * 0.25 + (kButtonHeight + kButtonInterval) * CGFloat(i + 1))
}
self.view.layoutIfNeeded()
}
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if touch.view != gestureRecognizer.view {
return false
}
return true
}
// Add a button with a closure
public func addButton(title:String, action:()->Void) -> HOKButton {
let btn = addButton(title)
btn.action = action
btn.actionType = HOKAcitonType.Closure
btn.addTarget(self, action:Selector("buttonTapped:"), forControlEvents:.TouchUpInside)
return btn
}
// Add a button with a selector
public func addButton(title:String, target:AnyObject, selector:Selector) -> HOKButton {
let btn = addButton(title)
btn.target = target
btn.selector = selector
btn.actionType = HOKAcitonType.Selector
btn.addTarget(self, action:Selector("buttonTapped:"), forControlEvents:.TouchUpInside)
return btn
}
// Add a cancel button
public func addCancelButton(title:String) -> HOKButton {
if let cancelButtonAction = cancelButtonAction {
return addButton(title, action: cancelButtonAction)
} else {
let btn = addButton(title)
btn.addTarget(self, action:Selector("buttonTapped:"), forControlEvents:.TouchUpInside)
btn.isCancelButton = true
return btn
}
}
// Add a button just with the title
private func addButton(title:String) -> HOKButton {
let btn = HOKButton()
btn.layer.masksToBounds = true
btn.setTitle(title, forState: .Normal)
menuView.addSubview(btn)
buttons.append(btn)
return btn
}
// Show the menu
public func show() {
if let rv = UIApplication.sharedApplication().keyWindow {
if rv.viewWithTag(HOKConsts().hokusaiTag) == nil {
view.tag = HOKConsts().hokusaiTag.hashValue
rv.addSubview(view)
}
} else {
print("Hokusai:: You have to call show() after the controller has appeared.")
return
}
// This is needed to retain this instance.
instance = self
let colors = (self.colors == nil) ? colorScheme.getColors() : self.colors
// Set a background color of Menuview
menuView.setShapeLayer(colors)
// Add a cancel button
self.addCancelButton("Done")
// Decide the menu size
let menuHeight = CGFloat(buttons.count + 2) * kButtonInterval + CGFloat(buttons.count) * kButtonHeight
menuView.frame = CGRect(
x: 0,
y: view.frame.height - menuHeight,
width: view.frame.width,
height: menuHeight
)
// Locate buttons
for var i = 0; i < buttons.count; i++ {
let btn = buttons[i]
btn.frame = CGRect(x: 0.0, y: 0.0, width: kButtonWidth, height: kButtonHeight)
btn.center = CGPoint(x: view.center.x, y: -kButtonHeight * 0.25 + (kButtonHeight + kButtonInterval) * CGFloat(i + 1))
btn.layer.cornerRadius = kButtonHeight * 0.5
btn.setFontName(fontName)
btn.setColor(colors)
}
// Animations
animationWillStart()
// Debug
if (buttons.count == 0) {
print("Hokusai:: The menu has no item yet.")
} else if (buttons.count > 6) {
print("Hokusai:: The menu has lots of items.")
}
}
// Add an animation on showing the menu
private func animationWillStart() {
// Background
self.view.backgroundColor = UIColor.clearColor()
UIView.animateWithDuration(HOKConsts().animationDuration * 0.4,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseOut,
animations: {
self.view.backgroundColor = self.bgColor
},
completion: nil
)
// Menuview
menuView.frame = CGRect(origin: CGPoint(x: 0.0, y: self.view.frame.height), size: menuView.frame.size)
UIView.animateWithDuration(HOKConsts().animationDuration,
delay: 0.0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.6,
options: [.BeginFromCurrentState, .AllowUserInteraction, .OverrideInheritedOptions],
animations: {
self.menuView.frame = CGRect(origin: CGPoint(x: 0.0, y: self.view.frame.height-self.menuView.frame.height), size: self.menuView.frame.size)
self.menuView.layoutIfNeeded()
},
completion: {(finished) in
})
menuView.positionAnimationWillStart()
}
// Dismiss the menuview
public func dismiss() {
// Background and Menuview
UIView.animateWithDuration(HOKConsts().animationDuration,
delay: 0.0,
usingSpringWithDamping: 100.0,
initialSpringVelocity: 0.6,
options: [.BeginFromCurrentState, .AllowUserInteraction, .OverrideInheritedOptions, .CurveEaseOut],
animations: {
self.view.backgroundColor = UIColor.clearColor()
self.menuView.frame = CGRect(origin: CGPoint(x: 0.0, y: self.view.frame.height), size: self.menuView.frame.size)
},
completion: {(finished) in
self.view.removeFromSuperview()
})
menuView.positionAnimationWillStart()
}
// When the buttons are tapped, this method is called.
func buttonTapped(btn:HOKButton) {
if btn.actionType == HOKAcitonType.Closure {
btn.action()
} else if btn.actionType == HOKAcitonType.Selector {
let control = UIControl()
control.sendAction(btn.selector, to:btn.target, forEvent:nil)
} else {
if !btn.isCancelButton {
print("Unknow action type for button")
}
}
dismiss()
}
}
| mit |
PodBuilder/XcodeKit | SwiftXcodeKit/Resources/CompileSourcesBuildPhase.swift | 1 | 2706 | /*
* The sources in the "XcodeKit" directory are based on the Ruby project Xcoder.
*
* Copyright (c) 2012 cisimple
*
* MIT License
*
* 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.
*/
public class CompileSourcesBuildPhase: BuildPhase {
public override class var isaString: String {
get {
return "PBXSourcesBuildPhase"
}
}
public class func create(inout inRegistry registry: ObjectRegistry) -> CompileSourcesBuildPhase {
let properties = [
"isa": isaString,
"buildActionMask": NSNumber(integer: 2147483647),
"files": [AnyObject](),
"runOnlyForDeploymentPreprocessing": "0"
]
let phase = CompileSourcesBuildPhase(identifier: registry.generateOID(targetDescription: nil), inRegistry: registry, properties: properties)
registry.putResource(phase)
return phase
}
public func addBuildFileWithReference(reference: FileReference, useAutomaticReferenceCounting useARC: Bool, buildSettings: [String : AnyObject]?) {
var modifiedSettings = buildSettings
if var dict = modifiedSettings {
var flagsObject: AnyObject? = dict["COMPILE_FLAGS"]
var flagArray = [String]()
if let flags: AnyObject = flagsObject {
if let array = flags as? [String] {
flagArray = array
}
} else {
dict["COMPLE_FLAGS"] = flagArray
}
flagArray.append("-fno-objc-arc")
}
addBuildFileWithReference(reference, buildSettings: modifiedSettings)
}
}
| mit |
yonaskolb/XcodeGen | Tests/Fixtures/TestProject/ExtensionKit Extension/EntryPoint.swift | 1 | 68 | import AppIntents
@main
struct EntryPoint: AppIntentsExtension {
}
| mit |
shengguoqiang/FTDKit | FTDKitDemo/FTDKitDemo/AppDelegate.swift | 1 | 2180 | //
// AppDelegate.swift
// FTDKitDemo
//
// Created by shengguoqiang on 16/12/6.
// Copyright © 2016年 盛世集团. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
JPIOS/JDanTang | JDanTang/JDanTang/Class/Tool(工具)/Common/NetworkTool.swift | 1 | 5398 | //
// NetworkTool.swift
// JDanTang
//
// Created by mac_KY on 2017/6/14.
// Copyright © 2017年 mac_KY. All rights reserved.
//
import UIKit
import Alamofire
import Foundation
import SwiftyJSON
import SVProgressHUD
class NetworkTool: NSObject {
/// 单利
static let shareNetworkTool = NetworkTool()
}
extension NetworkTool {
func getRequest(urlString: String, params: [String: Any], success: @escaping (_ response : JSON)-> (),failture: @escaping (_ error: Error)-> ()) {
let NewUrlString:String = BASE_URL+urlString
print("NewUrlString == " + NewUrlString)
SVProgressHUD.show(withStatus: "正在加载...")
Alamofire.request(NewUrlString, method: .get, parameters: params)
.responseJSON { (response) in
SVProgressHUD.dismiss()
guard response.result.isSuccess else {
SVProgressHUD.showError(withStatus: "加载失败...")
return
}
if let value = response.result.value {
let dict = JSON(value)
let code = dict["code"].intValue
let message = dict["message"].stringValue
guard code == RETURN_OK else {
SVProgressHUD.showInfo(withStatus: message)
return
}
// let data = dict["data"].dictionary
success(dict)
}
/* /*这里使用了闭包*/
//当请求后response是我们自定义的,这个变量用于接受服务器响应的信息
//使用switch判断请求是否成功,也就是response的result
switch response.result {
case .success(let value):
//当响应成功是,使用临时变量value接受服务器返回的信息并判断是否为[String: AnyObject]类型 如果是那么将其传给其定义方法中的success
//if let value = response.result.value as? [String: AnyObject] {
// success(value as! [String : AnyObject])
// }
let json = JSON(value)
print(json)
success(value as! [String : AnyObject])
case .failure(let error):
failture(error)
print("error:\(error)")*/
}
}
}
//MARK: - POST 请求
func postRequest(urlString : String, params : [String : Any], success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) {
Alamofire.request(urlString, method: HTTPMethod.post, parameters: params).responseJSON { (response) in
switch response.result{
case .success:
if let value = response.result.value as? [String: AnyObject] {
success(value)
let json = JSON(value)
print(json)
}
case .failure(let error):
failture(error)
print("error:\(error)")
}
}
}
//MARK: - 照片上传
///
/// - Parameters:
/// - urlString: 服务器地址
/// - params: ["flag":"","userId":""] - flag,userId 为必传参数
/// flag - 666 信息上传多张 -999 服务单上传 -000 头像上传
/// - data: image转换成Data
/// - name: fileName
/// - success:
/// - failture:
func upLoadImageRequest(urlString : String, params:[String:String], data: [Data], name: [String],success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()){
let headers = ["content-type":"multipart/form-data"]
Alamofire.upload(
multipartFormData: { multipartFormData in
//666多张图片上传
let flag = params["flag"]
let userId = params["userId"]
multipartFormData.append((flag?.data(using: String.Encoding.utf8)!)!, withName: "flag")
multipartFormData.append( (userId?.data(using: String.Encoding.utf8)!)!, withName: "userId")
for i in 0..<data.count {
multipartFormData.append(data[i], withName: "appPhoto", fileName: name[i], mimeType: "image/png")
}
},
to: urlString,
headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if let value = response.result.value as? [String: AnyObject]{
success(value)
let json = JSON(value)
print(json)
}
}
case .failure(let encodingError):
print(encodingError)
failture(encodingError)
}
}
)
}
| apache-2.0 |
sharkspeed/dororis | packages/swift/kitura/myFirstProject/Sources/main.swift | 1 | 215 | import Kitura
let router = Router()
let port = 8080
router.get("/") {
request, response, next in
response.send("Hello Kitura")
next()
}
Kitura.addHTTPServer(onPort: port, with: router)
Kitura.run() | bsd-2-clause |
fhchina/firefox-ios | Client/Frontend/Browser/LoginsHelper.swift | 1 | 13640 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import XCGLogger
import WebKit
private let log = Logger.browserLogger
private let SaveButtonTitle = NSLocalizedString("Save", comment: "Button to save the user's password")
private let NotNowButtonTitle = NSLocalizedString("Not now", comment: "Button to not save the user's password")
private let UpdateButtonTitle = NSLocalizedString("Update", comment: "Button to update the user's password")
private let CancelButtonTitle = NSLocalizedString("Cancel", comment: "Authentication prompt cancel button")
private let LogInButtonTitle = NSLocalizedString("Log in", comment: "Authentication prompt log in button")
class LoginsHelper: BrowserHelper {
private weak var browser: Browser?
private let profile: Profile
private var snackBar: SnackBar?
private static let MaxAuthenticationAttempts = 3
class func name() -> String {
return "LoginsHelper"
}
required init(browser: Browser, profile: Profile) {
self.browser = browser
self.profile = profile
if let path = NSBundle.mainBundle().pathForResource("LoginsHelper", ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String {
var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView!.configuration.userContentController.addUserScript(userScript)
}
}
}
func scriptMessageHandlerName() -> String? {
return "loginsManagerMessageHandler"
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
var res = message.body as! [String: String]
let type = res["type"]
if let url = browser?.url {
if type == "request" {
res["username"] = ""
res["password"] = ""
let login = Login.fromScript(url, script: res)
requestLogins(login, requestId: res["requestId"]!)
} else if type == "submit" {
setCredentials(Login.fromScript(url, script: res))
}
}
}
class func replace(base: String, keys: [String], replacements: [String]) -> NSMutableAttributedString {
var ranges = [NSRange]()
var string = base
for (index, key) in enumerate(keys) {
let replace = replacements[index]
let range = string.rangeOfString(key,
options: NSStringCompareOptions.LiteralSearch,
range: nil,
locale: nil)!
string.replaceRange(range, with: replace)
let nsRange = NSMakeRange(distance(string.startIndex, range.startIndex),
count(replace))
ranges.append(nsRange)
}
var attributes = [NSObject: AnyObject]()
attributes[NSFontAttributeName] = UIFont.systemFontOfSize(13, weight: UIFontWeightRegular)
attributes[NSForegroundColorAttributeName] = UIColor.darkGrayColor()
var attr = NSMutableAttributedString(string: string, attributes: attributes)
for (index, range) in enumerate(ranges) {
attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(13, weight: UIFontWeightMedium), range: range)
}
return attr
}
private func setCredentials(login: LoginData) {
if login.password.isEmpty {
log.debug("Empty password")
return
}
profile.logins
.getLoginsForProtectionSpace(login.protectionSpace, withUsername: login.username)
.uponQueue(dispatch_get_main_queue()) { res in
if let data = res.successValue {
log.debug("Found \(data.count) logins.")
for saved in data {
if let saved = saved {
if saved.password == login.password {
self.profile.logins.addUseOfLoginByGUID(saved.guid)
return
}
self.promptUpdateFromLogin(login: saved, toLogin: login)
return
}
}
}
self.promptSave(login)
}
}
private func promptSave(login: LoginData) {
let promptMessage: NSAttributedString
if let username = login.username {
let promptStringFormat = NSLocalizedString("Do you want to save the password for %@ on %@?", comment: "Prompt for saving a password. The first parameter is the username being saved. The second parameter is the hostname of the site.")
promptMessage = NSAttributedString(string: String(format: promptStringFormat, username, login.hostname))
} else {
let promptStringFormat = NSLocalizedString("Do you want to save the password on %@?", comment: "Prompt for saving a password with no username. The parameter is the hostname of the site.")
promptMessage = NSAttributedString(string: String(format: promptStringFormat, login.hostname))
}
if snackBar != nil {
browser?.removeSnackbar(snackBar!)
}
snackBar = TimerSnackBar(attrText: promptMessage,
img: UIImage(named: "lock_verified"),
buttons: [
SnackButton(title: SaveButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
self.profile.logins.addLogin(login)
}),
SnackButton(title: NotNowButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
return
})
])
browser?.addSnackbar(snackBar!)
}
private func promptUpdateFromLogin(login old: LoginData, toLogin new: LoginData) {
let guid = old.guid
let formatted: String
if let username = new.username {
let promptStringFormat = NSLocalizedString("Do you want to update the password for %@ on %@?", comment: "Prompt for updating a password. The first parameter is the username being saved. The second parameter is the hostname of the site.")
formatted = String(format: promptStringFormat, username, new.hostname)
} else {
let promptStringFormat = NSLocalizedString("Do you want to update the password on %@?", comment: "Prompt for updating a password with on username. The parameter is the hostname of the site.")
formatted = String(format: promptStringFormat, new.hostname)
}
let promptMessage = NSAttributedString(string: formatted)
if snackBar != nil {
browser?.removeSnackbar(snackBar!)
}
snackBar = TimerSnackBar(attrText: promptMessage,
img: UIImage(named: "lock_verified"),
buttons: [
SnackButton(title: UpdateButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
self.profile.logins.updateLoginByGUID(guid, new: new,
significant: new.isSignificantlyDifferentFrom(old))
}),
SnackButton(title: NotNowButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
return
})
])
browser?.addSnackbar(snackBar!)
}
private func requestLogins(login: LoginData, requestId: String) {
profile.logins.getLoginsForProtectionSpace(login.protectionSpace).uponQueue(dispatch_get_main_queue()) { res in
var jsonObj = [String: AnyObject]()
if let cursor = res.successValue {
log.debug("Found \(cursor.count) logins.")
jsonObj["requestId"] = requestId
jsonObj["name"] = "RemoteLogins:loginsFound"
jsonObj["logins"] = map(cursor, { $0!.toDict() })
}
let json = JSON(jsonObj)
let src = "window.__firefox__.logins.inject(\(json.toString()))"
self.browser?.webView?.evaluateJavaScript(src, completionHandler: { (obj, err) -> Void in
})
}
}
func handleAuthRequest(viewController: UIViewController, challenge: NSURLAuthenticationChallenge) -> Deferred<Result<LoginData>> {
// If there have already been too many login attempts, we'll just fail.
if challenge.previousFailureCount >= LoginsHelper.MaxAuthenticationAttempts {
return deferResult(LoginDataError(description: "Too many attempts to open site"))
}
var credential = challenge.proposedCredential
// If we were passed an initial set of credentials from iOS, try and use them.
if let proposed = credential {
if !(proposed.user?.isEmpty ?? true) {
if challenge.previousFailureCount == 0 {
return deferResult(Login.createWithCredential(credential!, protectionSpace: challenge.protectionSpace))
}
} else {
credential = nil
}
}
if let credential = credential {
// If we have some credentials, we'll show a prompt with them.
return promptForUsernamePassword(viewController, credentials: credential, protectionSpace: challenge.protectionSpace)
}
// Otherwise, try to look one up
let options = QueryOptions(filter: challenge.protectionSpace.host, filterType: .None, sort: .None)
return profile.logins.getLoginsForProtectionSpace(challenge.protectionSpace).bindQueue(dispatch_get_main_queue()) { res in
let credentials = res.successValue?[0]?.credentials
return self.promptForUsernamePassword(viewController, credentials: credentials, protectionSpace: challenge.protectionSpace)
}
}
private func promptForUsernamePassword(viewController: UIViewController, credentials: NSURLCredential?, protectionSpace: NSURLProtectionSpace) -> Deferred<Result<LoginData>> {
if protectionSpace.host.isEmpty {
println("Unable to show a password prompt without a hostname")
return deferResult(LoginDataError(description: "Unable to show a password prompt without a hostname"))
}
let deferred = Deferred<Result<LoginData>>()
let alert: UIAlertController
let title = NSLocalizedString("Authentication required", comment: "Authentication prompt title")
if !(protectionSpace.realm?.isEmpty ?? true) {
let msg = NSLocalizedString("A username and password are being requested by %@. The site says: %@", comment: "Authentication prompt message with a realm. First parameter is the hostname. Second is the realm string")
let formatted = NSString(format: msg, protectionSpace.host, protectionSpace.realm ?? "") as String
alert = UIAlertController(title: title, message: formatted, preferredStyle: UIAlertControllerStyle.Alert)
} else {
let msg = NSLocalizedString("A username and password are being requested by %@.", comment: "Authentication prompt message with no realm. Parameter is the hostname of the site")
let formatted = NSString(format: msg, protectionSpace.host) as String
alert = UIAlertController(title: title, message: formatted, preferredStyle: UIAlertControllerStyle.Alert)
}
// Add a button to log in.
let action = UIAlertAction(title: LogInButtonTitle,
style: UIAlertActionStyle.Default) { (action) -> Void in
let user = (alert.textFields?[0] as! UITextField).text
let pass = (alert.textFields?[1] as! UITextField).text
let login = Login.createWithCredential(NSURLCredential(user: user, password: pass, persistence: .ForSession), protectionSpace: protectionSpace)
deferred.fill(Result(success: login))
self.setCredentials(login)
}
alert.addAction(action)
// Add a cancel button.
let cancel = UIAlertAction(title: CancelButtonTitle, style: UIAlertActionStyle.Cancel) { (action) -> Void in
deferred.fill(Result(failure: LoginDataError(description: "Save password cancelled")))
}
alert.addAction(cancel)
// Add a username textfield.
alert.addTextFieldWithConfigurationHandler { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Username", comment: "Username textbox in Authentication prompt")
textfield.text = credentials?.user
}
// Add a password textfield.
alert.addTextFieldWithConfigurationHandler { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Password", comment: "Password textbox in Authentication prompt")
textfield.secureTextEntry = true
textfield.text = credentials?.password
}
viewController.presentViewController(alert, animated: true) { () -> Void in }
return deferred
}
}
| mpl-2.0 |
LongPF/FaceTube | FaceTube/Tool/Capture/FTPhotoFilters.swift | 1 | 1624 | //
// FTPhotoFilters.swift
// FaceTube
//
// Created by 龙鹏飞 on 2017/4/10.
// Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved.
//
import UIKit
/// 滤镜类
class FTPhotoFilters: NSObject {
var selectedFilter: CIFilter!
static let shared = FTPhotoFilters();
private override init() {
selectedFilter = FTPhotoFilters.defaultFilter()
}
public class func filterNames() -> [String] {
return [
"CIPhotoEffectChrome",
"CIPhotoEffectFade",
"CIPhotoEffectInstant",
"CIPhotoEffectMono",
"CIPhotoEffectNoir",
"CIPhotoEffectProcess",
"CIPhotoEffectTonal",
"CIPhotoEffectTransfer"
]
}
public class func filterDisplayNames() -> [String] {
var array: [String] = []
for filterName in FTPhotoFilters.filterNames(){
array.append(filterName.stringByMatchingRegex(regex: "CIPhotoEffect(.*)", capture: 1)!)
}
return array
}
public class func defaultFilter() -> CIFilter?{
let filterName: String = filterNames().first!
return CIFilter.init(name: filterName)!
}
public class func filterForDisplayName(displayName: String) -> CIFilter?{
for name in FTPhotoFilters.filterNames() {
if name.contains(displayName){
return CIFilter.init(name: name)
}
}
return nil
}
}
| mit |
exshin/PokePuzzler | PokePuzzler/Level.swift | 1 | 20391 | //
// Level.swift
// PokePuzzler
//
// Created by Eugene Chinveeraphan on 13/04/16.
// Copyright © 2016 Eugene Chinveeraphan. All rights reserved.
//
import Foundation
let NumColumns = 8
let NumRows = 8
let NumLevels = 1 // Excluding Level_0.json
class Level {
// MARK: Properties
// The 2D array that keeps track of where the Cookies are.
var cookies = Array2D<Cookie>(columns: NumColumns, rows: NumRows)
// The 2D array that contains the layout of the level.
fileprivate var tiles = Array2D<Tile>(columns: NumColumns, rows: NumRows)
// The list of swipes that result in a valid swap. Used to determine whether
// the player can make a certain swap, whether the board needs to be shuffled,
// and to generate hints.
var possibleSwaps = Set<Swap>()
var targetScore = 0
var maximumMoves = 0
var energySet: Array<String> = []
// MARK: Initialization
// Create a level by loading it from a file.
init(filename: String) {
guard let dictionary = Dictionary<String, AnyObject>.loadJSONFromBundle(filename: filename) else { return }
// The dictionary contains an array named "tiles". This array contains
// one element for each row of the level. Each of those row elements in
// turn is also an array describing the columns in that row. If a column
// is 1, it means there is a tile at that location, 0 means there is not.
guard let tilesArray = dictionary["tiles"] as? [[Int]] else { return }
// Loop through the rows...
for (row, rowArray) in tilesArray.enumerated() {
// Note: In Sprite Kit (0,0) is at the bottom of the screen,
// so we need to read this file upside down.
let tileRow = NumRows - row - 1
// Loop through the columns in the current r
for (column, value) in rowArray.enumerated() {
// If the value is 1, create a tile object.
if value == 1 {
tiles[column, tileRow] = Tile()
}
}
}
targetScore = dictionary["targetScore"] as! Int
maximumMoves = dictionary["moves"] as! Int
}
// MARK: Level Setup
// Fills up the level with new Cookie objects. The level is guaranteed free
// from matches at this point.
// Returns a set containing all the new Cookie objects.
func shuffle(energySet: Array<String>) -> Set<Cookie> {
var set: Set<Cookie>
repeat {
// Removes the old cookies and fills up the level with all new ones.
set = createInitialCookies(energySet: energySet)
self.energySet = energySet
// At the start of each turn we need to detect which cookies the player can
// actually swap. If the player tries to swap two cookies that are not in
// this set, then the game does not accept this as a valid move.
// This also tells you whether no more swaps are possible and the game needs
// to automatically reshuffle.
detectPossibleSwaps()
// print("possible swaps: \(possibleSwaps)")
// If there are no possible moves, then keep trying again until there are.
} while possibleSwaps.count == 0
return set
}
fileprivate func createInitialCookies(energySet: Array<String>) -> Set<Cookie> {
var set = Set<Cookie>()
// Loop through the rows and columns of the 2D array. Note that column 0,
// row 0 is in the bottom-left corner of the array.
for row in 0..<NumRows {
for column in 0..<NumColumns {
// Only make a new cookie if there is a tile at this spot.
if tiles[column, row] != nil {
// Pick the cookie type at random, and make sure that this never
// creates a chain of 3 or more. We want there to be 0 matches in
// the initial state.
var cookieType: CookieType
repeat {
cookieType = CookieType.random()
} while
// Only allow cookies based on the pokemon in play
!energySet.contains(cookieType.description) || (
(column >= 2 &&
cookies[column - 1, row]?.cookieType == cookieType &&
cookies[column - 2, row]?.cookieType == cookieType) ||
(row >= 2 &&
cookies[column, row - 1]?.cookieType == cookieType &&
cookies[column, row - 2]?.cookieType == cookieType))
// Create a new cookie and add it to the 2D array.
let cookie = Cookie(column: column, row: row, cookieType: cookieType)
cookies[column, row] = cookie
// Also add the cookie to the set so we can tell our caller about it.
set.insert(cookie)
}
}
}
return set
}
// MARK: Query the level
// Determines whether there's a tile at the specified column and row.
func tileAt(column: Int, row: Int) -> Tile? {
assert(column >= 0 && column < NumColumns)
assert(row >= 0 && row < NumRows)
return tiles[column, row]
}
// Returns the cookie at the specified column and row, or nil when there is none.
func cookieAt(column: Int, row: Int) -> Cookie? {
assert(column >= 0 && column < NumColumns)
assert(row >= 0 && row < NumRows)
return cookies[column, row]
}
// Determines whether the suggested swap is a valid one, i.e. it results in at
// least one new chain of 3 or more cookies of the same type.
func isPossibleSwap(_ swap: Swap) -> Bool {
return possibleSwaps.contains(swap)
}
fileprivate func hasChainAt(column: Int, row: Int) -> Bool {
// Here we do ! because we know there is a cookie here
let cookieType = cookies[column, row]!.cookieType
// Horizontal chain check
var horzLength = 1
// Left
var i = column - 1
// Here we do ? because there may be no cookie there; if there isn't then
// the loop will terminate because it is != cookieType. (So there is no
// need to check whether cookies[i, row] != nil.)
while i >= 0 && cookies[i, row]?.cookieType == cookieType {
i -= 1
horzLength += 1
}
// Right
i = column + 1
while i < NumColumns && cookies[i, row]?.cookieType == cookieType {
i += 1
horzLength += 1
}
if horzLength >= 3 { return true }
// Vertical chain check
var vertLength = 1
// Down
i = row - 1
while i >= 0 && cookies[column, i]?.cookieType == cookieType {
i -= 1
vertLength += 1
}
// Up
i = row + 1
while i < NumRows && cookies[column, i]?.cookieType == cookieType {
i += 1
vertLength += 1
}
return vertLength >= 3
}
// MARK: Swapping
// Swaps the positions of the two cookies from the Swap object.
func performSwap(_ swap: Swap) {
// Need to make temporary copies of these because they get overwritten.
let columnA = swap.cookieA.column
let rowA = swap.cookieA.row
let columnB = swap.cookieB.column
let rowB = swap.cookieB.row
// Swap the cookies. We need to update the array as well as the column
// and row properties of the Cookie objects, or they go out of sync!
cookies[columnA, rowA] = swap.cookieB
swap.cookieB.column = columnA
swap.cookieB.row = rowA
cookies[columnB, rowB] = swap.cookieA
swap.cookieA.column = columnB
swap.cookieA.row = rowB
}
// Recalculates which moves are valid.
func detectPossibleSwaps() {
var set = Set<Swap>()
for row in 0..<NumRows {
for column in 0..<NumColumns {
if let cookie = cookies[column, row] {
// Is it possible to swap this cookie with the one on the right?
// Note: don't need to check the last column.
if column < NumColumns - 1 {
// Have a cookie in this spot? If there is no tile, there is no cookie.
if let other = cookies[column + 1, row] {
// Swap them
cookies[column, row] = other
cookies[column + 1, row] = cookie
// Is either cookie now part of a chain?
if hasChainAt(column: column + 1, row: row) ||
hasChainAt(column: column, row: row) {
set.insert(Swap(cookieA: cookie, cookieB: other))
}
// Swap them back
cookies[column, row] = cookie
cookies[column + 1, row] = other
}
}
// Is it possible to swap this cookie with the one above?
// Note: don't need to check the last row.
if row < NumRows - 1 {
// Have a cookie in this spot? If there is no tile, there is no cookie.
if let other = cookies[column, row + 1] {
// Swap them
cookies[column, row] = other
cookies[column, row + 1] = cookie
// Is either cookie now part of a chain?
if hasChainAt(column: column, row: row + 1) ||
hasChainAt(column: column, row: row) {
set.insert(Swap(cookieA: cookie, cookieB: other))
}
// Swap them back
cookies[column, row] = cookie
cookies[column, row + 1] = other
}
}
}
}
}
possibleSwaps = set
}
fileprivate func calculateScores(for chains: Set<Chain>) {
// 3-chain is 3 pts, 4-chain is 4, 5-chain is 5, and so on
for chain in chains {
let chainType: String = chain.chainType.description
if chainType == "Horizontal" || chainType == "Vertical" {
chain.score = chain.length
} else {
chain.score = chain.length - 1
}
}
}
// MARK: Detecting Matches
fileprivate func detectHorizontalMatches() -> Set<Chain> {
// Contains the Cookie objects that were part of a horizontal chain.
// These cookies must be removed.
var set = Set<Chain>()
for row in 0..<NumRows {
// Don't need to look at last two columns.
var column = 0
while column < NumColumns-2 {
// If there is a cookie/tile at this position...
if let cookie = cookies[column, row] {
let matchType = cookie.cookieType
// And the next two columns have the same type...
if cookies[column + 1, row]?.cookieType == matchType &&
cookies[column + 2, row]?.cookieType == matchType {
// ...then add all the cookies from this chain into the set.
let chain = Chain(chainType: .horizontal)
repeat {
chain.add(cookie: cookies[column, row]!)
column += 1
} while column < NumColumns && cookies[column, row]?.cookieType == matchType
set.insert(chain)
continue
}
}
// Cookie did not match or empty tile, so skip over it.
column += 1
}
}
return set
}
// Same as the horizontal version but steps through the array differently.
fileprivate func detectVerticalMatches() -> Set<Chain> {
var set = Set<Chain>()
for column in 0..<NumColumns {
var row = 0
while row < NumRows-2 {
if let cookie = cookies[column, row] {
let matchType = cookie.cookieType
if cookies[column, row + 1]?.cookieType == matchType &&
cookies[column, row + 2]?.cookieType == matchType {
let chain = Chain(chainType: .vertical)
repeat {
chain.add(cookie: cookies[column, row]!)
row += 1
} while row < NumRows && cookies[column, row]?.cookieType == matchType
set.insert(chain)
continue
}
}
row += 1
}
}
return set
}
// Detects whether there are any chains of 3 or more cookies, and removes
// them from the level.
// Returns a set containing Chain objects, which describe the Cookies
// that were removed.
func removeMatches() -> Set<Chain> {
let horizontalChains = detectHorizontalMatches()
let verticalChains = detectVerticalMatches()
let specialChains = detectSpecialMatches(horizontalChains: horizontalChains, verticalChains: verticalChains)
// Note: to detect more advanced patterns such as an L shape, you can see
// whether a cookie is in both the horizontal & vertical chains sets and
// whether it is the first or last in the array (at a corner). Then you
// create a new Chain object with the new type and remove the other two.
removeCookies(horizontalChains)
removeCookies(verticalChains)
if specialChains.count == 0 {
calculateScores(for: horizontalChains)
calculateScores(for: verticalChains)
return horizontalChains.union(verticalChains)
} else {
calculateScores(for: specialChains)
return specialChains
}
}
fileprivate func detectSpecialMatches(horizontalChains: Set<Chain>, verticalChains: Set<Chain>) -> Set<Chain> {
var specialChains = Set<Chain>()
var hcookies: Array<Cookie> = []
var vcookies: Array<Cookie> = []
for chains in verticalChains {
for cookie in chains.cookies {
vcookies.append(cookie)
}
}
for chains in horizontalChains {
for cookie in chains.cookies {
hcookies.append(cookie)
}
}
let vcookieSet: Set<Cookie> = Set(vcookies)
let hcookieSet: Set<Cookie> = Set(hcookies)
for cookie in vcookieSet.intersection(hcookieSet) {
// Check each horizontal chain
for hchain in horizontalChains {
if cookie == hchain.firstCookie() || cookie == hchain.lastCookie() {
for vchain in verticalChains {
if cookie == vchain.firstCookie() || cookie == hchain.lastCookie() {
// L Shape Chain
let chain = Chain(chainType: .lshape)
// Add cookies from horizontal chain
for hchainCookie in hchain.cookies {
chain.add(cookie: hchainCookie)
}
// Add cookies from vertical chain
for vchainCookie in vchain.cookies {
chain.add(cookie: vchainCookie)
}
specialChains.insert(chain)
break
} else if vchain.containsCookie(cookie: cookie) {
// T Shape Cookie (T)
let chain = Chain(chainType: .tshape)
// Add cookies from horizontal chain
for hchainCookie in hchain.cookies {
chain.add(cookie: hchainCookie)
}
// Add cookies from vertical chain
for vchainCookie in vchain.cookies {
chain.add(cookie: vchainCookie)
}
specialChains.insert(chain)
break
}
}
hchain.chainType = .lshape
} else if hchain.containsCookie(cookie: cookie) {
// T Shape on the middle horizontal cookie
for vchain in verticalChains {
if cookie == vchain.firstCookie() || cookie == hchain.lastCookie() {
// T Shape Cookie (T)
let chain = Chain(chainType: .tshape)
// Add cookies from horizontal chain
for hchainCookie in hchain.cookies {
chain.add(cookie: hchainCookie)
}
// Add cookies from vertical chain
for vchainCookie in vchain.cookies {
chain.add(cookie: vchainCookie)
}
specialChains.insert(chain)
break
} else if vchain.containsCookie(cookie: cookie) {
// T Shape (+)
let chain = Chain(chainType: .tshape)
// Add cookies from horizontal chain
for hchainCookie in hchain.cookies {
chain.add(cookie: hchainCookie)
}
// Add cookies from vertical chain
for vchainCookie in vchain.cookies {
chain.add(cookie: vchainCookie)
}
specialChains.insert(chain)
break
}
}
}
}
}
return specialChains
}
fileprivate func removeCookies(_ chains: Set<Chain>) {
for chain in chains {
for cookie in chain.cookies {
if cookies[cookie.column, cookie.row] != nil {
cookies[cookie.column, cookie.row] = nil
}
}
}
}
func removeCookie(_ cookie: Cookie) {
cookies[cookie.column, cookie.row] = nil
}
// MARK: Detecting Holes
// Detects where there are holes and shifts any cookies down to fill up those
// holes. In effect, this "bubbles" the holes up to the top of the column.
// Returns an array that contains a sub-array for each column that had holes,
// with the Cookie objects that have shifted. Those cookies are already
// moved to their new position. The objects are ordered from the bottom up.
func fillHoles() -> [[Cookie]] {
var columns = [[Cookie]]() // you can also write this Array<Array<Cookie>>
// Loop through the rows, from bottom to top. It's handy that our row 0 is
// at the bottom already. Because we're scanning from bottom to top, this
// automatically causes an entire stack to fall down to fill up a hole.
// We scan one column at a time.
for column in 0..<NumColumns {
var array = [Cookie]()
for row in 0..<NumRows {
// If there is a tile at this position but no cookie, then there's a hole.
if tiles[column, row] != nil && cookies[column, row] == nil {
// Scan upward to find a cookie.
for lookup in (row + 1)..<NumRows {
if let cookie = cookies[column, lookup] {
// Swap that cookie with the hole.
cookies[column, lookup] = nil
cookies[column, row] = cookie
cookie.row = row
// For each column, we return an array with the cookies that have
// fallen down. Cookies that are lower on the screen are first in
// the array. We need an array to keep this order intact, so the
// animation code can apply the correct kind of delay.
array.append(cookie)
// Don't need to scan up any further.
break
}
}
}
}
if !array.isEmpty {
columns.append(array)
}
}
return columns
}
// Where necessary, adds new cookies to fill up the holes at the top of the
// columns.
// Returns an array that contains a sub-array for each column that had holes,
// with the new Cookie objects. Cookies are ordered from the top down.
func topUpCookies() -> [[Cookie]] {
var columns = [[Cookie]]()
var cookieType: CookieType = .unknown
// Detect where we have to add the new cookies. If a column has X holes,
// then it also needs X new cookies. The holes are all on the top of the
// column now, but the fact that there may be gaps in the tiles makes this
// a little trickier.
for column in 0..<NumColumns {
var array = [Cookie]()
// This time scan from top to bottom. We can end when we've found the
// first cookie.
var row = NumRows - 1
while row >= 0 && cookies[column, row] == nil {
// Found a hole?
if tiles[column, row] != nil {
// Randomly create a new cookie type. The only restriction is that
// it cannot be equal to the previous type. This prevents too many
// "freebie" matches.
var newCookieType: CookieType
repeat {
newCookieType = CookieType.random()
} while newCookieType == cookieType || !energySet.contains(newCookieType.description)
cookieType = newCookieType
// Create a new cookie and add it to the array for this column.
let cookie = Cookie(column: column, row: row, cookieType: cookieType)
cookies[column, row] = cookie
array.append(cookie)
}
row -= 1
}
if !array.isEmpty {
columns.append(array)
}
}
return columns
}
}
| apache-2.0 |
wendellantildes/SideMenu | SideMenuUITests/SideMenuUITests.swift | 1 | 1280 | //
// SideMenuUITests.swift
// SideMenuUITests
//
// Created by Wendell Antildes M Sampaio on 29/03/2016.
// Copyright © 2016 Wendell Antildes M Sampaio. All rights reserved.
//
import XCTest
class SideMenuUITests: 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.
}
}
| mit |
JohnEstropia/CoreStore | Sources/ObjectProxy.swift | 1 | 8333 | //
// ObjectProxy.swift
// CoreStore
//
// Copyright © 2020 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import CoreData
import Foundation
// MARK: - ObjectProxy
/**
An `ObjectProxy` is only used when overriding getters and setters for `CoreStoreObject` properties. Custom getters and setters are implemented as a closure that "overrides" the default property getter/setter. The closure receives an `ObjectProxy<O>`, which acts as a fast, type-safe KVC interface for `CoreStoreObject`. The reason a `CoreStoreObject` instance is not passed directly is because the Core Data runtime is not aware of `CoreStoreObject` properties' static typing, and so loading those info every time KVO invokes this accessor method incurs a heavy performance hit (especially in KVO-heavy operations such as `ListMonitor` observing.) When accessing the property value from `ObjectProxy<O>`, make sure to use `ObjectProxy<O>.$property.primitiveValue` instead of `ObjectProxy<O>.$property.value`, which would execute the same accessor again recursively.
*/
@dynamicMemberLookup
public struct ObjectProxy<O: CoreStoreObject> {
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, V>(dynamicMember member: KeyPath<O, FieldContainer<OBase>.Stored<V>>) -> FieldProxy<V> {
return .init(rawObject: self.rawObject, keyPath: member)
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, V>(dynamicMember member: KeyPath<O, FieldContainer<OBase>.Virtual<V>>) -> FieldProxy<V> {
return .init(rawObject: self.rawObject, keyPath: member)
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, V>(dynamicMember member: KeyPath<O, FieldContainer<OBase>.Coded<V>>) -> FieldProxy<V> {
return .init(rawObject: self.rawObject, keyPath: member)
}
// MARK: Internal
internal let rawObject: CoreStoreManagedObject
internal init(_ rawObject: CoreStoreManagedObject) {
self.rawObject = rawObject
}
// MARK: - FieldProxy
public struct FieldProxy<V> {
// MARK: Public
/**
Returns the value for the specified property from the object’s private internal storage.
This method is used primarily to implement custom accessor methods that need direct access to the object's private storage.
*/
public var primitiveValue: V? {
get {
return self.getPrimitiveValue()
}
nonmutating set {
self.setPrimitiveValue(newValue)
}
}
/**
Returns the value for the property identified by a given key.
*/
public var value: V {
get {
return self.getValue()
}
nonmutating set {
self.setValue(newValue)
}
}
// MARK: Internal
internal init<OBase>(rawObject: CoreStoreManagedObject, keyPath: KeyPath<O, FieldContainer<OBase>.Stored<V>>) {
self.init(rawObject: rawObject, field: O.meta[keyPath: keyPath])
}
internal init<OBase>(rawObject: CoreStoreManagedObject, keyPath: KeyPath<O, FieldContainer<OBase>.Virtual<V>>) {
self.init(rawObject: rawObject, field: O.meta[keyPath: keyPath])
}
internal init<OBase>(rawObject: CoreStoreManagedObject, keyPath: KeyPath<O, FieldContainer<OBase>.Coded<V>>) {
self.init(rawObject: rawObject, field: O.meta[keyPath: keyPath])
}
internal init<OBase>(rawObject: CoreStoreManagedObject, field: FieldContainer<OBase>.Stored<V>) {
let keyPathString = field.keyPath
self.getValue = {
return type(of: field).read(field: field, for: rawObject) as! V
}
self.setValue = {
type(of: field).modify(field: field, for: rawObject, newValue: $0)
}
self.getPrimitiveValue = {
return V.cs_fromFieldStoredNativeType(
rawObject.primitiveValue(forKey: keyPathString) as! V.FieldStoredNativeType
)
}
self.setPrimitiveValue = {
rawObject.willChangeValue(forKey: keyPathString)
defer {
rawObject.didChangeValue(forKey: keyPathString)
}
rawObject.setPrimitiveValue(
$0.cs_toFieldStoredNativeType(),
forKey: keyPathString
)
}
}
internal init<OBase>(rawObject: CoreStoreManagedObject, field: FieldContainer<OBase>.Virtual<V>) {
let keyPathString = field.keyPath
self.getValue = {
return type(of: field).read(field: field, for: rawObject) as! V
}
self.setValue = {
type(of: field).modify(field: field, for: rawObject, newValue: $0)
}
self.getPrimitiveValue = {
switch rawObject.primitiveValue(forKey: keyPathString) {
case let value as V:
return value
case nil,
is NSNull,
_? /* any other unrelated type */ :
return nil
}
}
self.setPrimitiveValue = {
rawObject.setPrimitiveValue(
$0,
forKey: keyPathString
)
}
}
internal init<OBase>(rawObject: CoreStoreManagedObject, field: FieldContainer<OBase>.Coded<V>) {
let keyPathString = field.keyPath
self.getValue = {
return type(of: field).read(field: field, for: rawObject) as! V
}
self.setValue = {
type(of: field).modify(field: field, for: rawObject, newValue: $0)
}
self.getPrimitiveValue = {
switch rawObject.primitiveValue(forKey: keyPathString) {
case let valueBox as Internals.AnyFieldCoder.TransformableDefaultValueCodingBox:
rawObject.setPrimitiveValue(valueBox.value, forKey: keyPathString)
return valueBox.value as? V
case let value as V:
return value
case nil,
is NSNull,
_? /* any other unrelated type */ :
return nil
}
}
self.setPrimitiveValue = {
rawObject.willChangeValue(forKey: keyPathString)
defer {
rawObject.didChangeValue(forKey: keyPathString)
}
rawObject.setPrimitiveValue(
$0,
forKey: keyPathString
)
}
}
// MARK: Private
private let getValue: () -> V
private let setValue: (V) -> Void
private let getPrimitiveValue: () -> V?
private let setPrimitiveValue: (V?) -> Void
}
}
| mit |
qmathe/Confetti | Viewpoint/App.swift | 1 | 620 | /**
Copyright (C) 2017 Quentin Mathe
Date: July 2017
License: MIT
*/
import Foundation
protocol App {
associatedtype
public init(value: T)
}
extension Viewpoint<T> {
// MARK: - Initialization
/// Initializes a new viewpoint to present the given value.
public init(value: T) {
self.value = value
self.objectGraph = objectGraph
}
// MARK: - Generating Item Representation
/// Must be overriden to return a custom item tree.
///
/// By default, causes a fatal error.
///
/// You must never call this method directly.
open func generate() -> Item {
fatalError("Must be overriden")
}
}
| mit |
Fenrikur/ef-app_ios | EurofurenceTests/Director/Module Interactions/WhenMessagesModuleRequestsUserResolution_DirectorShould.swift | 1 | 1250 | import XCTest
class WhenMessagesModuleRequestsUserResolution_DirectorShould: XCTestCase {
var context: ApplicationDirectorTestBuilder.Context!
var userResolved: Bool!
override func setUp() {
super.setUp()
context = ApplicationDirectorTestBuilder().build()
context.navigateToTabController()
context.newsModule.simulatePrivateMessagesDisplayRequested()
context.messages.simulateResolutionForUser({ self.userResolved = $0 })
}
func testTellMessagesModuleResolutionFailedWhenLoginCancelled() {
context.loginModule.simulateLoginCancelled()
XCTAssertFalse(userResolved)
}
func testNotTellMessagesModuleResolutionFailedBeforeCancellation() {
XCTAssertNil(userResolved)
}
func testTellMessagesModuleResolutionSucceededWhenLoginSucceeded() {
context.loginModule.simulateLoginSucceeded()
XCTAssertTrue(userResolved)
}
func testNotTellMessagesModuleResolutionSucceededBeforeLoginSucceeds() {
XCTAssertNil(userResolved)
}
func testDismissLoginModuleWhenLoginSucceeds() {
context.loginModule.simulateLoginSucceeded()
XCTAssertTrue(context.tabModule.stubInterface.didDismissViewController)
}
}
| mit |
ryuichis/swift-lint | Sources/Lint/Rule/RedundantIfStatementRule.swift | 2 | 3305 | /*
Copyright 2017, 2019 Ryuichi Laboratories 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 Foundation
import AST
class RedundantIfStatementRule: RuleBase, ASTVisitorRule {
let name = "Redundant If Statement"
var description: String? {
return """
This rule detects three types of redundant if statements:
- then-block and else-block are returning true/false or false/true respectively;
- then-block and else-block are the same constant;
- then-block and else-block are the same variable expression.
They are usually introduced by mistake, and should be simplified or removed.
"""
}
var examples: [String]? {
return [
"""
if a == b {
return true
} else {
return false
}
// return a == b
""",
"""
if a == b {
return false
} else {
return true
}
// return a != b
""",
"""
if a == b {
return true
} else {
return true
}
// return true
""",
"""
if a == b {
return foo
} else {
return foo
}
// return foo
""",
]
}
let category = Issue.Category.badPractice
private func emitIssue(_ ifStmt: IfStatement, _ suggestion: String) {
emitIssue(
ifStmt.sourceRange,
description: "if statement is redundant and can be \(suggestion)")
}
func visit(_ ifStmt: IfStatement) throws -> Bool {
guard ifStmt.areAllConditionsExpressions,
let (thenStmt, elseStmt) = ifStmt.thenElseStmts
else {
return true
}
// check then and else block each has one return statement that has expression
guard let thenReturn = thenStmt as? ReturnStatement,
let elseReturn = elseStmt as? ReturnStatement,
let thenExpr = thenReturn.expression,
let elseExpr = elseReturn.expression
else {
return true
}
if let suggestion = checkRedundant(
trueExpression: thenExpr, falseExpression: elseExpr)
{
emitIssue(ifStmt, suggestion)
}
return true
}
}
fileprivate extension IfStatement {
var thenElseStmts: (Statement, Statement)? {
// check if both then-block and else-block exist and have one and only one statement
guard codeBlock.statements.count == 1,
let elseClause = elseClause,
case .else(let elseBlock) = elseClause,
elseBlock.statements.count == 1
else {
return nil
}
let thenStmt = codeBlock.statements[0]
let elseStmt = elseBlock.statements[0]
return (thenStmt, elseStmt)
}
var areAllConditionsExpressions: Bool {
return conditionList.filter({
if case .expression = $0 {
return false
}
return true
}).isEmpty
}
}
| apache-2.0 |
rwbutler/TypographyKit | Example/TypographyKit/UIKitViewController.swift | 1 | 830 | //
// UIKitViewController.swift
// TypographyKit
//
// Created by Ross Butler on 05/09/2017.
// Copyright (c) 2017 Ross Butler. All rights reserved.
//
import Foundation
import UIKit
class UIKitViewController: UIViewController {
@IBOutlet weak var attributedStringButton: UIButton!
@IBOutlet weak var attributedStringLabel: UILabel!
@IBOutlet weak var colorsButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
title = "UIKit Example"
view.backgroundColor = .background
let buttonText = attributedStringButton.titleLabel?.attributedText
attributedStringButton.attributedText(buttonText, style: .paragraph)
let labelText = attributedStringLabel.attributedText
attributedStringLabel.attributedText(labelText, style: .paragraph)
}
}
| mit |
WeHUD/app | weHub-ios/Gzone_App/Pods/XLPagerTabStrip/Sources/PagerTabStripError.swift | 6 | 1350 | // PagerTabStripError.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.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
public enum PagerTabStripError: Error {
case viewControllerNotContainedInPagerTabStrip
}
| bsd-3-clause |
Subsets and Splits