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 |
---|---|---|---|---|---|
RevenueCat/purchases-ios | Tests/UnitTests/Mocks/MockUserDefaults.swift | 1 | 2085 | //
// Created by RevenueCat on 2/3/20.
// Copyright (c) 2020 Purchases. All rights reserved.
//
import Foundation
class MockUserDefaults: UserDefaults {
var stringForKeyCalledValue: String?
var setObjectForKeyCalledValue: String?
var setObjectForKeyCallCount: Int = 0
var removeObjectForKeyCalledValues: [String] = []
var dataForKeyCalledValue: String?
var objectForKeyCalledValue: String?
var dictionaryForKeyCalledValue: String?
var setBoolForKeyCalledValue: String?
var setValueForKeyCalledValue: String?
var mockValues: [String: Any] = [:]
override func string(forKey defaultName: String) -> String? {
stringForKeyCalledValue = defaultName
return mockValues[defaultName] as? String
}
override func removeObject(forKey defaultName: String) {
removeObjectForKeyCalledValues.append(defaultName)
mockValues.removeValue(forKey: defaultName)
}
override func set(_ value: Any?, forKey defaultName: String) {
setObjectForKeyCallCount += 1
setObjectForKeyCalledValue = defaultName
mockValues[defaultName] = value
}
override func data(forKey defaultName: String) -> Data? {
dataForKeyCalledValue = defaultName
return mockValues[defaultName] as? Data
}
override func object(forKey defaultName: String) -> Any? {
objectForKeyCalledValue = defaultName
return mockValues[defaultName]
}
override func set(_ value: Bool, forKey defaultName: String) {
setValueForKeyCalledValue = defaultName
mockValues[defaultName] = value
}
override func dictionary(forKey defaultName: String) -> [String: Any]? {
dictionaryForKeyCalledValue = defaultName
return mockValues[defaultName] as? [String: Any]
}
override func dictionaryRepresentation() -> [String: Any] { mockValues }
override func synchronize() -> Bool {
// Nothing to do
return false
}
override func removePersistentDomain(forName domainName: String) {
mockValues = [:]
}
}
| mit |
CGRrui/TestKitchen_1606 | TestKitchen/TestKitchen/classes/mall/homePage/controller/MallViewController.swift | 1 | 881 | //
// MallViewController.swift
// TestKitchen
//
// Created by Rui on 16/8/15.
// Copyright © 2016年 Rui. All rights reserved.
//
import UIKit
//商城界面
class MallViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
hiralin/MultiAgentSimulation | MultiAgentSimulation/AppDelegate.swift | 1 | 919 | //
// AppDelegate.swift
// MultiAgentSimulation
//
// Created by Tokuya HIRAIZUMI on 2016/10/03.
// Copyright © 2016年 Tokuya HIRAIZUMI. 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) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
| mit |
GrandCentralBoard/GrandCentralBoard | Pods/Operations/Sources/Features/Shared/CloudCapability.swift | 2 | 10402 | //
// CloudCapability.swift
// Operations
//
// Created by Daniel Thorpe on 02/10/2015.
// Copyright © 2015 Dan Thorpe. All rights reserved.
//
import CloudKit
/**
# Cloud Status
Value represents the current CloudKit status for the user.
CloudKit has a relatively convoluted status API.
First, we must check the user's accout status, i.e. are
they logged in to iCloud.
Next, we check the status for the application permissions.
Then, we might need to request the application permissions.
*/
public struct CloudStatus: AuthorizationStatusType {
/// - returns: the CKAccountStatus
public let account: CKAccountStatus
/// - returns: the CKApplicationPermissionStatus?
public let permissions: CKApplicationPermissionStatus?
/// - returns: any NSError?
public let error: NSError?
init(account: CKAccountStatus, permissions: CKApplicationPermissionStatus? = .None, error: NSError? = .None) {
self.account = account
self.permissions = permissions
self.error = error
}
/**
Determine whether the application permissions have been met.
This method takes into account, any errors received from CloudKit,
the account status, application permission status, and the required
application permissions.
*/
public func isRequirementMet(requirement: CKApplicationPermissions) -> Bool {
if let _ = error {
return false
}
switch (requirement, account, permissions) {
case ([], .Available, _):
return true
case (_, .Available, .Some(.Granted)) where requirement != []:
return true
default:
return false
}
}
}
/**
A refined CapabilityRegistrarType for Capability.Cloud. This
protocol defines two functions which the registrar uses to get
the current authorization status and request access.
*/
public protocol CloudContainerRegistrarType: CapabilityRegistrarType {
var containerIdentifier: String? { get }
var cloudKitContainer: CKContainer! { get }
/**
Provide an instance of Self with the given identifier. This is
because we need to determined the capability of a specific cloud
kit container.
*/
static func containerWithIdentifier(identifier: String?) -> Self
/**
Get the account status, a CKAccountStatus.
- parameter completionHandler: a completion handler which receives the account status.
*/
func opr_accountStatusWithCompletionHandler(completionHandler: (CKAccountStatus, NSError?) -> Void)
/**
Get the application permission, a CKApplicationPermissions.
- parameter applicationPermission: the CKApplicationPermissions
- parameter completionHandler: a CKApplicationPermissionBlock closure
*/
func opr_statusForApplicationPermission(applicationPermission: CKApplicationPermissions, completionHandler: CKApplicationPermissionBlock)
/**
Request the application permission, a CKApplicationPermissions.
- parameter applicationPermission: the CKApplicationPermissions
- parameter completionHandler: a CKApplicationPermissionBlock closure
*/
func opr_requestApplicationPermission(applicationPermission: CKApplicationPermissions, completionHandler: CKApplicationPermissionBlock)
}
/**
The Cloud capability, which generic over CloudContainerRegistrarType.
Framework consumers should not use this directly, but instead
use Capability.Cloud. So that its usage is like this:
```swift
GetAuthorizationStatus(Capability.Cloud()) { status in
// check the status etc.
}
```
- see: Capability.Cloud
*/
public class CloudCapability: NSObject, CapabilityType {
/// - returns: a String, the name of the capability
public let name: String
/// - returns: a CKApplicationPermissions, the required permissions for the container
public let requirement: CKApplicationPermissions
var hasRequirements: Bool {
return requirement != []
}
internal let containerId: String?
internal var storedRegistrar: CloudContainerRegistrarType? = .None
internal var registrar: CloudContainerRegistrarType {
get {
storedRegistrar = storedRegistrar ?? CloudContainerRegistrar.containerWithIdentifier(containerId)
return storedRegistrar!
}
}
public init(permissions: CKApplicationPermissions = [], containerId: String? = .None) {
self.name = "Cloud"
self.requirement = permissions
self.containerId = containerId
super.init()
}
/**
Initialize the capability. By default, it requires no extra application permissions.
Note that framework consumers should not initialized this class directly, but instead
use Capability.Cloud, which is a typealias of CloudCapability, and has a slightly
different initializer to allow supplying the CloudKit container identifier.
- see: Capability.Cloud
- see: CloudCapability
- parameter requirement: the required EKEntityType, defaults to .Event
- parameter registrar: the registrar to use. Defauls to creating a Registrar.
*/
public required init(_ requirement: CKApplicationPermissions = []) {
self.name = "Cloud"
self.requirement = requirement
self.containerId = .None
super.init()
}
/// - returns: true, CloudKit is always available
public func isAvailable() -> Bool {
return true
}
/**
Get the current authorization status of CloudKit from the Registrar.
- parameter completion: a CloudStatus -> Void closure.
*/
public func authorizationStatus(completion: CloudStatus -> Void) {
verifyAccountStatus(completion: completion)
}
/**
Requests authorization to the Cloud Kit container from the Registrar.
- parameter completion: a dispatch_block_t
*/
public func requestAuthorizationWithCompletion(completion: dispatch_block_t) {
verifyAccountStatus(true) { _ in
completion()
}
}
func verifyAccountStatus(shouldRequest: Bool = false, completion: CloudStatus -> Void) {
registrar.opr_accountStatusWithCompletionHandler { status, error in
switch (status, self.hasRequirements) {
case (.Available, true):
self.verifyPermissions(shouldRequest, completion: completion)
default:
completion(CloudStatus(account: status, permissions: .None, error: error))
}
}
}
func verifyPermissions(shouldRequest: Bool = false, completion: CloudStatus -> Void) {
registrar.opr_statusForApplicationPermission(requirement) { status, error in
switch (status, shouldRequest) {
case (.InitialState, true):
self.requestPermissionsWithCompletion(completion)
default:
completion(CloudStatus(account: .Available, permissions: status, error: error))
}
}
}
func requestPermissionsWithCompletion(completion: CloudStatus -> Void) {
dispatch_async(Queue.Main.queue) {
self.registrar.opr_requestApplicationPermission(self.requirement) { status, error in
completion(CloudStatus(account: .Available, permissions: status, error: error))
}
}
}
}
/**
A registrar for CKContainer.
*/
public final class CloudContainerRegistrar: NSObject, CloudContainerRegistrarType {
/// Provide a CloudContainerRegistrar for a CKContainer with the given identifier.
public static func containerWithIdentifier(identifier: String?) -> CloudContainerRegistrar {
let container = CloudContainerRegistrar()
container.containerIdentifier = identifier
if let id = identifier {
container.cloudKitContainer = CKContainer(identifier: id)
}
return container
}
public private(set) var containerIdentifier: String? = .None
public private(set) lazy var cloudKitContainer: CKContainer! = CKContainer.defaultContainer()
/**
Get the account status, a CKAccountStatus.
- parameter completionHandler: a completion handler which receives the account status.
*/
public func opr_accountStatusWithCompletionHandler(completionHandler: (CKAccountStatus, NSError?) -> Void) {
cloudKitContainer.accountStatusWithCompletionHandler(completionHandler)
}
/**
Get the application permission, a CKApplicationPermissions.
- parameter applicationPermission: the CKApplicationPermissions
- parameter completionHandler: a CKApplicationPermissionBlock closure
*/
public func opr_statusForApplicationPermission(applicationPermission: CKApplicationPermissions, completionHandler: CKApplicationPermissionBlock) {
cloudKitContainer.statusForApplicationPermission(applicationPermission, completionHandler: completionHandler)
}
/**
Request the application permission, a CKApplicationPermissions.
- parameter applicationPermission: the CKApplicationPermissions
- parameter completionHandler: a CKApplicationPermissionBlock closure
*/
public func opr_requestApplicationPermission(applicationPermission: CKApplicationPermissions, completionHandler: CKApplicationPermissionBlock) {
cloudKitContainer.requestApplicationPermission(applicationPermission, completionHandler: completionHandler)
}
}
extension Capability {
/**
# Capability.Cloud
This type represents the app's permission to access a particular CKContainer.
For framework consumers - use with `GetAuthorizationStatus`, `Authorize` and
`AuthorizedFor`.
For example, authorize usage of the default container
```swift
Authorize(Capability.Cloud()) { available, status in
// etc
}
```
For example, authorize usage of another container;
```swift
Authorize(Capability.Cloud(containerId: "iCloud.com.myapp.my-container-id")) { available, status in
// etc
}
```
*/
public typealias Cloud = CloudCapability
}
extension CloudCapability {
/// - returns: the `CKContainer`
public var container: CKContainer {
return registrar.cloudKitContainer
}
}
@available(*, unavailable, renamed="AuthorizedFor(Cloud())")
public typealias CloudContainerCondition = AuthorizedFor<Capability.Cloud>
| gpl-3.0 |
davidisaaclee/VectorSwift | Example/Tests/CustomVectorSpec.swift | 1 | 3387 | import Quick
import Nimble
import VectorSwift
class CustomVector2TypeSpec: QuickSpec {
typealias VectorType = CustomVector2
override func spec() {
describe("Custom vectors") {
let pt = VectorType(collection: [3, 4])
it("can initialize from collections") {
expect(CustomVector2(x: 0, y: 1)).to(equal(CustomVector2(x: 0, y: 1)))
expect(VectorType(collection: [1, 2])).to(equal(CustomVector2(x: 1, y: 2)))
expect(VectorType(collection: [-1, -2, 3])).to(equal(CustomVector2(x: -1, y: -2)))
}
it("adopts CollectionType") {
expect(pt[0]).to(equal(pt.x))
expect(pt[1]).to(equal(pt.y))
}
it("calculates magnitude") {
expect(pt.magnitude).to(equal(5))
}
it("can add") {
let pt2 = VectorType(collection: [1, -2])
expect(pt + pt2).to(equal(VectorType(collection: [4, 2])))
}
it("can scale") {
expect(pt * Float(3)).to(equal(VectorType(collection: [9, 12])))
expect(pt * Float(-1)).to(equal(VectorType(collection: [-3, -4])))
}
it("can get unit vector") {
expect(VectorType(collection: [10, 0]).unit).to(equal(VectorType(collection: [1, 0])))
expect(VectorType(collection: [0, 10]).unit).to(equal(VectorType(collection: [0, 1])))
let u = VectorType(collection: [3, 4]).unit
expect(u.x).to(beCloseTo(0.6))
expect(u.y).to(beCloseTo(0.8))
}
it("can negate") {
expect(pt.negative).to(equal(VectorType(collection: [-pt.x, -pt.y])))
}
it("can subtract") {
expect(pt - VectorType(collection: [-2, 4])).to(equal(VectorType(collection: [pt.x + 2, pt.y - 4])))
}
}
}
}
class CustomVector3TypeSpec: QuickSpec {
typealias VectorType = CustomVector3
override func spec() {
describe("Custom vectors") {
let pt = VectorType(collection: [3, 4, 5])
it("can initialize from collections") {
expect(VectorType(collection: [1, 2, 3])).to(equal(VectorType(x: 1, y: 2, z: 3)))
expect(VectorType(collection: [-1, -2, 3, 4])).to(equal(VectorType(x: -1, y: -2, z: 3)))
}
it("adopts CollectionType") {
expect(pt[0]).to(equal(pt.x))
expect(pt[1]).to(equal(pt.y))
expect(pt[2]).to(equal(pt.z))
}
it("calculates magnitude") {
expect(pt.magnitude).to(beCloseTo(5 * Float(2.0).toThePowerOf(0.5)))
}
it("can add") {
let pt2 = VectorType(collection: [1, -2, 3])
expect(pt + pt2).to(equal(VectorType(collection: [3 + 1, 4 + -2, 5 + 3])))
}
it("can scale") {
expect(pt * Float(3)).to(equal(VectorType(collection: [9, 12, 15])))
expect(pt * Float(-1)).to(equal(VectorType(collection: [-3, -4, -5])))
}
it("can get unit vector") {
expect(VectorType(collection: [10, 0, 0]).unit).to(equal(VectorType(collection: [1, 0, 0])))
expect(VectorType(collection: [0, 10, 0]).unit).to(equal(VectorType(collection: [0, 1, 0])))
expect(VectorType(collection: [0, 0, 10]).unit).to(equal(VectorType(collection: [0, 0, 1])))
let u = VectorType(collection: [3, 4, 5]).unit
expect(u.x).to(beCloseTo(3.0 / (5.0 * pow(2.0, 0.5))))
expect(u.y).to(beCloseTo(2.0 * pow(2.0, 0.5) / 5.0))
expect(u.z).to(beCloseTo(1.0 / pow(2.0, 0.5)))
}
it("can negate") {
expect(pt.negative).to(equal(VectorType(collection: [-pt.x, -pt.y, -pt.z])))
}
it("can subtract") {
expect(pt - VectorType(collection: [-2, 4, 1])).to(equal(VectorType(collection: [pt.x + 2, pt.y - 4, pt.z - 1])))
}
}
}
}
| mit |
necrowman/CRLAlamofireFuture | Examples/SimpleTvOSCarthage/Carthage/Checkouts/Future/Future/Future+Functional.swift | 111 | 7931 | //===--- Future+Functional.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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 Result
import Boilerplate
import ExecutionContext
public extension Future {
public func onComplete(callback: Result<Value, AnyError> -> Void) -> Self {
return self.onCompleteInternal(callback)
}
}
public extension FutureType {
public func onSuccess(f: Value -> Void) -> Self {
return self.onComplete { (result:Result<Value, AnyError>) in
result.analysis(ifSuccess: { value in
f(value)
}, ifFailure: {_ in})
}
}
public func onFailure<E : ErrorProtocol>(f: E -> Void) -> Self{
return self.onComplete { (result:Result<Value, E>) in
result.analysis(ifSuccess: {_ in}, ifFailure: {error in
f(error)
})
}
}
public func onFailure(f: ErrorProtocol -> Void) -> Self {
return self.onComplete { (result:Result<Value, AnyError>) in
result.analysis(ifSuccess: {_ in}, ifFailure: {error in
f(error.error)
})
}
}
}
public extension FutureType {
public func map<B>(f:(Value) throws -> B) -> Future<B> {
let future = MutableFuture<B>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
let result = result.flatMap { value in
materializeAny {
try f(value)
}
}
try! future.complete(result)
}
return future
}
public func flatMap<B, F : FutureType where F.Value == B>(f:(Value) -> F) -> Future<B> {
let future = MutableFuture<B>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
result.analysis(ifSuccess: { value in
let b = f(value)
b.onComplete { (result:Result<B, AnyError>) in
try! future.complete(result)
}
}, ifFailure: { error in
try! future.fail(error)
})
}
return future
}
public func flatMap<B, E : ErrorProtocol>(f:(Value) -> Result<B, E>) -> Future<B> {
let future = MutableFuture<B>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
result.analysis(ifSuccess: { value in
let b = f(value)
try! future.complete(b)
}, ifFailure: { error in
try! future.fail(error)
})
}
return future
}
public func flatMap<B>(f:(Value) -> B?) -> Future<B> {
let future = MutableFuture<B>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
let result:Result<B, AnyError> = result.flatMap { value in
guard let b = f(value) else {
return Result(error: AnyError(Error.MappedNil))
}
return Result(value: b)
}
try! future.complete(result)
}
return future
}
public func filter(f: (Value)->Bool) -> Future<Value> {
let future = MutableFuture<Value>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
result.analysis(ifSuccess: { value in
if f(value) {
try! future.success(value)
} else {
try! future.fail(Error.FilteredOut)
}
}, ifFailure: { error in
try! future.fail(error)
})
}
return future
}
public func filterNot(f: (Value)->Bool) -> Future<Value> {
return self.filter { value in
return !f(value)
}
}
public func recover<E : ErrorProtocol>(f:(E) throws ->Value) -> Future<Value> {
let future = MutableFuture<Value>(context: self.context)
self.onComplete { (result:Result<Value, E>) in
let result = result.flatMapError { error in
return materializeAny {
try f(error)
}
}
future.tryComplete(result)
}
// if first one didn't match this one will be called next
future.completeWith(self)
return future
}
public func recover(f:(ErrorProtocol) throws ->Value) -> Future<Value> {
let future = MutableFuture<Value>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
let result = result.flatMapError { error in
return materializeAny {
try f(error.error)
}
}
future.tryComplete(result)
}
// if first one didn't match this one will be called next
future.completeWith(self)
return future
}
public func recoverWith<E : ErrorProtocol>(f:(E) -> Future<Value>) -> Future<Value> {
let future = MutableFuture<Value>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
guard let mapped:Result<Value, E> = result.tryAsError() else {
try! future.complete(result)
return
}
mapped.analysis(ifSuccess: { _ in
try! future.complete(result)
}, ifFailure: { e in
future.completeWith(f(e))
})
}
return future
}
public func recoverWith(f:(ErrorProtocol) -> Future<Value>) -> Future<Value> {
let future = MutableFuture<Value>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
guard let mapped:Result<Value, AnyError> = result.tryAsError() else {
try! future.complete(result)
return
}
mapped.analysis(ifSuccess: { _ in
try! future.complete(result)
}, ifFailure: { e in
future.completeWith(f(e.error))
})
}
return future
}
public func zip<B, F : FutureType where F.Value == B>(f:F) -> Future<(Value, B)> {
let future = MutableFuture<(Value, B)>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
let context = ExecutionContext.current
result.analysis(ifSuccess: { first -> Void in
f.onComplete { (result:Result<B, AnyError>) in
context.execute {
result.analysis(ifSuccess: { second in
try! future.success((first, second))
}, ifFailure: { e in
try! future.fail(e.error)
})
}
}
}, ifFailure: { e in
try! future.fail(e.error)
})
}
return future
}
} | mit |
seraphjiang/JHUIKit | Example/JHUIKit/JHProfileViewController.swift | 1 | 2198 | //
// JHProfileViewController.swift
// JHUIKit
//
// Created by Huan Jiang on 5/6/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import JHUIKit
class JHProfileViewController: UIViewController, JHSwipeViewDelegate {
let runtimeConstants = RuntimeConstants()
var personView: JHProfileCardView?
override func viewDidLoad() {
super.viewDidLoad()
addPersonCard()
handleNotification()
}
func addPersonCard()
{
let superView = UIView(frame: CGRectMake(runtimeConstants.CardMarginWidth, self.runtimeConstants.CardTop, self.runtimeConstants.CardWidth, runtimeConstants.AdaptiveCardHeight))
personView = JHProfileCardView(frame: superView.bounds, image: UIImage(named: "mask")!, radius: 200)
personView!.swipeViewDelegate = self
superView.addSubview(personView!)
self.view.addSubview(superView);
}
func handleNotification()
{
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(JHProfileViewController.cardSwiped(_:)), name: "CardSwipedNotification", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(JHProfileViewController.cardLikeOrDislike(_:)), name: "CardLikeOrDislikeNotification", object: nil)
}
func cardSwiped(notification: NSNotification)
{
if let _: NSDictionary = notification.userInfo
{
// let swipe_action:String = info["swipe_action"] as! String
// var isLike: Int = swipe_action == "like" ? 1 : 0
}
self.personView!.removeFromSuperview()
NSLog("PersonCard.Notification:jobCardSwiped ")
self.addPersonCard()
}
func cardLikeOrDislike(notification: NSNotification)
{
if let _: NSDictionary = notification.userInfo
{
// let action:String = info["action"] as! String
// var isLike: Int = action == "like" ? 1 : 0
}
self.addPersonCard()
}
func cardUsedUp() {
}
func cardSwiped(liked: Bool, viewSwiped:UIView) {
}
func addNextCard() {
}
} | mit |
xiaotaijun/actor-platform | actor-apps/app-ios/ActorApp/Controllers/Conversation/Cells/AABubbleMediaCell.swift | 2 | 15010 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class AABubbleMediaCell : AABubbleBaseFileCell, NYTPhotosViewControllerDelegate {
// Views
let preview = UIImageView()
let progressBg = UIImageView()
let circullarNode = CircullarNode()
let fileStatusIcon = UIImageView()
let timeBg = UIImageView()
let timeLabel = UILabel()
let statusView = UIImageView()
// Layout
var contentWidth = 0
var contentHeight = 0
var contentViewSize: CGSize? = nil
// Binded data
var thumb : ACFastThumb? = nil
var thumbLoaded = false
var contentLoaded = false
// MARK: -
// MARK: Constructors
init(frame: CGRect) {
super.init(frame: frame, isFullSize: false)
timeBg.image = Imaging.imageWithColor(MainAppTheme.bubbles.mediaDateBg, size: CGSize(width: 1, height: 1))
timeLabel.font = UIFont(name: "HelveticaNeue-Italic", size: 11)
timeLabel.textColor = MainAppTheme.bubbles.mediaDate
statusView.contentMode = UIViewContentMode.Center
fileStatusIcon.contentMode = UIViewContentMode.Center
progressBg.image = Imaging.roundedImage(UIColor(red: 0, green: 0, blue: 0, alpha: 0x64/255.0), size: CGSizeMake(CGFloat(64.0),CGFloat(64.0)), radius: CGFloat(32.0))
mainView.addSubview(preview)
mainView.addSubview(progressBg)
mainView.addSubview(fileStatusIcon)
mainView.addSubview(circullarNode.view)
mainView.addSubview(timeBg)
mainView.addSubview(timeLabel)
mainView.addSubview(statusView)
preview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "mediaDidTap"))
preview.userInteractionEnabled = true
contentInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func bind(message: ACMessage, reuse: Bool, cellLayout: CellLayout, setting: CellSetting) {
bubbleInsets = UIEdgeInsets(
top: setting.clenchTop ? AABubbleCell.bubbleTopCompact : AABubbleCell.bubbleTop,
left: 10 + (isIPad ? 16 : 0),
bottom: setting.clenchBottom ? AABubbleCell.bubbleBottomCompact : AABubbleCell.bubbleBottom,
right: 10 + (isIPad ? 16 : 0))
if (!reuse) {
// Bind bubble
if (self.isOut) {
bindBubbleType(BubbleType.MediaOut, isCompact: false)
} else {
bindBubbleType(BubbleType.MediaIn, isCompact: false)
}
// Build bubble size
if (message.getContent() is ACPhotoContent) {
var photo = message.getContent() as! ACPhotoContent;
thumb = photo.getFastThumb()
contentWidth = Int(photo.getW())
contentHeight = Int(photo.getH())
} else if (message.getContent() is ACVideoContent) {
var video = message.getContent() as! ACVideoContent;
thumb = video.getFastThumb()
contentWidth = Int(video.getW())
contentHeight = Int(video.getH())
} else {
fatalError("Unsupported content")
}
contentViewSize = AABubbleMediaCell.measureMedia(contentWidth, h: contentHeight)
// Reset loaded thumbs and contents
preview.image = nil
thumbLoaded = false
contentLoaded = false
// Reset progress
circullarNode.hidden = true
circullarNode.setProgress(0, animated: false)
UIView.animateWithDuration(0, animations: { () -> Void in
self.circullarNode.alpha = 0
self.preview.alpha = 0
self.progressBg.alpha = 0
})
// Bind file
fileBind(message, autoDownload: message.getContent() is ACPhotoContent)
}
// Update time
timeLabel.text = cellLayout.date
// Update status
if (isOut) {
statusView.hidden = false
switch(UInt(message.getMessageState().ordinal())) {
case ACMessageState.PENDING.rawValue:
self.statusView.image = Resources.iconClock;
self.statusView.tintColor = MainAppTheme.bubbles.statusMediaSending
break;
case ACMessageState.SENT.rawValue:
self.statusView.image = Resources.iconCheck1;
self.statusView.tintColor = MainAppTheme.bubbles.statusMediaSent
break;
case ACMessageState.RECEIVED.rawValue:
self.statusView.image = Resources.iconCheck2;
self.statusView.tintColor = MainAppTheme.bubbles.statusMediaReceived
break;
case ACMessageState.READ.rawValue:
self.statusView.image = Resources.iconCheck2;
self.statusView.tintColor = MainAppTheme.bubbles.statusMediaRead
break;
case ACMessageState.ERROR.rawValue:
self.statusView.image = Resources.iconError;
self.statusView.tintColor = MainAppTheme.bubbles.statusMediaError
break
default:
self.statusView.image = Resources.iconClock;
self.statusView.tintColor = MainAppTheme.bubbles.statusMediaSending
break;
}
} else {
statusView.hidden = true
}
}
func mediaDidTap() {
var content = bindedMessage!.getContent() as! ACDocumentContent
if let fileSource = content.getSource() as? ACFileRemoteSource {
Actor.requestStateWithFileId(fileSource.getFileReference().getFileId(), withCallback: CocoaDownloadCallback(
notDownloaded: { () -> () in
Actor.startDownloadingWithReference(fileSource.getFileReference())
}, onDownloading: { (progress) -> () in
Actor.cancelDownloadingWithFileId(fileSource.getFileReference().getFileId())
}, onDownloaded: { (reference) -> () in
var photoInfo = AAPhoto(image: UIImage(contentsOfFile: CocoaFiles.pathFromDescriptor(reference))!)
var controller = NYTPhotosViewController(photos: [photoInfo])
controller.delegate = self
self.controller.presentViewController(controller, animated: true, completion: nil)
}))
} else if let fileSource = content.getSource() as? ACFileLocalSource {
var rid = bindedMessage!.getRid()
Actor.requestUploadStateWithRid(rid, withCallback: CocoaUploadCallback(
notUploaded: { () -> () in
Actor.resumeUploadWithRid(rid)
}, onUploading: { (progress) -> () in
Actor.pauseUploadWithRid(rid)
}, onUploadedClosure: { () -> () in
var photoInfo = AAPhoto(image: UIImage(contentsOfFile: CocoaFiles.pathFromDescriptor(fileSource.getFileDescriptor()))!)
var controller = NYTPhotosViewController(photos: [photoInfo])
controller.delegate = self
self.controller.presentViewController(controller, animated: true, completion: nil)
}))
}
}
override func fileUploadPaused(reference: String, selfGeneration: Int) {
bgLoadReference(reference, selfGeneration: selfGeneration)
bgShowState(selfGeneration)
bgShowIcon("ic_upload", selfGeneration: selfGeneration)
bgHideProgress(selfGeneration)
}
override func fileUploading(reference: String, progress: Double, selfGeneration: Int) {
bgLoadReference(reference, selfGeneration: selfGeneration)
bgShowState(selfGeneration)
bgHideIcon(selfGeneration)
bgShowProgress(progress, selfGeneration: selfGeneration)
}
override func fileDownloadPaused(selfGeneration: Int) {
bgLoadThumb(selfGeneration)
bgShowState(selfGeneration)
bgShowIcon("ic_download", selfGeneration: selfGeneration)
bgHideProgress(selfGeneration)
}
override func fileDownloading(progress: Double, selfGeneration: Int) {
bgLoadThumb(selfGeneration)
bgShowState(selfGeneration)
bgHideIcon(selfGeneration)
bgShowProgress(progress, selfGeneration: selfGeneration)
}
override func fileReady(reference: String, selfGeneration: Int) {
bgLoadReference(reference, selfGeneration: selfGeneration)
bgHideState(selfGeneration)
bgHideIcon(selfGeneration)
bgHideProgress(selfGeneration)
}
func bgLoadThumb(selfGeneration: Int) {
if (thumbLoaded) {
return
}
thumbLoaded = true
if (thumb != nil) {
var loadedThumb = UIImage(data: self.thumb!.getImage().toNSData()!)?.roundCorners(contentViewSize!.width - 2, h: contentViewSize!.height - 2, roundSize: 14)
runOnUiThread(selfGeneration,closure: { ()->() in
self.setPreviewImage(loadedThumb!, fast: true)
});
}
}
func bgLoadReference(reference: String, selfGeneration: Int) {
if (contentLoaded) {
return
}
contentLoaded = true
var loadedContent = UIImage(contentsOfFile: CocoaFiles.pathFromDescriptor(reference))?.roundCorners(contentViewSize!.width - 2, h: contentViewSize!.height - 2, roundSize: 14)
if (loadedContent == nil) {
return
}
runOnUiThread(selfGeneration, closure: { () -> () in
self.setPreviewImage(loadedContent!, fast: false)
})
}
// Progress show/hide
func bgHideProgress(selfGeneration: Int) {
self.runOnUiThread(selfGeneration, closure: { () -> () in
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.circullarNode.alpha = 0
}, completion: { (val) -> Void in
if (val) {
self.circullarNode.hidden = true
}
})
})
}
func bgShowProgress(value: Double, selfGeneration: Int) {
self.runOnUiThread(selfGeneration, closure: { () -> () in
if (self.circullarNode.hidden) {
self.circullarNode.hidden = false
self.circullarNode.alpha = 0
}
self.circullarNode.postProgress(value, animated: true)
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.circullarNode.alpha = 1
})
})
}
// State show/hide
func bgHideState(selfGeneration: Int) {
self.runOnUiThread(selfGeneration, closure: { () -> () in
self.progressBg.hideView()
})
}
func bgShowState(selfGeneration: Int) {
self.runOnUiThread(selfGeneration, closure: { () -> () in
self.progressBg.showView()
})
}
// Icon show/hide
func bgShowIcon(name: String, selfGeneration: Int) {
var img = UIImage(named: name)?.tintImage(UIColor.whiteColor())
self.runOnUiThread(selfGeneration, closure: { () -> () in
self.fileStatusIcon.image = img
self.fileStatusIcon.showView()
})
}
func bgHideIcon(selfGeneration: Int) {
self.runOnUiThread(selfGeneration, closure: { () -> () in
self.fileStatusIcon.hideView()
})
}
func setPreviewImage(img: UIImage, fast: Bool){
if ((fast && self.preview.image == nil) || !fast) {
self.preview.image = img;
self.preview.showView()
}
}
// MARK: -
// MARK: Getters
private class func measureMedia(w: Int, h: Int) -> CGSize {
var screenScale = UIScreen.mainScreen().scale;
var scaleW = 240 / CGFloat(w)
var scaleH = 340 / CGFloat(h)
var scale = min(scaleW, scaleH)
return CGSize(width: scale * CGFloat(w), height: scale * CGFloat(h))
}
class func measureMediaHeight(message: ACMessage) -> CGFloat {
if (message.getContent() is ACPhotoContent) {
var photo = message.getContent() as! ACPhotoContent;
return measureMedia(Int(photo.getW()), h: Int(photo.getH())).height + 2;
} else if (message.getContent() is ACVideoContent) {
var video = message.getContent() as! ACVideoContent;
return measureMedia(Int(video.getW()), h: Int(video.getH())).height + 2;
} else {
fatalError("Unknown content type")
}
}
// MARK: -
// MARK: Layout
override func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) {
var insets = fullContentInsets
var contentWidth = self.contentView.frame.width
var contentHeight = self.contentView.frame.height
var bubbleHeight = contentHeight - insets.top - insets.bottom
var bubbleWidth = bubbleHeight * CGFloat(self.contentWidth) / CGFloat(self.contentHeight)
layoutBubble(bubbleWidth, contentHeight: bubbleHeight)
if (isOut) {
preview.frame = CGRectMake(contentWidth - insets.left - bubbleWidth, insets.top, bubbleWidth, bubbleHeight)
} else {
preview.frame = CGRectMake(insets.left, insets.top, bubbleWidth, bubbleHeight)
}
circullarNode.frame = CGRectMake(preview.frame.origin.x + preview.frame.width/2 - 32, preview.frame.origin.y + preview.frame.height/2 - 32, 64, 64)
progressBg.frame = circullarNode.frame
fileStatusIcon.frame = CGRectMake(preview.frame.origin.x + preview.frame.width/2 - 24, preview.frame.origin.y + preview.frame.height/2 - 24, 48, 48)
timeLabel.frame = CGRectMake(0, 0, 1000, 1000)
timeLabel.sizeToFit()
var timeWidth = (isOut ? 23 : 0) + timeLabel.bounds.width
var timeHeight: CGFloat = 20
timeLabel.frame = CGRectMake(preview.frame.maxX - timeWidth - 18, preview.frame.maxY - timeHeight - 6, timeLabel.frame.width, timeHeight)
if (isOut) {
statusView.frame = CGRectMake(timeLabel.frame.maxX, timeLabel.frame.minY, 23, timeHeight)
}
timeBg.frame = CGRectMake(timeLabel.frame.minX - 3, timeLabel.frame.minY - 1, timeWidth + 6, timeHeight + 2)
}
func photosViewController(photosViewController: NYTPhotosViewController!, referenceViewForPhoto photo: NYTPhoto!) -> UIView! {
return self.preview
}
}
| mit |
hejunbinlan/Operations | Operations/Operations/GatedOperation.swift | 1 | 990 | //
// GatedOperation.swift
// Operations
//
// Created by Daniel Thorpe on 24/07/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import Foundation
/**
Allows a `NSOperation` to be composed inside an `Operation`,
with a block to act as a gate.
*/
public class GatedOperation<O: NSOperation>: GroupOperation {
public typealias GateBlockType = () -> Bool
public let operation: O
let gate: GateBlockType
/**
Return true from the block to have the composed operation
be executed, return false and the operation will not
be executed.
:param: operation, any subclass of `NSOperation`.
:param: gate, a block which returns a Bool.
*/
public init(operation: O, gate: GateBlockType) {
self.operation = operation
self.gate = gate
super.init(operations: [])
}
public override func execute() {
if gate() {
addOperation(operation)
}
super.execute()
}
}
| mit |
mauriciosantos/Buckets-Swift | Source/BitArray.swift | 3 | 9259 | //
// BitArray.swift
// Buckets
//
// Created by Mauricio Santos on 2/23/15.
// Copyright (c) 2015 Mauricio Santos. All rights reserved.
//
import Foundation
/// An array of boolean values stored
/// using individual bits, thus providing a
/// very small memory footprint. It has most of the features of a
/// standard array such as constant time random access and
/// amortized constant time insertion at the end of the array.
///
/// Conforms to `MutableCollection`, `ExpressibleByArrayLiteral`
/// , `Equatable`, `Hashable`, `CustomStringConvertible`
public struct BitArray {
// MARK: Creating a BitArray
/// Constructs an empty bit array.
public init() {}
/// Constructs a bit array from a `Bool` sequence, such as an array.
public init<S: Sequence>(_ elements: S) where S.Iterator.Element == Bool {
for value in elements {
append(value)
}
}
/// Constructs a new bit array from an `Int` array representation.
/// All values different from 0 are considered `true`.
public init(intRepresentation : [Int]) {
bits.reserveCapacity((intRepresentation.count/Constants.IntSize) + 1)
for value in intRepresentation {
append(value != 0)
}
}
/// Constructs a new bit array with `count` bits set to the specified value.
public init(repeating repeatedValue: Bool, count: Int) {
precondition(count >= 0, "Can't construct BitArray with count < 0")
let numberOfInts = (count/Constants.IntSize) + 1
let intValue = repeatedValue ? ~0 : 0
bits = [Int](repeating: intValue, count: numberOfInts)
self.count = count
if repeatedValue {
bits[bits.count - 1] = 0
let missingBits = count % Constants.IntSize
self.count = count - missingBits
for _ in 0..<missingBits {
append(repeatedValue)
}
cardinality = count
}
}
// MARK: Querying a BitArray
/// Number of bits stored in the bit array.
public fileprivate(set) var count = 0
/// Returns `true` if and only if `count == 0`.
public var isEmpty: Bool {
return count == 0
}
/// The first bit, or nil if the bit array is empty.
public var first: Bool? {
return isEmpty ? nil : valueAtIndex(0)
}
/// The last bit, or nil if the bit array is empty.
public var last: Bool? {
return isEmpty ? nil : valueAtIndex(count-1)
}
/// The number of bits set to `true` in the bit array.
public fileprivate(set) var cardinality = 0
// MARK: Adding and Removing Bits
/// Adds a new `Bool` as the last bit.
public mutating func append(_ bit: Bool) {
if realIndexPath(count).arrayIndex >= bits.count {
bits.append(0)
}
setValue(bit, atIndex: count)
count += 1
}
/// Inserts a bit into the array at a given index.
/// Use this method to insert a new bit anywhere within the range
/// of existing bits, or as the last bit. The index must be less
/// than or equal to the number of bits in the bit array. If you
/// attempt to remove a bit at a greater index, you’ll trigger an error.
public mutating func insert(_ bit: Bool, at index: Int) {
checkIndex(index, lessThan: count + 1)
append(bit)
for i in stride(from: (count - 2), through: index, by: -1) {
let iBit = valueAtIndex(i)
setValue(iBit, atIndex: i+1)
}
setValue(bit, atIndex: index)
}
/// Removes the last bit from the bit array and returns it.
///
/// - returns: The last bit, or nil if the bit array is empty.
@discardableResult
public mutating func removeLast() -> Bool {
if let value = last {
setValue(false, atIndex: count-1)
count -= 1
return value
}
preconditionFailure("Array is empty")
}
/// Removes the bit at the given index and returns it.
/// The index must be less than the number of bits in the
/// bit array. If you attempt to remove a bit at a
/// greater index, you’ll trigger an error.
@discardableResult
public mutating func remove(at index: Int) -> Bool {
checkIndex(index)
let bit = valueAtIndex(index)
for i in (index + 1)..<count {
let iBit = valueAtIndex(i)
setValue(iBit, atIndex: i-1)
}
removeLast()
return bit
}
/// Removes all the bits from the array, and by default
/// clears the underlying storage buffer.
public mutating func removeAll(keepingCapacity keep: Bool = false) {
if !keep {
bits.removeAll(keepingCapacity: false)
} else {
bits[0 ..< bits.count] = [0]
}
count = 0
cardinality = 0
}
// MARK: Private Properties and Helper Methods
/// Structure holding the bits.
fileprivate var bits = [Int]()
fileprivate func valueAtIndex(_ logicalIndex: Int) -> Bool {
let indexPath = realIndexPath(logicalIndex)
var mask = 1 << indexPath.bitIndex
mask = mask & bits[indexPath.arrayIndex]
return mask != 0
}
fileprivate mutating func setValue(_ newValue: Bool, atIndex logicalIndex: Int) {
let indexPath = realIndexPath(logicalIndex)
let mask = 1 << indexPath.bitIndex
let oldValue = mask & bits[indexPath.arrayIndex] != 0
switch (oldValue, newValue) {
case (false, true):
cardinality += 1
case (true, false):
cardinality -= 1
default:
break
}
if newValue {
bits[indexPath.arrayIndex] |= mask
} else {
bits[indexPath.arrayIndex] &= ~mask
}
}
fileprivate func realIndexPath(_ logicalIndex: Int) -> (arrayIndex: Int, bitIndex: Int) {
return (logicalIndex / Constants.IntSize, logicalIndex % Constants.IntSize)
}
fileprivate func checkIndex(_ index: Int, lessThan: Int? = nil) {
let bound = lessThan == nil ? count : lessThan
precondition(count >= 0 && index < bound!, "Index out of range (\(index))")
}
// MARK: Constants
fileprivate struct Constants {
// Int size in bits
static let IntSize = MemoryLayout<Int>.size * 8
}
}
extension BitArray: MutableCollection {
// MARK: MutableCollection Protocol Conformance
/// Always zero, which is the index of the first bit when non-empty.
public var startIndex : Int {
return 0
}
/// Always `count`, which the successor of the last valid
/// subscript argument.
public var endIndex : Int {
return count
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Int) -> Int {
return i + 1
}
/// Provides random access to individual bits using square bracket noation.
/// The index must be less than the number of items in the bit array.
/// If you attempt to get or set a bit at a greater
/// index, you’ll trigger an error.
public subscript(index: Int) -> Bool {
get {
checkIndex(index)
return valueAtIndex(index)
}
set {
checkIndex(index)
setValue(newValue, atIndex: index)
}
}
}
extension BitArray: ExpressibleByArrayLiteral {
// MARK: ExpressibleByArrayLiteral Protocol Conformance
/// Constructs a bit array using a `Bool` array literal.
/// `let example: BitArray = [true, false, true]`
public init(arrayLiteral elements: Bool...) {
bits.reserveCapacity((elements.count/Constants.IntSize) + 1)
for element in elements {
append(element)
}
}
}
extension BitArray: CustomStringConvertible {
// MARK: CustomStringConvertible Protocol Conformance
/// A string containing a suitable textual
/// representation of the bit array.
public var description: String {
return "[" + self.map {"\($0)"}.joined(separator: ", ") + "]"
}
}
extension BitArray: Equatable {
}
// MARK: BitArray Equatable Protocol Conformance
/// Returns `true` if and only if the bit arrays contain the same bits in the same order.
public func ==(lhs: BitArray, rhs: BitArray) -> Bool {
if lhs.count != rhs.count || lhs.cardinality != rhs.cardinality {
return false
}
return lhs.elementsEqual(rhs)
}
extension BitArray: Hashable {
// MARK: Hashable Protocol Conformance
/// The hash value.
/// `x == y` implies `x.hashValue == y.hashValue`
public var hashValue: Int {
var result = 43
result = (31 ^ result) ^ count
for element in self {
result = (31 ^ result) ^ element.hashValue
}
return result
}
}
| mit |
antoninbiret/ABSteppedProgressBar | Exemple-ABSteppedProgressBar/Pods/ABSteppedProgressBar/Sources/ABSteppedProgessBar.swift | 1 | 13992 | //
// ABSteppedProgressBar.swift
// ABSteppedProgressBar
//
// Created by Antonin Biret on 17/02/15.
// Copyright (c) 2015 Antonin Biret. All rights reserved.
//
import UIKit
import Foundation
import CoreGraphics
@objc public protocol ABSteppedProgressBarDelegate {
optional func progressBar(progressBar: ABSteppedProgressBar,
willSelectItemAtIndex index: Int)
optional func progressBar(progressBar: ABSteppedProgressBar,
didSelectItemAtIndex index: Int)
optional func progressBar(progressBar: ABSteppedProgressBar,
canSelectItemAtIndex index: Int) -> Bool
optional func progressBar(progressBar: ABSteppedProgressBar,
textAtIndex index: Int) -> String
}
@IBDesignable public class ABSteppedProgressBar: UIView {
@IBInspectable public var numberOfPoints: Int = 3 {
didSet {
self.setNeedsDisplay()
}
}
public var currentIndex: Int = 0 {
willSet(newValue){
if let delegate = self.delegate {
delegate.progressBar?(self, willSelectItemAtIndex: newValue)
}
}
didSet {
animationRendering = true
self.setNeedsDisplay()
}
}
private var previousIndex: Int = 0
@IBInspectable public var lineHeight: CGFloat = 0.0 {
didSet {
self.setNeedsDisplay()
}
}
private var _lineHeight: CGFloat {
get {
if(lineHeight == 0.0 || lineHeight > self.bounds.height) {
return self.bounds.height * 0.4
}
return lineHeight
}
}
@IBInspectable public var radius: CGFloat = 0.0 {
didSet {
self.setNeedsDisplay()
}
}
private var _radius: CGFloat {
get{
if(radius == 0.0 || radius > self.bounds.height / 2.0) {
return self.bounds.height / 2.0
}
return radius
}
}
@IBInspectable public var progressRadius: CGFloat = 0.0 {
didSet {
maskLayer.cornerRadius = progressRadius
self.setNeedsDisplay()
}
}
private var _progressRadius: CGFloat {
get {
if(progressRadius == 0.0 || progressRadius > self.bounds.height / 2.0) {
return self.bounds.height / 2.0
}
return progressRadius
}
}
@IBInspectable public var progressLineHeight: CGFloat = 0.0 {
didSet {
self.setNeedsDisplay()
}
}
private var _progressLineHeight: CGFloat {
get {
if(progressLineHeight == 0.0 || progressLineHeight > _lineHeight) {
return _lineHeight
}
return progressLineHeight
}
}
@IBInspectable public var stepAnimationDuration: CFTimeInterval = 0.4
@IBInspectable public var displayNumbers: Bool = true {
didSet {
self.setNeedsDisplay()
}
}
public var numbersFont: UIFont? {
didSet {
self.setNeedsDisplay()
}
}
public var numbersColor: UIColor? {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable public var backgroundShapeColor: UIColor = UIColor(red: 166.0/255.0, green: 160.0/255.0, blue: 151.0/255.0, alpha: 0.8) {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable public var selectedBackgoundColor: UIColor = UIColor(red: 150.0/255.0, green: 24.0/255.0, blue: 33.0/255.0, alpha: 1.0) {
didSet {
self.setNeedsDisplay()
}
}
public var delegate: ABSteppedProgressBarDelegate?
private var backgroundLayer: CAShapeLayer = CAShapeLayer()
private var progressLayer: CAShapeLayer = CAShapeLayer()
private var maskLayer: CAShapeLayer = CAShapeLayer()
private var centerPoints = Array<CGPoint>()
private var animationRendering = false
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
convenience init() {
self.init(frame:CGRectZero)
}
func commonInit() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "gestureAction:")
let swipeGestureRecognizer = UIPanGestureRecognizer(target: self, action: "gestureAction:")
self.addGestureRecognizer(tapGestureRecognizer)
self.addGestureRecognizer(swipeGestureRecognizer)
self.backgroundColor = UIColor.clearColor()
self.layer.addSublayer(backgroundLayer)
self.layer.addSublayer(progressLayer)
progressLayer.mask = maskLayer
self.contentMode = UIViewContentMode.Redraw
}
override public func drawRect(rect: CGRect) {
super.drawRect(rect)
let largerRadius = fmax(_radius, _progressRadius)
let distanceBetweenCircles = (self.bounds.width - (CGFloat(numberOfPoints) * 2 * largerRadius)) / CGFloat(numberOfPoints - 1)
var xCursor: CGFloat = largerRadius
for _ in 0...(numberOfPoints - 1) {
centerPoints.append(CGPointMake(xCursor, bounds.height / 2))
xCursor += 2 * largerRadius + distanceBetweenCircles
}
let progressCenterPoints = Array<CGPoint>(centerPoints[0..<(currentIndex+1)])
if(!animationRendering) {
if let bgPath = shapePath(centerPoints, aRadius: _radius, aLineHeight: _lineHeight) {
backgroundLayer.path = bgPath.CGPath
backgroundLayer.fillColor = backgroundShapeColor.CGColor
}
if let progressPath = shapePath(centerPoints, aRadius: _progressRadius, aLineHeight: _progressLineHeight) {
progressLayer.path = progressPath.CGPath
progressLayer.fillColor = selectedBackgoundColor.CGColor
}
if(displayNumbers) {
for i in 0...(numberOfPoints - 1) {
let centerPoint = centerPoints[i]
let textLayer = CATextLayer()
var textLayerFont = UIFont.boldSystemFontOfSize(_progressRadius)
textLayer.contentsScale = UIScreen.mainScreen().scale
if let nFont = self.numbersFont {
textLayerFont = nFont
}
textLayer.font = CTFontCreateWithName(textLayerFont.fontName as CFStringRef, textLayerFont.pointSize, nil)
textLayer.fontSize = textLayerFont.pointSize
if let nColor = self.numbersColor {
textLayer.foregroundColor = nColor.CGColor
}
if let text = self.delegate?.progressBar?(self, textAtIndex: i) {
textLayer.string = text
} else {
textLayer.string = "\(i)"
}
textLayer.sizeWidthToFit()
textLayer.frame = CGRectMake(centerPoint.x - textLayer.bounds.width/2, centerPoint.y - textLayer.bounds.height/2, textLayer.bounds.width, textLayer.bounds.height)
self.layer.addSublayer(textLayer)
}
}
}
if let currentProgressCenterPoint = progressCenterPoints.last {
let maskPath = self.maskPath(currentProgressCenterPoint)
maskLayer.path = maskPath.CGPath
CATransaction.begin()
let progressAnimation = CABasicAnimation(keyPath: "path")
progressAnimation.duration = stepAnimationDuration * CFTimeInterval(abs(currentIndex - previousIndex))
progressAnimation.toValue = maskPath
progressAnimation.removedOnCompletion = false
progressAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
CATransaction.setCompletionBlock { () -> Void in
if(self.animationRendering) {
if let delegate = self.delegate {
delegate.progressBar?(self, didSelectItemAtIndex: self.currentIndex)
}
self.animationRendering = false
}
}
maskLayer.addAnimation(progressAnimation, forKey: "progressAnimation")
CATransaction.commit()
}
previousIndex = currentIndex
}
func shapePath(centerPoints: Array<CGPoint>, aRadius: CGFloat, aLineHeight: CGFloat) -> UIBezierPath? {
let nbPoint = centerPoints.count
let path = UIBezierPath()
var distanceBetweenCircles: CGFloat = 0
if let first = centerPoints.first where nbPoint > 2 {
let second = centerPoints[1]
distanceBetweenCircles = second.x - first.x - 2 * aRadius
}
let angle = aLineHeight / 2.0 / aRadius;
var xCursor: CGFloat = 0
for i in 0...(2 * nbPoint - 1) {
var index = i
if(index >= nbPoint) {
index = (nbPoint - 1) - (i - nbPoint)
}
let centerPoint = centerPoints[index]
var startAngle: CGFloat = 0
var endAngle: CGFloat = 0
if(i == 0) {
xCursor = centerPoint.x
startAngle = CGFloat(M_PI)
endAngle = -angle
} else if(i < nbPoint - 1) {
startAngle = CGFloat(M_PI) + angle
endAngle = -angle
} else if(i == (nbPoint - 1)){
startAngle = CGFloat(M_PI) + angle
endAngle = 0
} else if(i == nbPoint) {
startAngle = 0
endAngle = CGFloat(M_PI) - angle
} else if (i < (2 * nbPoint - 1)) {
startAngle = angle
endAngle = CGFloat(M_PI) - angle
} else {
startAngle = angle
endAngle = CGFloat(M_PI)
}
path.addArcWithCenter(CGPointMake(centerPoint.x, centerPoint.y), radius: aRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
if(i < nbPoint - 1) {
xCursor += aRadius + distanceBetweenCircles
path.addLineToPoint(CGPointMake(xCursor, centerPoint.y - aLineHeight / 2.0))
xCursor += aRadius
} else if (i < (2 * nbPoint - 1) && i >= nbPoint) {
xCursor -= aRadius + distanceBetweenCircles
path.addLineToPoint(CGPointMake(xCursor, centerPoint.y + aLineHeight / 2.0))
xCursor -= aRadius
}
}
return path
}
func progressMaskPath(currentProgressCenterPoint: CGPoint) -> UIBezierPath {
let maskPath = UIBezierPath(rect: CGRectMake(0.0, 0.0, currentProgressCenterPoint.x + _progressRadius, self.bounds.height))
return maskPath
}
func maskPath(currentProgressCenterPoint: CGPoint) -> UIBezierPath {
let angle = _progressLineHeight / 2.0 / _progressRadius;
let xOffset = cos(angle) * _progressRadius
let maskPath = UIBezierPath()
maskPath.moveToPoint(CGPointMake(0.0, 0.0))
maskPath.addLineToPoint(CGPointMake(currentProgressCenterPoint.x + xOffset, 0.0))
maskPath.addLineToPoint(CGPointMake(currentProgressCenterPoint.x + xOffset, currentProgressCenterPoint.y - _progressLineHeight))
maskPath.addArcWithCenter(currentProgressCenterPoint, radius: _progressRadius, startAngle: -angle, endAngle: angle, clockwise: true)
maskPath.addLineToPoint(CGPointMake(currentProgressCenterPoint.x + xOffset, self.bounds.height))
maskPath.addLineToPoint(CGPointMake(0.0, self.bounds.height))
maskPath.closePath()
return maskPath
}
func gestureAction(gestureRecognizer:UIGestureRecognizer) {
if(gestureRecognizer.state == UIGestureRecognizerState.Ended ||
gestureRecognizer.state == UIGestureRecognizerState.Changed ) {
let touchPoint = gestureRecognizer.locationInView(self)
var smallestDistance = CGFloat(Float.infinity)
var selectedIndex = 0
for (index, point) in centerPoints.enumerate() {
let distance = touchPoint.distanceWith(point)
if(distance < smallestDistance) {
smallestDistance = distance
selectedIndex = index
}
}
if(currentIndex != selectedIndex) {
if let canSelect = self.delegate?.progressBar?(self, canSelectItemAtIndex: selectedIndex) {
if (canSelect) {
currentIndex = selectedIndex
}
} else {
currentIndex = selectedIndex
}
}
}
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/BlockchainComponentLibrary/Sources/Examples/2 - Primitives/InputExamples.swift | 1 | 3487 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import SwiftUI
#if canImport(UIKit)
import UIKit
struct InputExamples: View {
@State var firstResponder: Field? = .email
@State var text: String = ""
@State var password: String = ""
@State var hidePassword: Bool = true
@State var number: String = ""
enum Field {
case email
case password
case number
}
var showPasswordError: Bool {
!password.isEmpty && password.count < 5
}
var body: some View {
VStack {
// Text
Input(
text: $text,
isFirstResponder: firstResponderBinding(for: .email),
subTextStyle: .default,
placeholder: "Email Address",
prefix: nil,
state: .default,
configuration: { textField in
textField.keyboardType = .emailAddress
textField.textContentType = .emailAddress
textField.returnKeyType = .next
},
onReturnTapped: {
firstResponder = .password
}
)
// Password
Input(
text: $password,
isFirstResponder: firstResponderBinding(for: .password),
subText: showPasswordError ? "Password too short" : nil,
subTextStyle: showPasswordError ? .error : .default,
placeholder: "Password",
state: showPasswordError ? .error : .default,
configuration: { textField in
textField.isSecureTextEntry = hidePassword
textField.textContentType = .password
textField.returnKeyType = .next
},
trailing: {
if hidePassword {
IconButton(icon: .visibilityOn) {
hidePassword = false
}
} else {
IconButton(icon: .visibilityOff) {
hidePassword = true
}
}
},
onReturnTapped: {
firstResponder = .number
}
)
// Number
Input(
text: $number,
isFirstResponder: firstResponderBinding(for: .number),
label: "Purchase amount",
placeholder: "0",
prefix: "USD",
configuration: { textField in
textField.keyboardType = .decimalPad
textField.returnKeyType = .done
}
)
Spacer()
}
.padding()
}
func firstResponderBinding(for field: Field) -> Binding<Bool> {
Binding(
get: { firstResponder == field },
set: { newValue in
if newValue {
firstResponder = field
} else if firstResponder == field {
firstResponder = nil
}
}
)
}
}
struct InputExamples_Previews: PreviewProvider {
static var previews: some View {
InputExamples()
}
}
#else
struct InputExamples: View {
var body: some View {
Text("Not supported on macOS")
}
}
#endif
| lgpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionDomain/TransactionAPI/TransactionProcessor/TransactionConfirmation/TransactionConfirmationKind.swift | 1 | 405 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public enum TransactionConfirmationKind: Equatable {
case description
case agreementInterestTandC
case agreementInterestTransfer
case readOnly
case memo
case largeTransactionWarning
case feeSelection
case errorNotice
case invoiceCountdown
case networkFee
case quoteCountdown
}
| lgpl-3.0 |
iOSWizards/AwesomeMedia | AwesomeMedia/Classes/Models/AwesomeMediaMarker.swift | 1 | 338 | //
// AwesomeMediaMarkers.swift
// AwesomeMedia
//
// Created by Emmanuel on 19/04/2018.
//
import Foundation
public struct AwesomeMediaMarker: Equatable {
public var title: String = ""
public var time: Double = 0
public init(title: String, time: Double){
self.title = title
self.time = time
}
}
| mit |
huonw/swift | validation-test/compiler_crashers_fixed/01012-swift-modulefile-getdecl.swift | 65 | 557 | // 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
var f: b {
class B : NSObject {
}
class A<T, end: d where B : A? = 0.substringWithRange(t: S) -> {
let c : Any, f(m(Any) {
protocol c == "\(a<T, e)
}
enum A {
| apache-2.0 |
Jnosh/swift | validation-test/compiler_crashers_fixed/28271-swift-archetypebuilder-getallarchetypes.swift | 65 | 456 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func b{{
protocol P{func b
func b<T where T=e
typealias e
| apache-2.0 |
harlanhaskins/csh.link | Sources/csh.link/Models/Link.swift | 1 | 2335 | import Vapor
import Fluent
import Foundation
enum LinkError: Error {
case noID
case invalidShortCode
}
struct Link: Model {
var id: Node?
var url: URL
var code: String
var created: Date
var exists: Bool = false
var active: Bool = true
var creator: String? = nil
init(url: URL, code: String? = nil, creator: String? = nil, created: Date? = nil) throws {
self.url = url
self.code = code ?? IDGenerator.encodeID(url.hashValue ^ Date().hashValue)
self.creator = creator
self.created = created ?? Date()
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
let urlString: String = try node.extract("url")
url = URL(string: urlString)!
code = try node.extract("code")
creator = try node.extract("creator")
active = try node.extract("active")
created = try node.extract("created_at") { (timestamp: TimeInterval) -> Date in
return Date(timeIntervalSince1970: timestamp)
}
}
func makeNode(context: Context) -> Node {
var data: Node = [
"url": .string(url.absoluteString),
"active": .bool(active),
"code": .string(code),
"id": id ?? .null,
"created_at": .number(Node.Number(created.timeIntervalSince1970))
]
if let creator = creator {
data["creator"] = .string(creator)
}
return data
}
func makeJSON() -> JSON {
return JSON(makeNode(context: EmptyNode))
}
static func forCode(_ code: String) throws -> Link? {
return try Link.query()
.filter("code", code)
.filter("active", true)
.first()
}
static func prepare(_ database: Database) throws {
try database.create("links") { link in
link.id()
link.string("url")
link.string("code")
link.string("creator", length: 36, optional: false)
link.bool("active")
link.double("created_at")
}
}
static func revert(_ database: Database) throws {
try database.delete("links")
}
func visits() -> Children<Visit> {
return children()
}
}
| mit |
T-Pro/CircularRevealKit | Example/CircularRevealKit/UIImageViewExtension.swift | 1 | 1993 | //
// Copyright (c) 2019 T-Pro
//
// 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 UIImageView {
func roundCornersForAspectFit(radius: CGFloat) {
if let image = self.image {
//calculate drawingRect
let boundsScale = self.bounds.size.width / self.bounds.size.height
let imageScale = image.size.width / image.size.height
var drawingRect: CGRect = self.bounds
if boundsScale > imageScale {
drawingRect.size.width = drawingRect.size.height * imageScale
drawingRect.origin.x = (self.bounds.size.width - drawingRect.size.width) / 2
} else {
drawingRect.size.height = drawingRect.size.width / imageScale
drawingRect.origin.y = (self.bounds.size.height - drawingRect.size.height) / 2
}
let path = UIBezierPath(roundedRect: drawingRect, cornerRadius: radius)
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
}
| mit |
lamb/Tile | Tile/view/ScoreView.swift | 1 | 1191 | //
// ScoreView.swift
// Tile
//
// Created by Lamb on 14-6-22.
// Copyright (c) 2014年 mynah. All rights reserved.
//
import UIKit
protocol ScoreViewProtocol{
func changeScore(value s:Int)
}
class ScoreView:UIView, ScoreViewProtocol{
var label:UILabel
let defaultFrame = CGRectMake(0, 0, 100, 30)
var score:Int = 0{
didSet{
label.text = "分数\(score)"
}
}
override init(){
label = UILabel(frame:defaultFrame)
label.textAlignment = NSTextAlignment.Center
super.init(frame:defaultFrame)
backgroundColor = UIColor.orangeColor()
label.font = UIFont(name:"微软雅黑", size:16)
label.textColor = UIColor.whiteColor()
self.addSubview(label)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func changeScore(value s:Int){
score = s
}
}
class BestScoreView:ScoreView, ScoreViewProtocol{
var bestScore:Int = 0{
didSet{
label.text = "最高分\(bestScore)"
}
}
override func changeScore(value s:Int){
bestScore = s
}
}
| mit |
mechinn/our-alliance-ios | ouralliance/MasterViewController.swift | 2 | 9498 | //
// MasterViewController.swift
// ouralliance
//
// Created by Michael Chinn on 9/13/15.
// Copyright (c) 2015 frc869. All rights reserved.
//
import UIKit
import CoreData
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var detailViewController: DetailViewController? = nil
var managedObjectContext: NSManagedObjectContext? = nil
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as! NSManagedObject
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(NSDate(), forKey: "timeStamp")
// Save the context.
var error: NSError? = nil
if !context.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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject)
var error: NSError? = nil
if !context.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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
cell.textLabel!.text = object.valueForKey("timeStamp")!.description
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = [sortDescriptor]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
var error: NSError? = nil
if !_fetchedResultsController!.performFetch(&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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
default:
return
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/
}
| gpl-2.0 |
tadija/AELog | Example/AELogDemo watchOS Extension/InterfaceController.swift | 1 | 788 | /**
* https://github.com/tadija/AELog
* Copyright © 2016-2020 Marko Tadić
* Licensed under the MIT license
*/
import WatchKit
import Foundation
import AELog
class InterfaceController: WKInterfaceController {
override func awake(withContext context: Any?) {
super.awake(withContext: context)
aelog()
}
override func willActivate() {
super.willActivate()
aelog()
}
override func didDeactivate() {
super.didDeactivate()
aelog()
}
@IBAction func didTapButton() {
let queue = DispatchQueue.global()
queue.async {
generateLogLines(count: Int.random(max: 1000))
DispatchQueue.main.async(execute: {
aelog()
})
}
}
}
| mit |
johnno1962d/swift | test/IRGen/struct_resilience.swift | 3 | 9234 | // RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-ir -enable-resilience %s | FileCheck %s
// RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-ir -enable-resilience -O %s
import resilient_struct
import resilient_enum
// CHECK: %Si = type <{ [[INT:i32|i64]] }>
// CHECK-LABEL: @_TMfV17struct_resilience26StructWithResilientStorage = internal global
// Resilient structs from outside our resilience domain are manipulated via
// value witnesses
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience26functionWithResilientTypesFTV16resilient_struct4Size1fFS1_S1__S1_(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i8*, %swift.refcounted*)
public func functionWithResilientTypes(_ s: Size, f: Size -> Size) -> Size {
// CHECK: [[RESULT:%.*]] = alloca [[BUFFER_TYPE:\[.* x i8\]]]
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV16resilient_struct4Size()
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 5
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[initializeBufferWithCopy:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[BUFFER:%.*]] = call %swift.opaque* [[initializeBufferWithCopy]]([[BUFFER_TYPE]]* [[RESULT]], %swift.opaque* %1, %swift.type* [[METADATA]])
// CHECK: [[FN:%.*]] = bitcast i8* %2 to void (%swift.opaque*, %swift.opaque*, %swift.refcounted*)*
// CHECK: call void [[FN]](%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture [[BUFFER]], %swift.refcounted* %3)
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 3
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[deallocateBuffer:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: call void [[deallocateBuffer]]([[BUFFER_TYPE]]* [[RESULT]], %swift.type* [[METADATA]])
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[destroy:%.*]] = bitcast i8* [[WITNESS]] to void (%swift.opaque*, %swift.type*)*
// CHECK: call void [[destroy]](%swift.opaque* %1, %swift.type* [[METADATA]])
// CHECK: ret void
return f(s)
}
// CHECK-LABEL: declare %swift.type* @_TMaV16resilient_struct4Size()
// Rectangle has fixed layout inside its resilience domain, and dynamic
// layout on the outside.
//
// Make sure we use a type metadata accessor function, and load indirect
// field offsets from it.
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience26functionWithResilientTypesFV16resilient_struct9RectangleT_(%V16resilient_struct9Rectangle* noalias nocapture)
public func functionWithResilientTypes(_ r: Rectangle) {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV16resilient_struct9Rectangle()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], i32 3
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %V16resilient_struct9Rectangle* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Si*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %Si, %Si* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
_ = r.color
// CHECK: ret void
}
// Resilient structs from inside our resilience domain are manipulated
// directly.
public struct MySize {
public let w: Int
public let h: Int
}
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience28functionWithMyResilientTypesFTVS_6MySize1fFS0_S0__S0_(%V17struct_resilience6MySize* {{.*}}, %V17struct_resilience6MySize* {{.*}}, i8*, %swift.refcounted*)
public func functionWithMyResilientTypes(_ s: MySize, f: MySize -> MySize) -> MySize {
// CHECK: [[TEMP:%.*]] = alloca %V17struct_resilience6MySize
// CHECK: bitcast
// CHECK: llvm.lifetime.start
// CHECK: [[COPY:%.*]] = bitcast %V17struct_resilience6MySize* %4 to i8*
// CHECK: [[ARG:%.*]] = bitcast %V17struct_resilience6MySize* %1 to i8*
// CHECK: call void @llvm.memcpy{{.*}}(i8* [[COPY]], i8* [[ARG]], {{i32 8|i64 16}}, i32 {{.*}}, i1 false)
// CHECK: [[FN:%.*]] = bitcast i8* %2
// CHECK: call void [[FN]](%V17struct_resilience6MySize* {{.*}} %0, {{.*}} [[TEMP]], %swift.refcounted* %3)
// CHECK: ret void
return f(s)
}
// Structs with resilient storage from a different resilience domain require
// runtime metadata instantiation, just like generics.
public struct StructWithResilientStorage {
public let s: Size
public let ss: (Size, Size)
public let n: Int
public let i: ResilientInt
}
// Make sure we call a function to access metadata of structs with
// resilient layout, and go through the field offset vector in the
// metadata when accessing stored properties.
// CHECK-LABEL: define{{( protected)?}} {{i32|i64}} @_TFV17struct_resilience26StructWithResilientStorageg1nSi(%V17struct_resilience26StructWithResilientStorage* {{.*}})
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV17struct_resilience26StructWithResilientStorage()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], i32 3
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %V17struct_resilience26StructWithResilientStorage* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Si*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %Si, %Si* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Indirect enums with resilient payloads are still fixed-size.
public struct StructWithIndirectResilientEnum {
public let s: FunnyShape
public let n: Int
}
// CHECK-LABEL: define{{( protected)?}} {{i32|i64}} @_TFV17struct_resilience31StructWithIndirectResilientEnumg1nSi(%V17struct_resilience31StructWithIndirectResilientEnum* {{.*}})
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %V17struct_resilience31StructWithIndirectResilientEnum, %V17struct_resilience31StructWithIndirectResilientEnum* %0, i32 0, i32 1
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %Si, %Si* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Public metadata accessor for our resilient struct
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_TMaV17struct_resilience6MySize()
// CHECK: ret %swift.type* bitcast ([[INT]]* getelementptr inbounds {{.*}} @_TMfV17struct_resilience6MySize, i32 0, i32 1) to %swift.type*)
// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_StructWithResilientStorage(i8*)
// CHECK: [[FIELDS:%.*]] = alloca [4 x i8**]
// CHECK: [[VWT:%.*]] = load i8**, i8*** getelementptr inbounds ({{.*}} @_TMfV17struct_resilience26StructWithResilientStorage{{.*}}, [[INT]] -1)
// CHECK: [[FIELDS_ADDR:%.*]] = getelementptr inbounds [4 x i8**], [4 x i8**]* [[FIELDS]], i32 0, i32 0
// public let s: Size
// CHECK: [[FIELD_1:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 0
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_1]]
// public let ss: (Size, Size)
// CHECK: [[FIELD_2:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 1
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_2]]
// Fixed-layout aggregate -- we can reference a static value witness table
// public let n: Int
// CHECK: [[FIELD_3:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 2
// CHECK: store i8** getelementptr inbounds (i8*, i8** @_TWVBi{{32|64}}_, i32 {{.*}}), i8*** [[FIELD_3]]
// Resilient aggregate with one field -- make sure we don't look inside it
// public let i: ResilientInt
// CHECK: [[FIELD_4:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 3
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_4]]
// CHECK: call void @swift_initStructMetadata_UniversalStrategy([[INT]] 4, i8*** [[FIELDS_ADDR]], [[INT]]* {{.*}}, i8** [[VWT]])
// CHECK: store atomic %swift.type* {{.*}} @_TMfV17struct_resilience26StructWithResilientStorage{{.*}}, %swift.type** @_TMLV17struct_resilience26StructWithResilientStorage release,
// CHECK: ret void
| apache-2.0 |
ryanbaldwin/RealmSwiftFHIR | firekit/fhir-parser-resources/fhir-1.6.0/swift-3.1/template-resource-initializers.swift | 1 | 1097 | {% if klass.has_nonoptional %}
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(
{%- for nonop in klass.properties|rejectattr("nonoptional", "equalto", false) %}
{%- if loop.index is greaterthan 1 %}, {% endif -%}
{%- if "value" == nonop.name %}val{% else %}{{ nonop.name }}{% endif %}: {% if nonop.is_array %}[{% endif %}{{ nonop.class_name }}{% if nonop.is_array %}]{% endif %}
{%- endfor -%}
) {
self.init(json: nil)
{%- for nonop in klass.properties %}{% if nonop.nonoptional %}
{%- if nonop.is_array and nonop.is_native %}
self.{{ nonop.name }}.append(objectsIn: {{ nonop.name }}.map{ Realm{{ nonop.class_name }}(value: [$0]) })
{%- elif nonop.is_array %}
self.{{ nonop.name }}.append(objectsIn: {{ nonop.name }})
{%- else %}
self.{{ nonop.name }}{% if nonop|requires_realm_optional %}.value{% endif %} = {% if "value" == nonop.name %}val{% else %}{{ nonop.name }}{% endif %}
{%- endif %}
{%- endif %}{% endfor %}
}
{% endif -%} | apache-2.0 |
LearningSwift2/LearningApps | SimpleBallFun/SimpleBallFun/ViewController.swift | 1 | 2779 | //
// ViewController.swift
// SimpleBallFun
//
// Created by Phil Wright on 4/9/16.
// Copyright © 2016 Touchopia, LLC. All rights reserved.
//
import UIKit
import QuartzCore
class ViewController: UIViewController, UICollisionBehaviorDelegate {
let leftIdentifier = "leftSide"
let rightIdentifier = "rightSide"
let velocity: CGFloat = 1.0
var ball = UIView(frame: CGRect(x: 100, y: 100, width: 40, height: 40))
var animator = UIDynamicAnimator()
override func viewDidLoad() {
super.viewDidLoad()
self.ball.backgroundColor = UIColor.redColor()
self.ball.layer.cornerRadius = 20
self.view.addSubview(self.ball)
self.animator = UIDynamicAnimator(referenceView: self.view)
addCollision()
pushLeft()
}
func pushLeft() {
let push = UIPushBehavior(items: [self.ball], mode: .Instantaneous)
push.pushDirection = CGVector(dx: -1 * velocity, dy: 0)
self.animator.addBehavior(push)
}
func pushRight() {
let push = UIPushBehavior(items: [self.ball], mode: .Instantaneous)
push.pushDirection = CGVector(dx: 1 * velocity, dy: 0)
self.animator.addBehavior(push)
}
func addCollision() {
let collisionBehavior = UICollisionBehavior(items: [self.ball])
collisionBehavior.collisionDelegate = self
let frame = self.view.frame
let leftFromPoint = CGPoint(x: 0, y: 0)
let leftToPoint = CGPoint(x: 0, y: frame.size.height)
collisionBehavior.addBoundaryWithIdentifier(leftIdentifier,
fromPoint:leftFromPoint,
toPoint: leftToPoint)
let rightFromPoint = CGPoint(x: frame.size.width, y: 0)
let rightToPoint = CGPoint(x: frame.size.width, y: frame.size.height)
collisionBehavior.addBoundaryWithIdentifier(rightIdentifier,
fromPoint: rightFromPoint,
toPoint: rightToPoint)
self.animator.addBehavior(collisionBehavior)
}
func collisionBehavior(behavior: UICollisionBehavior, endedContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?) {
if let identifier = identifier as? String {
print(identifier)
if identifier == leftIdentifier {
pushRight()
}
if identifier == rightIdentifier {
pushLeft()
}
}
}
}
| apache-2.0 |
Obisoft2017/BeautyTeamiOS | BeautyTeam/BeautyTeam/ViewController.swift | 1 | 4103 | //
// ViewController.swift
// BeautyTeam
//
// Created by 李昂 on 3/29/16.
// Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Alamofire.request(.GET, "https://www.obisoft.com.cn/api/").responseJSON(completionHandler: {
// resp in
//
// print(resp.request)
// print(resp.response)
// print(resp.data)
// print(resp.result)
//
// guard let JSON = resp.result.value else {
// return
// }
// print(JSON)
// })
// Alamofire.request(.POST, "https://www.obisoft.com.cn/api/Register", parameters: [
// "Email": "hkyla@obisoft.com.cn",
// "Password": "FbK7xr.fE9H/fh",
// "ConfirmPassword": "FbK7xr.fE9H/fh"
// ]).responseJSON {
// resp in
//
// guard let json = resp.result.value else {
// return
// }
// print(json)
// }
// Alamofire.request(.POST, "https://www.obisoft.com.cn/api/Login", parameters: [
// "Email": "hkyla@obisoft.com.cn",
// "Password": "Kn^GGs6R6hcbm#",
// "RememberMe": true.description
// ]).responseJSON {
// resp in
//
// guard let json = resp.result.value else {
// return
// }
// print(json)
// }
//
// Alamofire.request(.POST, "https://www.obisoft.com.cn/api/Log", parameters: [
// "HappenTime": "2016/4/12 15:00:00",
// "Description": "Blame the user",
// "HappenPlatform": "ios",
// "version": "v1.0.0"
// ]).responseJSON {
// resp in
//
// guard let json = resp.result.value else {
// return
// }
// print(json)
// }
// Alamofire.request(.POST, "https://www.obisoft.com.cn/api/ForgotPassword", parameters: [
// "Email": "hkyla@obisoft.com.cn",
// "ByEmailNotBySms": true.description
// ]).responseJSON {
// resp in
//
// guard let json = resp.result.value else {
// fatalError()
// }
// print(json)
// }
Alamofire.request(.POST, "https://www.obisoft.com.cn/api/ChangePassword/", parameters: [
"OldPassword": "Kn^GGs6", // Kn^GGs6R6hcbm#
"NewPassword": "123456",
"ConfirmPassword": "123456"
]).responseJSON {
resp in
guard let json = resp.result.value else {
fatalError()
}
print(json)
}
Alamofire.request(.POST, "https://www.obisoft.com.cn/api/SetSchoolAccount", parameters: [
"Account": "20155134",
"Password": "1q2w3e4r"
]).responseJSON {
resp in
guard let json = resp.result.value else {
fatalError()
}
print(json)
}
// Alamofire.request(.GET, "https://www.obisoft.com.cn/api/latestversion", parameters: [
// "Platform": "ios",
// "CurrentVersion": "v0.0.1"
// ]).responseJSON {
// resp in
//
// guard let json = resp.result.value else {
// return
// }
// print(json)
// }
// 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.
}
}
| apache-2.0 |
Onix-Systems/RainyRefreshControl | Example/RainyRefreshControl Demo/ViewController.swift | 1 | 1536 | //
// ViewController.swift
// RainyRefreshControl Demo
//
// Created by Anton Dolzhenko on 04.01.17.
// Copyright © 2017 Onix-Systems. All rights reserved.
//
import UIKit
import RainyRefreshControl
class ViewController: UIViewController {
fileprivate var items = Array(1...10).map{ "\($0)"}
@IBOutlet weak var tableView: UITableView!
fileprivate let refresh = RainyRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.barTintColor = UIColor.white
refresh.addTarget(self, action: #selector(ViewController.doRefresh), for: .valueChanged)
tableView.addSubview(refresh)
}
func doRefresh(){
let popTime = DispatchTime.now() + Double(Int64(3.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC);
DispatchQueue.main.asyncAfter(deadline: popTime) { () -> Void in
self.refresh.endRefreshing()
}
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
cell.config()
return cell
}
}
| mit |
uber/RIBs | ios/tutorials/tutorial1/TicTacToe/Root/RootRouter.swift | 1 | 1670 | //
// Copyright (c) 2017. Uber Technologies
//
// 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 RIBs
protocol RootInteractable: Interactable, LoggedOutListener {
var router: RootRouting? { get set }
var listener: RootListener? { get set }
}
protocol RootViewControllable: ViewControllable {
func present(viewController: ViewControllable)
}
final class RootRouter: LaunchRouter<RootInteractable, RootViewControllable>, RootRouting {
init(interactor: RootInteractable,
viewController: RootViewControllable,
loggedOutBuilder: LoggedOutBuildable) {
self.loggedOutBuilder = loggedOutBuilder
super.init(interactor: interactor, viewController: viewController)
interactor.router = self
}
override func didLoad() {
super.didLoad()
let loggedOut = loggedOutBuilder.build(withListener: interactor)
self.loggedOut = loggedOut
attachChild(loggedOut)
viewController.present(viewController: loggedOut.viewControllable)
}
// MARK: - Private
private let loggedOutBuilder: LoggedOutBuildable
private var loggedOut: ViewableRouting?
}
| apache-2.0 |
BBBInc/AlzPrevent-ios | researchline/IdentificationViewController.swift | 1 | 1878 | //
// EnterPasswordViewController.swift
// researchline
//
// Created by riverleo on 2015. 11. 8..
// Copyright © 2015년 bbb. All rights reserved.
//
import UIKit
class IdentificationViewController: UIViewController {
var passcode = ""
@IBOutlet weak var password: UITextField!
@IBOutlet weak var nextButton: UIBarButtonItem!
@IBAction func passwordChange(sender: AnyObject) {
var sizeOfCode = password.text!.characters.count
let passwordText: String = password.text!
let toNumber = Int(passwordText)
if(passwordText == ""){
return
}else if((toNumber == nil)){
password.text = self.passcode
}
if(sizeOfCode > 4){
password.text = self.passcode
sizeOfCode = password.text!.characters.count
}else{
self.passcode = password.text!
}
if(sizeOfCode == 4){
nextButton.enabled = true
Constants.userDefaults.setObject(self.passcode, forKey: "passcode")
}else{
nextButton.enabled = false
Constants.userDefaults.removeObjectForKey("passcode")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| bsd-3-clause |
alessandrostone/RIABrowser | RIABrowser/object/ObjectExtractor.swift | 1 | 6014 | //
// ObjectExtractor.swift
// RIABrowser
//
// Created by Yoshiyuki Tanaka on 2015/05/10.
// Copyright (c) 2015 Yoshiyuki Tanaka. All rights reserved.
//
import UIKit
import RealmSwift
class ObjectExtractor {
typealias Extractor = ()-> [RIAObject]
typealias ArrayPropertyExtractor = (object:Object, name:String) -> [Object]?
var realmPath = Realm.defaultPath
private var classes = [String:Extractor]()
private var arrayPropertyExtractors = [String:ArrayPropertyExtractor]()
class var sharedInstance : ObjectExtractor {
struct Static {
static let instance : ObjectExtractor = ObjectExtractor()
}
return Static.instance
}
func registerClass<T:Object>(type:T.Type) {
var name = "\(type)".componentsSeparatedByString(".")[1]
let extractor:Extractor = {
var riaObjects = [RIAObject]()
let realmSwiftObjects = self.realm.objects(type)
for i in 0..<realmSwiftObjects.count {
riaObjects.append(self.convertToRIAObject(realmSwiftObjects[i]))
}
return riaObjects
}
classes["\(name)"] = extractor
let arrayPropertyExtractor:ArrayPropertyExtractor = {(object:Object, name:String) -> [Object]? in
var riaObjects = [Object]()
if let value = object.valueForKey(name) as? List<T> {
var objectList = [Object]()
for i in 0..<value.count {
objectList.append(value[i])
}
return objectList
}
return nil
}
arrayPropertyExtractors["\(name)"] = arrayPropertyExtractor
}
func unregisterClass<T:Object>(type:T.Type) {
var name = "\(type)".componentsSeparatedByString(".")[1]
classes.removeValueForKey("\(name)")
arrayPropertyExtractors.removeValueForKey("\(name)")
}
var classNames:[String] {
get {
var names = [String]()
for (className, extractor) in classes {
names.append(className)
}
return names;
}
}
func objects (className: String) -> [RIAObject] {
if let objects = classes[className]?() {
return objects
}
return [RIAObject]()
}
private var realm:Realm {
get {
return Realm(path: realmPath)
}
}
private func convertToRIAObject(object: Object) -> RIAObject {
let riaObject = RIAObject(name: object.objectSchema.className)
let primaryKeyProperty:Property? = object.objectSchema.primaryKeyProperty
for property in object.objectSchema.properties {
var isPrimaryKey = false
if property == primaryKeyProperty {
isPrimaryKey = true
}
let riaProperty = convertToRIAProperty(object, name: property.name, type: property.type)
riaObject.addProperty(riaProperty, primaryKey: isPrimaryKey)
}
return riaObject
}
private func convertToRIAProperty(object: Object, name: String,type :PropertyType) -> RIAProperty {
switch type {
case .String:
return stringToString(object, name: name)
case .Int:
return intToString(object, name: name)
case .Float:
return floatToString(object, name: name)
case .Double:
return doubleToString(object, name: name)
case .Bool:
return boolToString(object, name: name)
case .Date:
return dateToString(object, name: name)
case .Data:
return dataToString(object, name: name)
case .Object:
return objectToString(object, name: name)
case .Array:
return arrayToString(object, name: name)
case .Any:
return anyToString(object, name: name)
}
}
private func stringToString(object: Object, name: String) -> RIAStringProperty {
let value = object.valueForKey(name) as! String
return RIAStringProperty(type: "String", name: name, stringValue: value)
}
private func intToString(object: Object, name: String) -> RIAStringProperty {
let value = object.valueForKey(name) as! Int
return RIAStringProperty(type: "Int", name: name, stringValue: String(value))
}
private func floatToString(object: Object, name: String) -> RIAStringProperty {
let value = object.valueForKey(name) as! Float
return RIAStringProperty(type: "Float", name: name, stringValue: "\(value)")
}
private func doubleToString(object: Object, name: String) -> RIAStringProperty {
let value = object.valueForKey(name) as! Double
return RIAStringProperty(type: "Double", name: name, stringValue: "\(value)")
}
private func boolToString(object: Object, name: String) -> RIAStringProperty {
let value = object.valueForKey(name) as! Bool
return RIAStringProperty(type: "Double", name: name, stringValue: "\(value)")
}
private func dateToString(object: Object, name: String) -> RIAStringProperty {
let value = object.valueForKey(name) as! NSDate
return RIAStringProperty(type: "Date", name: name, stringValue: "\(value)")
}
private func dataToString(object: Object, name: String) -> RIAProperty {
let value = object.valueForKey(name) as! NSData
return RIADataProperty(type: "Data", name: name, dataValue: value)
}
private func objectToString(object: Object, name: String) -> RIAObjectProperty {
let value = object.valueForKey(name) as! Object
return RIAObjectProperty(type: "Object", name: name, objectValue:convertToRIAObject(value))
}
private func arrayToString(object: Object, name: String) -> RIAArrayProperty {
var objects:[Object]?
for (className, extractor) in arrayPropertyExtractors {
objects = extractor(object: object, name: name)
if objects != nil {
break
}
}
var riaObjects = objects?.map({ (o) -> RIAObject in
return self.convertToRIAObject(o)
})
if riaObjects == nil {
riaObjects = [RIAObject]()
}
return RIAArrayProperty(type: "Object", name: name, arrayValue:riaObjects!)
}
private func anyToString (object: Object, name: String) -> RIAStringProperty {
return RIAStringProperty(type: "Any", name: name, stringValue: "Any type is not supported")
}
}
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/Map Detail/Presenter Tests/BeforeMapDetailSceneLoads_MapDetailPresenterShould.swift | 1 | 513 | import EurofurenceApplication
import EurofurenceModel
import XCTest
import XCTEurofurenceModel
class BeforeMapDetailSceneLoads_MapDetailPresenterShould: XCTestCase {
func testNotBindAnySceneComponents() {
let identifier = MapIdentifier.random
let viewModelFactory = FakeMapDetailViewModelFactory(expectedMapIdentifier: identifier)
let context = MapDetailPresenterTestBuilder().with(viewModelFactory).build(for: identifier)
XCTAssertNil(context.scene.capturedTitle)
}
}
| mit |
NoryCao/zhuishushenqi | zhuishushenqi/Root/Views/ZSVoiceCategoryHeaderView.swift | 1 | 1460 | //
// QSCatalogPresenter.swift
// zhuishushenqi
//
// Created yung on 2017/4/21.
// Copyright © 2017年 QS. All rights reserved.
//
// Template generated by Juanpe Catalán @JuanpeCMiOS
//
class ZSVoiceCategoryHeaderView: UITableViewHeaderFooterView {
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
setupSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupSubviews() {
imageView = UIImageView(frame: CGRect.zero)
contentView.addSubview(imageView)
titleLabel = UILabel(frame: CGRect.zero)
titleLabel.textColor = UIColor.black
titleLabel.textAlignment = .left
titleLabel.font = UIFont.systemFont(ofSize: 17)
contentView.addSubview(titleLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
guard let image = imageView.image else {
titleLabel.frame = CGRect(x: 20, y: 0, width: bounds.width, height: bounds.height)
return
}
imageView.frame = CGRect(x: 20, y: bounds.height/2 - image.size.height/2, width: image.size.width, height: image.size.height)
titleLabel.frame = CGRect(x: imageView.frame.maxX + 10, y: 0, width: bounds.width, height: bounds.height)
}
var imageView:UIImageView!
var titleLabel:UILabel!
}
| mit |
mpclarkson/StravaSwift | Sources/StravaSwift/GeneralExtensions.swift | 1 | 718 | //
// GeneralExtensions.swift
// StravaSwift
//
// Created by Matthew on 19/11/2015.
// Copyright © 2015 Matthew Clarkson. All rights reserved.
//
import Foundation
extension RawRepresentable {
init?(optionalRawValue rawValue: RawValue?) {
guard let rawValue = rawValue, let value = Self(rawValue: rawValue) else { return nil }
self = value
}
}
extension DateFormatter {
func dateFromString(optional string: String?) -> Date? {
guard let string = string else { return nil }
return date(from: string)
}
}
extension URL {
init?(optionalString string: String?) {
guard let string = string else { return nil }
self.init(string: string)
}
}
| mit |
mike4aday/SwiftlySalesforce | Sources/SwiftlySalesforce/Errors/RequestError.swift | 1 | 217 | import Foundation
struct RequestError: Error, CustomDebugStringConvertible {
let debugDescription: String
init(_ debugDescription: String) {
self.debugDescription = debugDescription
}
}
| mit |
jjluebke/pigeon | Pigeon/FlightController.swift | 1 | 7894 | //
// FlightController.swift
// Pigeon
//
// Created by Jason Luebke on 5/22/15.
// Copyright (c) 2015 Jason Luebke. All rights reserved.
//
import Foundation
import CoreMotion
class FlightController : HardwareInterfaceDelegate {
var hardwareInterface:HardwareInterface!
var motion = CMMotionManager()
var delegate: Pigeon!
var attitude: Attitude!
var motors: Outputs = Array(count: 4, repeatedValue: 0)
var rotationRate: RotationRate!
var vitalsTimer: NSTimer!
var pids: PIDs!
var inputs:Inputs!
var yawTarget: Double = 0
var gyroStable: Bool = false
var pidRateVals: PIDValues!
var pidStabVals: PIDValues!
init () {
motion.showsDeviceMovementDisplay = true
motion.deviceMotionUpdateInterval = 1/60
hardwareInterface = PWMAudio()
hardwareInterface.delegate = self
}
func setupPIDs () {
pids = PIDs()
pidRateVals = PIDValues(
name: "ratePID",
delegate: delegate,
pitch : ["p": 0.5, "i": 1, "imax": 50],
roll : ["p": 0.5, "i": 1, "imax": 50],
yaw : ["p": 0.5, "i": 1, "imax": 50]
)
pidStabVals = PIDValues(
name: "stabPID",
delegate: delegate,
pitch : ["p": 4.5, "i": 1],
roll : ["p": 4.5, "i": 1],
yaw : ["p": 4.5, "i": 1]
)
self.updatePIDvalues()
}
func updatePIDvalues () {
pids.pitchRate = PID(pids: pidRateVals.pitch)
pids.rollRate = PID(pids: pidRateVals.roll)
pids.yawRate = PID(pids: pidRateVals.yaw)
pids.pitchStab = PID(pids: pidStabVals.pitch)
pids.rollStab = PID(pids: pidStabVals.roll)
pids.yawStab = PID(pids: pidStabVals.yaw)
}
func arm (data: Array<AnyObject>, ack: SocketAckEmitter?) {
motion.startDeviceMotionUpdatesUsingReferenceFrame(CMAttitudeReferenceFrame.XArbitraryCorrectedZVertical, toQueue: NSOperationQueue.mainQueue(), withHandler: self.didReceiveMotionUpdate)
vitalsTimer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "sendVitals:", userInfo: nil, repeats: true)
}
func disarm (data: Array<AnyObject>, ack: SocketAckEmitter?) {
motion.stopDeviceMotionUpdates()
gyroStable = false
delegate.armed(self.gyroStable)
if hardwareInterface.available {
hardwareInterface.stop()
}
}
@objc func sendVitals (timer: NSTimer) {
if attitude != nil {
delegate.sendPayload(attitude, motors: self.motors)
}
}
func didReceiveMotionUpdate (data: CMDeviceMotion?, error: NSError?) {
if let motion = data {
attitude = Attitude(data: motion.attitude)
rotationRate = RotationRate(data: motion.rotationRate)
}
if gyroStable {
self.processFrameData()
} else {
self.initGyro()
}
}
func initGyro () {
let threshhold: Double = 5
let diff: Double = abs(toDeg(attitude.roll) - toDeg(attitude.pitch))
if diff <= threshhold {
self.gyroStable = true
delegate.armed(self.gyroStable)
hardwareInterface.start()
} else {
delegate.armed(self.gyroStable)
}
}
func processInput(data: Array<AnyObject>, ack: SocketAckEmitter?) {
self.inputs = scaleInputs(data[0] as! Inputs)
}
func processFrameData () {
self.updatePIDvalues()
// from CM.rotationRate
var rollRate: Double!
var pitchRate: Double!
var yawRate: Double!
// from CM.attitude
var roll: Double!
var pitch: Double!
var yaw: Double!
// from the tx
var rcThro: Double = 0
var rcRoll: Double = 0
var rcPitch: Double = 0
var rcYaw: Double = 0
// outputs
var rollStabOutput: Double!
var pitchStabOutput: Double!
var yawStabOutput: Double!
var rollOutput: Double!
var pitchOutput: Double!
var yawOutput: Double!
if self.inputs != nil {
pitchRate = toDeg(rotationRate.x)
rollRate = toDeg(rotationRate.y)
yawRate = toDeg(rotationRate.z)
roll = toDeg(attitude.roll)
pitch = toDeg(attitude.pitch)
yaw = toDeg(attitude.yaw)
rcThro = inputs["thro"]!
rcRoll = inputs["roll"]!
rcPitch = inputs["pitch"]!
rcYaw = inputs["yaw"]!
rollStabOutput = constrain(pids.rollStab.calculate(rcRoll - roll, scaler: 1), low: -250, high: 250)
pitchStabOutput = constrain(pids.pitchStab.calculate(rcPitch - pitch, scaler: 1), low: -250, high: 250)
yawStabOutput = constrain(pids.yawStab.calculate(self.wrap180(yawTarget - yaw), scaler: 1), low: -360, high: 360)
// is pilot asking for yaw change
// if so feed directly to rate pid (overwriting yaw stab output)
if(abs(rcYaw ) > 5) {
yawStabOutput = rcYaw
yawTarget = yaw // remember this yaw for when pilot stops
}
rollOutput = constrain(pids.rollRate.calculate(rollStabOutput - rollRate, scaler: 1), low: -500, high: 500)
pitchOutput = constrain(pids.pitchRate.calculate(pitchStabOutput - pitchRate, scaler: 1), low: -500, high: 500)
yawOutput = constrain(pids.yawRate.calculate(yawStabOutput - yawRate, scaler: 1), low: -500, high: 500)
if rcThro >= 50 {
motors[0] = mapValue(rcThro + rollOutput + pitchOutput - yawOutput, inMin: -500, inMax: 1250, outMin: EscRange.Low.rawValue, outMax: EscRange.High.rawValue)
motors[1] = mapValue(rcThro + rollOutput - pitchOutput + yawOutput, inMin: -500, inMax: 1250, outMin: EscRange.Low.rawValue, outMax: EscRange.High.rawValue)
motors[2] = mapValue(rcThro - rollOutput + pitchOutput + yawOutput, inMin: -500, inMax: 1250, outMin: EscRange.Low.rawValue, outMax: EscRange.High.rawValue)
motors[3] = mapValue(rcThro - rollOutput - pitchOutput - yawOutput, inMin: -500, inMax: 1250, outMin: EscRange.Low.rawValue, outMax: EscRange.High.rawValue)
}
if hardwareInterface.available {
hardwareInterface.write(motors)
}
}
}
func wrap180 (yaw: Double) -> Double {
return yaw < -180 ? yaw + 360 : (yaw > 180 ? yaw - 360: yaw)
}
func toDeg(rad: Double) -> Double {
return (rad * 180) / M_PI
}
func constrain (n: Double, low: Double, high: Double) -> Double {
return min(max(n, low), high)
}
func scaleInputs(inputs: Inputs) -> Inputs {
var result: Inputs = Inputs()
var high: Double
var low: Double
for(channel, value) in inputs {
switch channel {
case "pitch":
fallthrough
case "roll":
high = RollRange.High.rawValue
low = RollRange.Low.rawValue
case "yaw":
high = YawRange.High.rawValue
low = YawRange.Low.rawValue
default:
high = ThroRange.High.rawValue
low = ThroRange.Low.rawValue
}
result[channel] = mapValue(value, inMin: InputRange.Low.rawValue, inMax: InputRange.High.rawValue, outMin: low, outMax: high)
}
return result
}
} | apache-2.0 |
kriscarle/dev4outdoors-parkbook | Parkbook/FirstViewController.swift | 1 | 3748 | //
// FirstViewController.swift
// Parkbook
//
// Created by Kristofor Carle on 4/12/15.
// Copyright (c) 2015 Kristofor Carle. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController, BeaconManagerDelegate, UIAlertViewDelegate {
var mapView: MGLMapView!
var beaconManager: BeaconManager?
var beaconList = Dictionary<String, Bool>() // major+minor -> yes or no
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initializeMap()
self.beaconManager = sharedBeaconManager
self.beaconManager?.delegate = self
self.beaconManager?.start()
}
func initializeMap() {
//set your MapBox account token - see: https://www.mapbox.com/account/apps/
let mapBoxAccountToken = "INSERT TOKEN HERE"
//frame for the map view
let mapFrame = CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height)
//instantiate a MapBoxGL map
mapView = MGLMapView(frame: mapFrame, accessToken: mapBoxAccountToken)
mapView.tintColor = UIColor(red: 30, green: 30, blue: 30, alpha: 1)
//set the default style
mapView.useBundledStyleNamed("outdoors")
//zoom map to area of interest
let lat = 38.889487
let lng = -77.0347045
let centerCoordinate = CLLocationCoordinate2DMake(lat, lng)
mapView.setCenterCoordinate(centerCoordinate, zoomLevel: 14, animated: true)
//add the map to the parent view
view.addSubview(mapView)
}
func insideRegion(regionIdentifier: String) {
// println("VC insideRegion \(regionIdentifier)")
//self.beaconList[regionIdentifier] = true
//self.setUI()
sendLocalNotificationWithMessage(regionIdentifier, playSound: false) // Only send notification when we enter
}
func didEnterRegion(regionIdentifier: String) {
println("VC didEnterRegion \(regionIdentifier)")
//self.beaconList[regionIdentifier] = true
//self.setUI()
sendLocalNotificationWithMessage(regionIdentifier, playSound: false) // Only send notification when we enter
}
func didExitRegion(regionIdentifier: String) {
println("VC didExitRegion \(regionIdentifier)")
//self.beaconList[regionIdentifier] = nil
//self.setUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func sendLocalNotificationWithMessage(message: String!, playSound: Bool) {
let notification:UILocalNotification = UILocalNotification()
let alertMessage = "Checked into park: " + message;
notification.alertBody = alertMessage
if(playSound) {
// classic star trek communicator beep
// http://www.trekcore.com/audio/
//
// note: convert mp3 and wav formats into caf using:
// "afconvert -f caff -d LEI16@44100 -c 1 in.wav out.caf"
// http://stackoverflow.com/a/10388263
notification.soundName = "tos_beep.caf";
}
UIApplication.sharedApplication().scheduleLocalNotification(notification)
let alertView = UIAlertController(title: "Checked In", message: alertMessage, preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alertView, animated: true, completion: nil)
}
}
| mit |
brave/browser-ios | Shared/Logger.swift | 17 | 3652 | /* 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 XCGLogger
public struct Logger {}
// MARK: - Singleton Logger Instances
public extension Logger {
static let logPII = false
/// Logger used for recording happenings with Sync, Accounts, Providers, Storage, and Profiles
static let syncLogger = RollingFileLogger(filenameRoot: "sync", logDirectoryPath: Logger.logFileDirectoryPath())
/// Logger used for recording frontend/browser happenings
static let browserLogger = RollingFileLogger(filenameRoot: "browser", logDirectoryPath: Logger.logFileDirectoryPath())
/// Logger used for recording interactions with the keychain
static let keychainLogger: XCGLogger = Logger.fileLoggerWithName("keychain")
/// Logger used for logging database errors such as corruption
static let corruptLogger: RollingFileLogger = {
let logger = RollingFileLogger(filenameRoot: "corruptLogger", logDirectoryPath: Logger.logFileDirectoryPath())
logger.newLogWithDate(Date())
return logger
}()
/**
Return the log file directory path. If the directory doesn't exist, make sure it exist first before returning the path.
:returns: Directory path where log files are stored
*/
static func logFileDirectoryPath() -> String? {
if let cacheDir = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first {
let logDir = "\(cacheDir)/Logs"
if !FileManager.default.fileExists(atPath: logDir) {
do {
try FileManager.default.createDirectory(atPath: logDir, withIntermediateDirectories: false, attributes: nil)
return logDir
} catch _ as NSError {
return nil
}
} else {
return logDir
}
}
return nil
}
static private func fileLoggerWithName(_ name: String) -> XCGLogger {
let log = XCGLogger()
if let logFileURL = urlForLogNamed(name) {
let fileDestination = FileDestination(
owner: log,
writeToFile: logFileURL.absoluteString,
identifier: "com.mozilla.firefox.filelogger.\(name)"
)
log.add(destination: fileDestination)
}
return log
}
static private func urlForLogNamed(_ name: String) -> URL? {
guard let logDir = Logger.logFileDirectoryPath() else {
return nil
}
return URL(string: "\(logDir)/\(name).log")
}
/**
Grabs all of the configured logs that write to disk and returns them in NSData format along with their
associated filename.
- returns: Tuples of filenames to each file's contexts in a NSData object
*/
static func diskLogFilenamesAndData() throws -> [(String, Data?)] {
var filenamesAndURLs = [(String, URL)]()
filenamesAndURLs.append(("browser", urlForLogNamed("browser")!))
filenamesAndURLs.append(("keychain", urlForLogNamed("keychain")!))
// Grab all sync log files
do {
filenamesAndURLs += try syncLogger.logFilenamesAndURLs()
filenamesAndURLs += try corruptLogger.logFilenamesAndURLs()
filenamesAndURLs += try browserLogger.logFilenamesAndURLs()
} catch _ {
}
return filenamesAndURLs.map { ($0, try? Data(contentsOf: URL(fileURLWithPath: $1.absoluteString))) }
}
}
| mpl-2.0 |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/Common/Nodes/Generators/Oscillators/Triangle/AKTriangleOscillator.swift | 1 | 6956 | //
// AKTriangleOscillator.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// Bandlimited triangleoscillator This is a bandlimited triangle oscillator
/// ported from the "triangle" function from the Faust programming language.
///
/// - parameter frequency: In cycles per second, or Hz.
/// - parameter amplitude: Output Amplitude.
/// - parameter detuningOffset: Frequency offset in Hz.
/// - parameter detuningMultiplier: Frequency detuning multiplier
///
public class AKTriangleOscillator: AKVoice {
// MARK: - Properties
internal var internalAU: AKTriangleOscillatorAudioUnit?
internal var token: AUParameterObserverToken?
private var frequencyParameter: AUParameter?
private var amplitudeParameter: AUParameter?
private var detuningOffsetParameter: AUParameter?
private var detuningMultiplierParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet(newValue) {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// In cycles per second, or Hz.
public var frequency: Double = 440 {
willSet(newValue) {
if frequency != newValue {
if internalAU!.isSetUp() {
frequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.frequency = Float(newValue)
}
}
}
}
/// Output Amplitude.
public var amplitude: Double = 1 {
willSet(newValue) {
if amplitude != newValue {
if internalAU!.isSetUp() {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.amplitude = Float(newValue)
}
}
}
}
/// Frequency offset in Hz.
public var detuningOffset: Double = 0 {
willSet(newValue) {
if detuningOffset != newValue {
if internalAU!.isSetUp() {
detuningOffsetParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.detuningOffset = Float(newValue)
}
}
}
}
/// Frequency detuning multiplier
public var detuningMultiplier: Double = 1 {
willSet(newValue) {
if detuningMultiplier != newValue {
if internalAU!.isSetUp() {
detuningMultiplierParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.detuningMultiplier = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
override public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize the oscillator with defaults
public convenience override init() {
self.init(frequency: 440)
}
/// Initialize this oscillator node
///
/// - parameter frequency: In cycles per second, or Hz.
/// - parameter amplitude: Output Amplitude.
/// - parameter detuningOffset: Frequency offset in Hz.
/// - parameter detuningMultiplier: Frequency detuning multiplier
///
public init(
frequency: Double,
amplitude: Double = 0.5,
detuningOffset: Double = 0,
detuningMultiplier: Double = 1) {
self.frequency = frequency
self.amplitude = amplitude
self.detuningOffset = detuningOffset
self.detuningMultiplier = detuningMultiplier
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x7472696f /*'trio'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKTriangleOscillatorAudioUnit.self,
asComponentDescription: description,
name: "Local AKTriangleOscillator",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKTriangleOscillatorAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
}
guard let tree = internalAU?.parameterTree else { return }
frequencyParameter = tree.valueForKey("frequency") as? AUParameter
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
detuningOffsetParameter = tree.valueForKey("detuningOffset") as? AUParameter
detuningMultiplierParameter = tree.valueForKey("detuningMultiplier") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.frequencyParameter!.address {
self.frequency = Double(value)
} else if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
} else if address == self.detuningOffsetParameter!.address {
self.detuningOffset = Double(value)
} else if address == self.detuningMultiplierParameter!.address {
self.detuningMultiplier = Double(value)
}
}
}
internalAU?.frequency = Float(frequency)
internalAU?.amplitude = Float(amplitude)
internalAU?.detuningOffset = Float(detuningOffset)
internalAU?.detuningMultiplier = Float(detuningMultiplier)
}
/// Function create an identical new node for use in creating polyphonic instruments
public override func duplicate() -> AKVoice {
let copy = AKTriangleOscillator(frequency: self.frequency, amplitude: self.amplitude, detuningOffset: self.detuningOffset, detuningMultiplier: self.detuningMultiplier)
return copy
}
/// Function to start, play, or activate the node, all do the same thing
public override func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public override func stop() {
self.internalAU!.stop()
}
}
| apache-2.0 |
OperatorFoundation/Postcard | Postcard/PostcardUITests/PostcardUITests.swift | 1 | 1261 | //
// PostcardUITests.swift
// PostcardUITests
//
// Created by Adelita Schule on 4/15/16.
// Copyright © 2016 operatorfoundation.org. All rights reserved.
//
import XCTest
class PostcardUITests: 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 |
apple/swift | validation-test/compiler_crashers_fixed/00435-swift-typebase-getcanonicaltype.swift | 65 | 460 | // 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
protocol c : e {
class A {
print() -> Int = {
}
}
typealias e
| apache-2.0 |
eneko/JSONRequest | Sources/JSONRequestVerbs.swift | 1 | 7199 | //
// JSONRequestVerbs.swift
// JSONRequest
//
// Created by Eneko Alonso on 1/11/16.
// Copyright © 2016 Hathway. All rights reserved.
//
public enum JSONRequestHttpVerb: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
}
// MARK: Instance basic sync/async
public extension JSONRequest {
public func send(method: JSONRequestHttpVerb, url: String, queryParams: JSONObject? = nil,
payload: AnyObject? = nil, headers: JSONObject? = nil) -> JSONResult {
return submitSyncRequest(method, url: url, queryParams: queryParams,
payload: payload, headers: headers)
}
public func send(method: JSONRequestHttpVerb, url: String, queryParams: JSONObject? = nil,
payload: AnyObject? = nil, headers: JSONObject? = nil,
complete: (result: JSONResult) -> Void) {
submitAsyncRequest(method, url: url, queryParams: queryParams, payload: payload,
headers: headers, complete: complete)
}
}
// MARK: Instance HTTP Sync methods
public extension JSONRequest {
public func get(url: String, queryParams: JSONObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return send(.GET, url: url, queryParams: queryParams, headers: headers)
}
public func post(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return send(.POST, url: url, queryParams: queryParams, payload: payload,
headers: headers)
}
public func put(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return send(.PUT, url: url, queryParams: queryParams, payload: payload,
headers: headers)
}
public func patch(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return send(.PATCH, url: url, queryParams: queryParams, payload: payload,
headers: headers)
}
public func delete(url: String, queryParams: JSONObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return send(.DELETE, url: url, queryParams: queryParams, headers: headers)
}
}
// MARK: Instance HTTP Async methods
public extension JSONRequest {
public func get(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil,
complete: (result: JSONResult) -> Void) {
send(.GET, url: url, queryParams: queryParams, headers: headers,
complete: complete)
}
public func post(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
send(.POST, url: url, queryParams: queryParams, payload: payload,
headers: headers, complete: complete)
}
public func put(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
send(.PUT, url: url, queryParams: queryParams, payload: payload,
headers: headers, complete: complete)
}
public func patch(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
send(.PATCH, url: url, queryParams: queryParams, payload: payload,
headers: headers, complete: complete)
}
public func delete(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
send(.DELETE, url: url, queryParams: queryParams, headers: headers,
complete: complete)
}
}
// MARK: Class HTTP Sync methods
public extension JSONRequest {
public class func get(url: String, queryParams: JSONObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return JSONRequest().get(url, queryParams: queryParams, headers: headers)
}
public class func post(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return JSONRequest().post(url, queryParams: queryParams, payload: payload,
headers: headers)
}
public class func put(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return JSONRequest().put(url, queryParams: queryParams, payload: payload,
headers: headers)
}
public class func patch(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return JSONRequest().patch(url, queryParams: queryParams, payload: payload,
headers: headers)
}
public class func delete(url: String, queryParams: JSONObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return JSONRequest().delete(url, queryParams: queryParams, headers: headers)
}
}
// MARK: Class HTTP Async methods
public extension JSONRequest {
public class func get(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil,
complete: (result: JSONResult) -> Void) {
JSONRequest().get(url, queryParams: queryParams, headers: headers, complete: complete)
}
public class func post(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
JSONRequest().post(url, queryParams: queryParams, payload: payload, headers: headers,
complete: complete)
}
public class func put(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
JSONRequest().put(url, queryParams: queryParams, payload: payload, headers: headers,
complete: complete)
}
public class func patch(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
JSONRequest().patch(url, queryParams: queryParams, payload: payload, headers: headers,
complete: complete)
}
public class func delete(url: String, queryParams: JSONObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
JSONRequest().delete(url, queryParams: queryParams, headers: headers, complete: complete)
}
}
| mit |
apple/swift | test/NameLookup/Inputs/private_import/Most.swift | 14 | 248 | @available(*, deprecated, message: "got Boast version")
public struct Boast { } // Not deprecated in Host
@available(*, deprecated, message: "got Boast version")
public enum Coast { case downhill } // Also defined in Ghost
| apache-2.0 |
samodom/TestableCoreLocation | TestableCoreLocation/CLLocationManager/CLLocationManagerStopMonitoringForRegionSpy.swift | 1 | 3016 | //
// CLLocationManagerStopMonitoringForRegionSpy.swift
// TestableCoreLocation
//
// Created by Sam Odom on 3/6/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import CoreLocation
import FoundationSwagger
import TestSwagger
public extension CLLocationManager {
private static let stopMonitoringForRegionCalledKeyString = UUIDKeyString()
private static let stopMonitoringForRegionCalledKey =
ObjectAssociationKey(stopMonitoringForRegionCalledKeyString)
private static let stopMonitoringForRegionCalledReference =
SpyEvidenceReference(key: stopMonitoringForRegionCalledKey)
private static let stopMonitoringForRegionRegionKeyString = UUIDKeyString()
private static let stopMonitoringForRegionRegionKey =
ObjectAssociationKey(stopMonitoringForRegionRegionKeyString)
private static let stopMonitoringForRegionRegionReference =
SpyEvidenceReference(key: stopMonitoringForRegionRegionKey)
/// Spy controller for ensuring that a location manager has had `stopMonitoring(for:)`
/// called on it.
public enum StopMonitoringForRegionSpyController: SpyController {
public static let rootSpyableClass: AnyClass = CLLocationManager.self
public static let vector = SpyVector.direct
public static let coselectors = [
SpyCoselectors(
methodType: .instance,
original: #selector(CLLocationManager.stopMonitoring(for:)),
spy: #selector(CLLocationManager.spy_stopMonitoring(for:))
)
] as Set
public static let evidence = [
stopMonitoringForRegionCalledReference,
stopMonitoringForRegionRegionReference
] as Set
public static let forwardsInvocations = false
}
/// Spy method that replaces the true implementation of `stopMonitoring(for:)`
dynamic public func spy_stopMonitoring(for region: CLRegion) {
stopMonitoringForRegionCalled = true
stopMonitoringForRegionRegion = region
}
/// Indicates whether the `stopMonitoring(for:)` method has been called on this object.
public final var stopMonitoringForRegionCalled: Bool {
get {
return loadEvidence(with: CLLocationManager.stopMonitoringForRegionCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: CLLocationManager.stopMonitoringForRegionCalledReference)
}
}
/// Provides the region passed to `stopMonitoring(for:)` if called.
public final var stopMonitoringForRegionRegion: CLRegion? {
get {
return loadEvidence(with: CLLocationManager.stopMonitoringForRegionRegionReference) as? CLRegion
}
set {
let reference = CLLocationManager.stopMonitoringForRegionRegionReference
guard let region = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(region, with: reference)
}
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/09361-swift-metatypetype-get.swift | 11 | 217 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
{
}
class c {
func d<T : b
var b = <d
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/11466-swift-sourcemanager-getmessage.swift | 11 | 232 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var d {
protocol P {
enum e {
var d = [ 3 e {
( {
class
case ,
| mit |
lanffy/phpmanual | swift/Demo.playground/Contents.swift | 1 | 1493 | import UIKit
let colors = [
"Air Force Blue":(red:93,green:138,blue:168),
"Bittersweet":(red:254,green:111,blue:94),
"Canary Yellow":(red:255,green:239,blue:0),
"Dark Orange":(red:255,green:140,blue:0),
"Electric Violet":(red:143,green:0,blue:255),
"Fern":(red:113,green:188,blue:120),
"Gamboge":(red:228,green:155,blue:15),
"Hollywood Cerise":(red:252,green:0,blue:161),
"Icterine":(red:252,green:247,blue:94),
"Jazzberry Jam":(red:165,green:11,blue:94)
]
print(colors)
var backView = UIView(frame: CGRect.init(x: 0.0, y: 0.0, width: 320.0, height: CGFloat(colors.count * 50)))
backView.backgroundColor = UIColor.black
backView
var index = 0
for (colorName,rgbTuple) in colors {
let colorStripe = UILabel.init(frame: CGRect.init(x: 0.0, y: CGFloat(index * 50 + 5), width: 320.0, height: 40.0))
colorStripe.backgroundColor = UIColor.init(
red: CGFloat(rgbTuple.red) / 255.0,
green: CGFloat(rgbTuple.green) / 255.0,
blue: CGFloat(rgbTuple.blue) / 255.0,
alpha: 1.0
)
let colorNameLable = UILabel.init(frame: CGRect.init(x: 0.0, y: 0.0, width: 300.0, height: 40.0))
colorNameLable.font = UIFont.init(name: "Arial", size: 24.0)
colorNameLable.textColor = UIColor.black
colorNameLable.textAlignment = NSTextAlignment.right
colorNameLable.text = colorName
colorStripe.addSubview(colorNameLable)
backView.addSubview(colorStripe)
index += 1
}
backView
| apache-2.0 |
GitHubCha2016/ZLSwiftFM | ZLSwiftFM/ZLSwiftFMTests/ZLSwiftFMTests.swift | 1 | 965 | //
// ZLSwiftFMTests.swift
// ZLSwiftFMTests
//
// Created by ZXL on 2017/5/15.
// Copyright © 2017年 zl. All rights reserved.
//
import XCTest
@testable import ZLSwiftFM
class ZLSwiftFMTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
EasySwift/EasySwift | Carthage/Checkouts/EasySearchBar/TestEasySearchBar/TestEasySearchBar/ViewController.swift | 2 | 1428 | //
// ViewController.swift
// TestEasySearchBar
//
// Created by yuanxiaojun on 16/7/1.
// Copyright © 2016年 袁晓钧. All rights reserved.
//
import UIKit
import EasySearchBar
class ViewController: UIViewController {
fileprivate var searchBar: EasySearchBar?
override func viewDidLoad() {
super.viewDidLoad()
// 搜索框
self.searchBar = EasySearchBar(frame: CGRect(x: 0, y: 100, width: self.view.frame.size.width, height: 30))
self.searchBar?.easySearchBarPlaceholder = "搜索课程"
self.searchBar?.easyBackgroundColor = UIColor.cyan
self.view.addSubview(self.searchBar!)
self.searchBar?.easyCancelBTClickedBlock({ (search) in
print("点击了取消按钮")
search?.text = ""
})
self.searchBar?.easySearchBarTextDidBeginEditing({ (search) in
print("开始编辑" + (search?.text!)!)
})
self.searchBar?.easySearchBarTextDidChange({ (search, searchText) in
print("内容改变" + searchText!)
})
self.searchBar?.easySearchBarTextDidEndEditing({ (search) in
print("结束输入")
})
self.searchBar?.easySearchBarSearchButtonClickedBlock({ (search) in
print("点击键盘搜索" + (search?.text!)!)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| apache-2.0 |
tardieu/swift | test/Constraints/associated_types.swift | 6 | 598 | // RUN: %target-typecheck-verify-swift
protocol Runcible {
associatedtype Runcee
}
class Mince {
init() {}
}
class Spoon : Runcible {
init() {}
typealias Runcee = Mince
}
class Owl<T:Runcible> {
init() {}
func eat(_ what: T.Runcee, with: T) { }
}
func owl1() -> Owl<Spoon> {
return Owl<Spoon>()
}
func owl2() -> Owl<Spoon> {
return Owl()
}
func owl3() {
Owl<Spoon>().eat(Mince(), with:Spoon())
}
// "Can't access associated types through class-constrained generic parameters"
// (https://bugs.swift.org/browse/SR-726)
func spoon<S: Spoon>(_ s: S) {
let _: S.Runcee?
}
| apache-2.0 |
leizh007/HiPDA | HiPDA/HiPDA/Sections/EventBus/EventBus.swift | 1 | 914 | //
// EventBus.swift
// HiPDA
//
// Created by leizh007 on 16/9/13.
// Copyright © 2016年 HiPDA. All rights reserved.
//
import RxSwift
import RxCocoa
import Delta
/// 事件总线
struct EventBus: StoreType {
static var shared = EventBus(State())
var state: Variable<State>
init(_ state: State) {
self.state = Variable(state)
}
}
extension EventBus {
var activeAccount: Driver<LoginResult?> {
return state.value.accountChanged
.observeOn(MainScheduler.instance)
.asDriver(onErrorJustReturn: nil)
}
var unReadMessagesCount: Driver<UnReadMessagesCountModel> {
let model = UnReadMessagesCountModel(threadMessagesCount: 0, privateMessagesCount: 0, friendMessagesCount: 0)
return state.value.unReadMessagesCount
.observeOn(MainScheduler.instance)
.asDriver(onErrorJustReturn: model)
}
}
| mit |
Mioke/SwiftArchitectureWithPOP | SwiftyArchitecture/Base/RxExtension/RxExtension.swift | 1 | 890 | //
// RxExtension.swift
// SAD
//
// Created by jiangkelan on 16/10/2017.
// Copyright © 2017 KleinMioke. All rights reserved.
//
import Foundation
import RxSwift
extension Reactive {
public func loadData<T: ApiInfoProtocol>(with params: [String: Any]?)
-> Observable<T.ResultType> where Base: API<T> {
return Observable.create { observer in
self.base.loadData(with: params).response({ (api, data, error) in
if let error = error {
observer.onError(error)
}
else if let data = data {
observer.on(.next(data))
observer.onCompleted()
}
})
return Disposables.create(with: self.base.cancel)
}
}
}
extension BehaviorSubject {
public var value: Element? {
return try? value()
}
}
| mit |
zwaldowski/ParksAndRecreation | Latest/HTMLDocument.playground/Sources/HTMLDocument.swift | 1 | 11065 | import Darwin
private struct XML2 {
typealias CBufferCreate = @convention(c) () -> UnsafeMutableRawPointer?
typealias CBufferFree = @convention(c) (UnsafeMutableRawPointer?) -> Void
typealias CBufferGetContent = @convention(c) (UnsafeRawPointer?) -> UnsafePointer<CChar>
typealias CDocFree = @convention(c) (UnsafeMutableRawPointer) -> Void
typealias CDocAddFragment = @convention(c) (UnsafeMutableRawPointer) -> UnsafeMutableRawPointer?
typealias CDocGetRootElement = @convention(c) (UnsafeRawPointer) -> UnsafeMutableRawPointer?
typealias CNodeAddChild = @convention(c) (_ parent: UnsafeMutableRawPointer, _ cur: UnsafeRawPointer) -> UnsafeMutableRawPointer?
typealias CNodeUnlink = @convention(c) (UnsafeRawPointer) -> Void
typealias CNodeCopyProperty = @convention(c) (UnsafeRawPointer, UnsafePointer<CChar>) -> UnsafeMutablePointer<CChar>?
typealias CNodeCopyContent = @convention(c) (UnsafeRawPointer) -> UnsafeMutablePointer<CChar>?
typealias CHTMLNodeDump = @convention(c) (UnsafeMutableRawPointer?, UnsafeRawPointer, UnsafeRawPointer) -> Int32
typealias CHTMLReadMemory = @convention(c) (UnsafePointer<CChar>?, Int32, UnsafePointer<CChar>?, UnsafePointer<CChar>?, Int32) -> UnsafeMutableRawPointer?
// libxml/tree.h
let bufferCreate: CBufferCreate
let bufferFree: CBufferFree
let bufferGetContent: CBufferGetContent
let docFree: CDocFree
let docAddFragment: CDocAddFragment
let docGetRootElement: CDocGetRootElement
let nodeAddChild: CNodeAddChild
let nodeUnlink: CNodeUnlink
let nodeCopyProperty: CNodeCopyProperty
let nodeCopyContent: CNodeCopyContent
// libxml/HTMLtree.h
let htmlNodeDump: CHTMLNodeDump
// libxml/HTMLparser.h
let htmlReadMemory: CHTMLReadMemory
static let shared: XML2 = {
let handle = dlopen("/usr/lib/libxml2.dylib", RTLD_LAZY)
return XML2(
bufferCreate: unsafeBitCast(dlsym(handle, "xmlBufferCreate"), to: CBufferCreate.self),
bufferFree: unsafeBitCast(dlsym(handle, "xmlBufferFree"), to: CBufferFree.self),
bufferGetContent: unsafeBitCast(dlsym(handle, "xmlBufferContent"), to: CBufferGetContent.self),
docFree: unsafeBitCast(dlsym(handle, "xmlFreeDoc"), to: CDocFree.self),
docAddFragment: unsafeBitCast(dlsym(handle, "xmlNewDocFragment"), to: CDocAddFragment.self),
docGetRootElement: unsafeBitCast(dlsym(handle, "xmlDocGetRootElement"), to: CDocGetRootElement.self),
nodeAddChild: unsafeBitCast(dlsym(handle, "xmlAddChild"), to: CNodeAddChild.self),
nodeUnlink: unsafeBitCast(dlsym(handle, "xmlUnlinkNode"), to: CNodeUnlink.self),
nodeCopyProperty: unsafeBitCast(dlsym(handle, "xmlGetProp"), to: CNodeCopyProperty.self),
nodeCopyContent: unsafeBitCast(dlsym(handle, "xmlNodeGetContent"), to: CNodeCopyContent.self),
htmlNodeDump: unsafeBitCast(dlsym(handle, "htmlNodeDump"), to: CHTMLNodeDump.self),
htmlReadMemory: unsafeBitCast(dlsym(handle, "htmlReadMemory"), to: CHTMLReadMemory.self))
}()
}
/// A fragment of HTML parsed into a logical tree structure. A tree can have
/// many child nodes but only one element, the root element.
public final class HTMLDocument {
/// Element nodes in an tree structure. An element may have child nodes,
/// specifically element nodes, text nodes, comment nodes, or
/// processing-instruction nodes. It may also have subscript attributes.
public struct Node {
public struct Index {
fileprivate let variant: IndexVariant
}
/// A strong back-reference to the containing document.
public let document: HTMLDocument
fileprivate let handle: UnsafeRawPointer
}
/// Options you can use to control the parser's treatment of HTML.
private struct ParseOptions: OptionSet {
let rawValue: Int32
init(rawValue: Int32) { self.rawValue = rawValue }
// libxml/HTMLparser.h
/// Relaxed parsing
static let relaxedParsing = ParseOptions(rawValue: 1 << 0)
/// suppress error reports
static let noErrors = ParseOptions(rawValue: 1 << 5)
/// suppress warning reports
static let noWarnings = ParseOptions(rawValue: 1 << 6)
/// remove blank nodes
static let noBlankNodes = ParseOptions(rawValue: 1 << 8)
/// Forbid network access
static let noNetworkAccess = ParseOptions(rawValue: 1 << 11)
/// Do not add implied html/body... elements
static let noImpliedElements = ParseOptions(rawValue: 1 << 13)
}
fileprivate let handle: UnsafeMutableRawPointer
fileprivate init?<Input>(parsing input: Input) where Input: StringProtocol {
let options = [
.relaxedParsing, .noErrors, .noWarnings, .noBlankNodes,
.noNetworkAccess, .noImpliedElements
] as ParseOptions
guard let handle = input.withCString({ (cString) in
XML2.shared.htmlReadMemory(cString, Int32(strlen(cString)), nil, "UTF-8", options.rawValue)
}) else { return nil }
self.handle = handle
}
deinit {
XML2.shared.docFree(handle)
}
}
extension HTMLDocument {
/// Parses the HTML contents of a string source, such as "<p>Hello.</p>"
public static func parse<Input>(_ input: Input) -> Node? where Input: StringProtocol {
return HTMLDocument(parsing: input)?.root
}
/// Parses the HTML contents of an escaped string source, such as "<p>Hello.</p>".
public static func parseFragment<Input>(_ input: Input) -> Node? where Input: StringProtocol {
guard let document = HTMLDocument(parsing: "<html><body>\(input)"),
let textNode = document.root?.first?.first, textNode.kind == .text,
let rootNode = parse("<root>\(textNode.content)") else { return nil }
if let onlyChild = rootNode.first, rootNode.dropFirst().isEmpty {
return onlyChild
} else if let fragment = XML2.shared.docAddFragment(rootNode.document.handle) {
for child in rootNode {
XML2.shared.nodeUnlink(child.handle)
XML2.shared.nodeAddChild(fragment, child.handle)
}
return Node(document: rootNode.document, handle: fragment)
} else {
return nil
}
}
/// The root node of the receiver.
public var root: Node? {
guard let rootHandle = XML2.shared.docGetRootElement(handle) else { return nil }
return Node(document: self, handle: rootHandle)
}
}
// MARK: - Node
extension HTMLDocument.Node {
/// The different element types carried by an XML tree.
/// See http://www.w3.org/TR/REC-DOM-Level-1/
// libxml/tree.h
public enum Kind: Int32 {
case element = 1
case attribute = 2
case text = 3
case characterDataSection = 4
case entityReference = 5
case entity = 6
case processingInstruction = 7
case comment = 8
case document = 9
case documentType = 10
case documentFragment = 11
case notation = 12
case htmlDocument = 13
case documentTypeDefinition = 14
case elementDeclaration = 15
case attributeDeclaration = 16
case entityDeclaration = 17
case namespaceDeclaration = 18
case includeStart = 19
case includeEnd = 20
}
/// The natural type of this element.
/// See also [the W3C](http://www.w3.org/TR/REC-DOM-Level-1/).
public var kind: Kind {
// xmlNodePtr->type
return Kind(rawValue: handle.load(fromByteOffset: MemoryLayout<Int>.stride, as: Int32.self))!
}
/// The element tag. (ex: for `<foo />`, `"foo"`)
public var name: String {
// xmlNodePtr->name
guard let pointer = handle.load(fromByteOffset: MemoryLayout<Int>.stride * 2, as: UnsafePointer<CChar>?.self) else { return "" }
return String(cString: pointer)
}
/// If the node is a text node, the text carried directly by the node.
/// Otherwise, the aggregrate string of the values carried by this node.
public var content: String {
guard let buffer = XML2.shared.nodeCopyContent(handle) else { return "" }
defer { buffer.deallocate() }
return String(cString: buffer)
}
/// Request the content of the attribute `key`.
public subscript(key: String) -> String? {
guard let buffer = XML2.shared.nodeCopyProperty(handle, key) else { return nil }
defer { buffer.deallocate() }
return String(cString: buffer)
}
}
extension HTMLDocument.Node: Collection {
fileprivate enum IndexVariant: Equatable {
case valid(UnsafeRawPointer, offset: Int)
case invalid
}
public var startIndex: Index {
// xmlNodePtr->children
guard let firstHandle = handle.load(fromByteOffset: MemoryLayout<Int>.stride * 3, as: UnsafeRawPointer?.self) else { return Index(variant: .invalid) }
return Index(variant: .valid(firstHandle, offset: 0))
}
public var endIndex: Index {
return Index(variant: .invalid)
}
public subscript(position: Index) -> HTMLDocument.Node {
guard case .valid(let handle, _) = position.variant else { preconditionFailure("Index out of bounds") }
return HTMLDocument.Node(document: document, handle: handle)
}
public func index(after position: Index) -> Index {
// xmlNodePtr->next
guard case .valid(let handle, let offset) = position.variant,
let nextHandle = handle.load(fromByteOffset: MemoryLayout<Int>.stride * 6, as: UnsafeRawPointer?.self) else { return Index(variant: .invalid) }
let nextOffset = offset + 1
return Index(variant: .valid(nextHandle, offset: nextOffset))
}
}
extension HTMLDocument.Node: CustomDebugStringConvertible {
public var debugDescription: String {
let buffer = XML2.shared.bufferCreate()
defer { XML2.shared.bufferFree(buffer) }
_ = XML2.shared.htmlNodeDump(buffer, document.handle, handle)
return String(cString: XML2.shared.bufferGetContent(buffer))
}
}
extension HTMLDocument.Node: CustomReflectable {
public var customMirror: Mirror {
// Always use the debugDescription for `po`, none of this "▿" stuff.
return Mirror(self, unlabeledChildren: self, displayStyle: .struct)
}
}
// MARK: - Node Index
extension HTMLDocument.Node.Index: Comparable {
public static func == (lhs: HTMLDocument.Node.Index, rhs: HTMLDocument.Node.Index) -> Bool {
return lhs.variant == rhs.variant
}
public static func < (lhs: HTMLDocument.Node.Index, rhs: HTMLDocument.Node.Index) -> Bool {
switch (lhs.variant, rhs.variant) {
case (.valid(_, let lhs), .valid(_, let rhs)):
return lhs < rhs
case (.valid, .invalid):
return true
default:
return false
}
}
}
| mit |
crewshin/GasLog | Pods/Material/Sources/MaterialDepth.swift | 3 | 2387 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public typealias MaterialDepthType = (offset: CGSize, opacity: Float, radius: CGFloat)
public enum MaterialDepth {
case None
case Depth1
case Depth2
case Depth3
case Depth4
case Depth5
}
/**
:name: MaterialDepthToValue
*/
public func MaterialDepthToValue(depth: MaterialDepth) -> MaterialDepthType {
switch depth {
case .None:
return (offset: CGSizeZero, opacity: 0, radius: 0)
case .Depth1:
return (offset: CGSizeMake(0.2, 0.2), opacity: 0.5, radius: 1)
case .Depth2:
return (offset: CGSizeMake(0.4, 0.4), opacity: 0.5, radius: 2)
case .Depth3:
return (offset: CGSizeMake(0.6, 0.6), opacity: 0.5, radius: 3)
case .Depth4:
return (offset: CGSizeMake(0.8, 0.8), opacity: 0.5, radius: 4)
case .Depth5:
return (offset: CGSizeMake(1, 1), opacity: 0.5, radius: 5)
}
}
| mit |
iggym/PlaygroundNotes | Playground-Markup.playground/Pages/Page Navigation Examples.xcplaygroundpage/Contents.swift | 1 | 670 | //: [Previous](@previous) | [Home](Overview) | [Page Navigation Notes](Page%20Navigation)| [Next](@next)
/*:
## Page Navigation examples -
- - -
- - -
**Next Page:**
Open the next page in the playground. \
[Next Topic](@next)
- - -
**Previous Page:**
Open the previous page in the playground. \
[Previous](@previous)
- - -
**Named Page Link Reference:**
Open a named page in the playground. \
[Home](Overview) \
[Links Reference](Links)
[Go to the Page Navigation Notes](Page%20Navigation)
*/
//: ---
//: ---
//: [Next](@next) | [Home](Overview) | [List of Markup Examples](Examples%20Overview) | [[Page Navigation Notes](Page%20Navigation)]
| mit |
HongliYu/firefox-ios | Client/Frontend/Settings/HomePageSettingViewController.swift | 1 | 6678 | /* 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
class HomePageSettingViewController: SettingsTableViewController {
/* variables for checkmark settings */
let prefs: Prefs
var currentChoice: NewTabPage!
var hasHomePage = false
init(prefs: Prefs) {
self.prefs = prefs
super.init(style: .grouped)
self.title = Strings.AppMenuOpenHomePageTitleString
hasSectionSeparatorLine = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func generateSettings() -> [SettingSection] {
// The Home button and the New Tab page can be set independently
self.currentChoice = NewTabAccessors.getHomePage(self.prefs)
self.hasHomePage = HomeButtonHomePageAccessors.getHomePage(self.prefs) != nil
let onFinished = {
self.prefs.removeObjectForKey(PrefsKeys.HomeButtonHomePageURL)
self.prefs.setString(self.currentChoice.rawValue, forKey: NewTabAccessors.HomePrefKey)
self.tableView.reloadData()
}
let showTopSites = CheckmarkSetting(title: NSAttributedString(string: Strings.SettingsNewTabTopSites), subtitle: nil, accessibilityIdentifier: "HomeAsFirefoxHome", isEnabled: {return self.currentChoice == NewTabPage.topSites}, onChanged: {
self.currentChoice = NewTabPage.topSites
onFinished()
})
let showBookmarks = CheckmarkSetting(title: NSAttributedString(string: Strings.SettingsNewTabBookmarks), subtitle: nil, accessibilityIdentifier: "HomeAsBookmarks", isEnabled: {return self.currentChoice == NewTabPage.bookmarks}, onChanged: {
self.currentChoice = NewTabPage.bookmarks
onFinished()
})
let showHistory = CheckmarkSetting(title: NSAttributedString(string: Strings.SettingsNewTabHistory), subtitle: nil, accessibilityIdentifier: "HomeAsHistory", isEnabled: {return self.currentChoice == NewTabPage.history}, onChanged: {
self.currentChoice = NewTabPage.history
onFinished()
})
let showWebPage = WebPageSetting(prefs: prefs, prefKey: PrefsKeys.HomeButtonHomePageURL, defaultValue: nil, placeholder: Strings.CustomNewPageURL, accessibilityIdentifier: "HomeAsCustomURL", settingDidChange: { (string) in
self.currentChoice = NewTabPage.homePage
self.prefs.setString(self.currentChoice.rawValue, forKey: NewTabAccessors.HomePrefKey)
self.tableView.reloadData()
})
showWebPage.textField.textAlignment = .natural
let section = SettingSection(title: NSAttributedString(string: Strings.NewTabSectionName), footerTitle: NSAttributedString(string: Strings.NewTabSectionNameFooter), children: [showTopSites, showBookmarks, showHistory, showWebPage])
let topsitesSection = SettingSection(title: NSAttributedString(string: Strings.SettingsTopSitesCustomizeTitle), footerTitle: NSAttributedString(string: Strings.SettingsTopSitesCustomizeFooter), children: [TopSitesSettings(settings: self)])
let isPocketEnabledDefault = Pocket.IslocaleSupported(Locale.current.identifier)
let pocketSetting = BoolSetting(prefs: profile.prefs, prefKey: PrefsKeys.ASPocketStoriesVisible, defaultValue: isPocketEnabledDefault, attributedTitleText: NSAttributedString(string: Strings.SettingsNewTabPocket))
let pocketSection = SettingSection(title: NSAttributedString(string: Strings.SettingsNewTabASTitle), footerTitle: NSAttributedString(string: Strings.SettingsNewTabPocketFooter), children: [pocketSetting])
return [section, topsitesSection, pocketSection]
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.post(name: .HomePanelPrefsChanged, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.keyboardDismissMode = .onDrag
}
class TopSitesSettings: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var status: NSAttributedString {
let num = self.profile.prefs.intForKey(PrefsKeys.NumberOfTopSiteRows) ?? TopSitesRowCountSettingsController.defaultNumberOfRows
return NSAttributedString(string: String(format: Strings.TopSitesRowCount, num))
}
override var accessibilityIdentifier: String? { return "TopSitesRows" }
override var style: UITableViewCellStyle { return .value1 }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: Strings.ASTopSitesTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = TopSitesRowCountSettingsController(prefs: profile.prefs)
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
}
}
}
class TopSitesRowCountSettingsController: SettingsTableViewController {
let prefs: Prefs
var numberOfRows: Int32
static let defaultNumberOfRows: Int32 = 2
init(prefs: Prefs) {
self.prefs = prefs
numberOfRows = self.prefs.intForKey(PrefsKeys.NumberOfTopSiteRows) ?? TopSitesRowCountSettingsController.defaultNumberOfRows
super.init(style: .grouped)
self.title = Strings.AppMenuTopSitesTitleString
hasSectionSeparatorLine = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func generateSettings() -> [SettingSection] {
let createSetting: (Int32) -> CheckmarkSetting = { num in
return CheckmarkSetting(title: NSAttributedString(string: "\(num)"), subtitle: nil, isEnabled: { return num == self.numberOfRows }, onChanged: {
self.numberOfRows = num
self.prefs.setInt(Int32(num), forKey: PrefsKeys.NumberOfTopSiteRows)
self.tableView.reloadData()
})
}
let rows = [1, 2, 3, 4].map(createSetting)
let section = SettingSection(title: NSAttributedString(string: Strings.TopSitesRowSettingFooter), footerTitle: nil, children: rows)
return [section]
}
}
| mpl-2.0 |
zyhndesign/SDX_DG | sdxdg/sdxdg/ConsumeListViewController.swift | 1 | 4456 | //
// ConsumeListViewController.swift
// sdxdg
//
// Created by lotusprize on 16/12/26.
// Copyright © 2016年 geekTeam. All rights reserved.
//
import UIKit
import Alamofire
import ObjectMapper
class ConsumeListViewController: UITableViewController {
var storyBoard:UIStoryboard?
var naviController:UINavigationController?
let refresh = UIRefreshControl.init()
let pageLimit:Int = 10
var pageNum:Int = 0
var matchList:[Match] = []
let userId = LocalDataStorageUtil.getUserIdFromUserDefaults()
var vipName:String = ""
init(storyBoard:UIStoryboard, naviController:UINavigationController, vipName:String){
super.init(nibName: nil, bundle: nil)
self.storyBoard = storyBoard
self.naviController = naviController
self.vipName = vipName
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(FeedbackListCell.self, forCellReuseIdentifier: "feedbackCell")
//self.tableView.dataSource = self
refresh.backgroundColor = UIColor.white
refresh.tintColor = UIColor.lightGray
refresh.attributedTitle = NSAttributedString(string:"下拉刷新")
refresh.addTarget(self, action: #selector(refreshLoadingData), for: UIControlEvents.valueChanged)
self.tableView.addSubview(refresh)
loadCostumeData(limit: pageLimit,offset: 0)
self.tableView.tableFooterView = UIView.init(frame: CGRect.zero)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return matchList.count;
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 110.0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identify:String = "feedbackCell"
let cell:FeedbackListCell = tableView.dequeueReusableCell(withIdentifier: identify, for: indexPath) as! FeedbackListCell;
let match:Match = matchList[indexPath.row]
let matchLists:[Matchlist] = match.matchlists!
cell.initDataForCell(name:match.seriesname! , fbIcon1: matchLists[0].modelurl!, fbIcon2: matchLists[1].modelurl!,
fbIcon3: matchLists[2].modelurl!, fbIcon4: matchLists[3].modelurl!,time:match.createtime! ,storyBoard: storyBoard!, navigationController:naviController!)
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refreshLoadingData(){
loadCostumeData(limit: pageLimit,offset: pageLimit * pageNum)
}
func loadCostumeData(limit:Int, offset:Int){
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.label.text = "正在加载中..."
let parameters:Parameters = ["userId":userId, "vipName":vipName, "limit":limit,"offset":offset]
Alamofire.request(ConstantsUtil.APP_SHARE_HISTORY_URL,method:.post, parameters:parameters).responseObject { (response: DataResponse<MatchServerModel>) in
let matchServerModel = response.result.value
if (matchServerModel?.resultCode == 200){
if let matchServerModelList = matchServerModel?.object {
for matchModel in matchServerModelList{
self.matchList.insert(matchModel, at: 0)
self.pageNum = self.pageNum + 1
}
self.tableView.reloadData()
self.refresh.endRefreshing()
hud.label.text = "加载成功"
hud.hide(animated: true, afterDelay: 0.5)
}
else{
hud.label.text = "无推送历史数据"
hud.hide(animated: true, afterDelay: 0.5)
}
}
else{
hud.label.text = "加载失败"
hud.hide(animated: true, afterDelay: 0.5)
}
}
}
}
| apache-2.0 |
bmichotte/HSTracker | HSTracker/UIs/Trackers/OpponentDrawChance.swift | 3 | 1052 | //
// CountTextCellView.swift
// HSTracker
//
// Created by Benjamin Michotte on 6/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Cocoa
class OpponentDrawChance: TextFrame {
private let frameRect = NSRect(x: 0, y: 0, width: CGFloat(kFrameWidth), height: 71)
private let draw1Frame = NSRect(x: 70, y: 32, width: 68, height: 25)
private let draw2Frame = NSRect(x: 148, y: 32, width: 68, height: 25)
private let hand1Frame = NSRect(x: 70, y: 1, width: 68, height: 25)
private let hand2Frame = NSRect(x: 148, y: 1, width: 68, height: 25)
var drawChance1 = 0.0
var drawChance2 = 0.0
var handChance1 = 0.0
var handChance2 = 0.0
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
add(image: "opponent-chance-frame.png", rect: frameRect)
add(double: drawChance1, rect: draw1Frame)
add(double: drawChance2, rect: draw2Frame)
add(double: handChance1, rect: hand1Frame)
add(double: handChance2, rect: hand2Frame)
}
}
| mit |
ndleon09/SwiftSample500px | pictures/Modules/Detail/DetailModel.swift | 1 | 390 | //
// DetailModel.swift
// pictures
//
// Created by Nelson Dominguez on 05/11/15.
// Copyright © 2015 Nelson Dominguez. All rights reserved.
//
import Foundation
class DetailModel : NSObject {
var name: String?
var descriptionText: String?
var camera: String?
var userName: String?
var userImage: URL?
var latitude: Double?
var longitude: Double?
}
| mit |
windless/SqlWrapper | Pod/Classes/QueryComposedCondition.swift | 1 | 1085 | //
// SQLQueryComposedCondition.swift
// Pods
//
// Created by 钟建明 on 16/3/24.
//
//
import Foundation
public class QueryComposedCondition: Statement {
enum Operator: Statement {
case Or, And
var sqlString: String {
switch self {
case .Or:
return "OR"
case .And:
return "AND"
}
}
}
let left: Statement
let right: Statement
let opet: Operator
init(left: Statement, right: Statement, opet: Operator) {
self.left = left
self.right = right
self.opet = opet
}
public var sqlString: String {
return "(\(left.sqlString) \(opet.sqlString) \(right.sqlString))"
}
}
public func || (left: Statement, right: Statement) -> QueryComposedCondition {
return QueryComposedCondition(left: left, right: right, opet: .Or)
}
public func && (left: Statement, right: Statement) -> QueryComposedCondition {
return QueryComposedCondition(left: left, right: right, opet: .And)
}
| mit |
pietrocaselani/Trakt-Swift | Trakt/Models/Sync/HistoryParameters.swift | 1 | 838 | import Foundation
public final class HistoryParameters: Hashable {
public let type: HistoryType?
public let id: Int?
public let startAt, endAt: Date?
public init(type: HistoryType? = nil, id: Int? = nil, startAt: Date? = nil, endAt: Date? = nil) {
self.type = type
self.id = id
self.startAt = startAt
self.endAt = endAt
}
public var hashValue: Int {
var hash = 11
if let typeHash = type?.hashValue {
hash ^= typeHash
}
if let idHash = id?.hashValue {
hash ^= idHash
}
if let startAtHash = startAt?.hashValue {
hash ^= startAtHash
}
if let endAtHash = endAt?.hashValue {
hash ^= endAtHash
}
return hash
}
public static func == (lhs: HistoryParameters, rhs: HistoryParameters) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
| unlicense |
benlangmuir/swift | test/multifile/property-wrappers-sr12429.swift | 2 | 322 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -o %t/main %t/main.swift %S/Inputs/sr12429.swift
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main
// REQUIRES: executable_test
// https://github.com/apple/swift/issues/54868
let object = MyClass()
object.property = "value" | apache-2.0 |
nakajijapan/Shari | Shari-Demo/Base/AppDelegate.swift | 1 | 2159 | //
// AppDelegate.swift
// Shari
//
// Created by nakajijapan on 12/22/2015.
// Copyright (c) 2015 nakajijapan. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private 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 |
lambdaacademy/2015.01_swift | Lectures/1/LA_2015.01_1-Introduction_completed.playground/section-1.swift | 1 | 4108 | //
// Lambda Academy 2015.01 Lecture 1
//
import Foundation
// Define three variables – a string, an integer and a double with implicit data type
var strVar = "string"
var intVar = 1
var floVar = 2.0
// Define three constants with explicit data type
let str: String = "string"
let int: Int = 1
let flo: Double = 2.0
// Define string constants which is a concatenation of the string defined in previous example, a space, and the float defined in ex. 1.
let s = str + " " + "\(flo)"
// Create one array and one dictionary.
let arr = [1, 2, 3, 4]
let dic = ["a": 1, "b": 2, "c": 3]
// Append one element to the simple array and to the simple dictionary declared in previous example
let arr2 = arr + [5]
// Define a string variable that may or may not have a value, set it up to have a string equal to a string from previous example and then in the next line remove this value from a newly created variable (note that a variable that does not have a value is not the same as a variable with an empty string). Then assign this value back to string from previous example, what happens?
var maybeStr: String? = str
strVar = maybeStr!
maybeStr = nil
//strVar = maybeStr! // this will cause BAD_ACCESS,
// Use "if let" syntax to deal with the optional values being not set and rewrite a previous example setting strVar within if let
if let aStr = maybeStr {
strVar = aStr // we don't have to explicitly unwrap an optional now
}
// Define an empty dictionary containing characters as keys and integers as values.
var dic2: [Character: Int] = [:]
var dic3 = [Character: Int]()
// Write a for loop which populates the array with 10 entries of the following form:
for a in 1...10 {
let char = Character(UnicodeScalar(a+64))
dic2[char] = a
}
dic2
// Create switch statement on the following "myVeg" variable, print it within switch. If it is tomato print it twice, if its cocumber, print it in a form "My favourite tomato is cocumber" where cocumber is taken from myVeg
let vegetables = ["red pepper", "green pepper", "cocumber", "tomato"]
let myVeg = vegetables[Int(arc4random()%3)]
switch myVeg {
case "red pepper":
println(myVeg)
case "tomato":
println(myVeg)
println(myVeg)
case "cocumber":
println("My favourite veg is \(myVeg)")
default:
println(myVeg)
}
// Change the above example by adding one more case that uses pattern matching ("where" keyword) to match all "peppers"
switch myVeg {
case let x where x.hasSuffix("pepper"):
println("This is pepper called '\(x)'")
default:
println(myVeg)
}
// Write a function which takes two parameters
// 1. An integer (index)
// 2. A Function that returns a String
// This function should return a tuple consising of:
// 1. Vegetable name that is under specified index (if exists) or a default value taken from a function passed as a second argument
// 2. an index
// Call this function, passing different indexes
func testFunc(x: Int, def: ()->String) -> (String, Int) {
let res = (x >= 0 && x < vegetables.count) ? vegetables[x] : def()
return (res, x)
}
testFunc(4, { return "default" });
// Enums in Objective-C are just numbers, one of it's side effects possibility of performing calculations. for example the following if statement is true but it doesn't make sense:
if NSASCIIStringEncoding + NSNEXTSTEPStringEncoding == NSJapaneseEUCStringEncoding {
print("NSASCIIStringEncoding + NSNEXTSTEPStringEncoding == NSJapaneseEUCStringEncoding !!!")
}
// Swifts' enums doesn't have such issue.
// Define swift enum that represents few encoding types
enum Encoding {
case UTF8Encoding
case ASCIIEncoding
}
// Add an "extension" to the previous enumeration type that will adopt it to "Printable" protocol
extension Encoding: Printable {
var description: String {
get {
switch self {
case .UTF8Encoding:
return "UTF8Enconding"
case .ASCIIEncoding:
return "ASCIIEncoding"
}
}
}
}
Encoding.UTF8Encoding.description
| apache-2.0 |
STPDChen/STPDPopNotification | STPDPopNotification/STPDPopNotification/AppDelegate.swift | 1 | 2151 | //
// AppDelegate.swift
// STPDPopNotification
//
// Created by Chen Hao on 16/5/19.
// Copyright © 2016年 Chen Hao. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
FlyKite/DYJW-Swift | DYJW/Common/Extension/FloatingPanel.swift | 1 | 9987 | //
// FloatingPanel.swift
// FKTools
//
// Created by FlyKite on 2020/1/3.
// Copyright © 2020 Doge Studio. All rights reserved.
//
import UIKit
public enum TransitionType {
case presenting
case dismissing
}
public struct AnimationConfig {
public static var `default`: AnimationConfig = {
return AnimationConfig()
}()
/// 遮罩类型
public enum MaskType {
/// 无遮罩
case none
/// 黑色半透明遮罩
case black(alpha: CGFloat)
/// 指定颜色的遮罩
case color(color: UIColor)
}
/// present时的动画持续时间,默认值为0.35秒
public var duration: TimeInterval = 0.35
/// dismiss时的动画持续时间,若为nil则使用duration的值
public var durationForDismissing: TimeInterval?
/// 遮罩类型,默认值是alpha值为0.5的半透明黑色,
public var maskType: MaskType = .black(alpha: 0.5)
/// 可调整展示区域,默认nil不调整
public var targetFrame: CGRect?
/// 展示样式,默认为overFullScreen,可根据需求调整
public var presentationStyle: UIModalPresentationStyle = .overFullScreen
public init() { }
}
public typealias TransitionComplete = (_ isCancelled: Bool) -> Void
public protocol FloatingPanel: UIViewController {
/// 通过该方法返回动画配置,若返回nil则使用默认值
///
/// - Returns: 浮动面板显示隐藏时的动画配置
func floatingPanelAnimationConfigs() -> AnimationConfig
/// 转场动画开始之前该方法将被调用,该方法有一个默认的空实现,因此该方法是可选的(optional)
/// - Parameter type: 即将开始的转场类型
func floatingPanelWillBeginTransition(type: TransitionType)
/// 通过该方法更新浮动面板显示和隐藏时的约束值或其他属性
///
/// - Parameters:
/// - transitionType: 当前要执行的转场动画类型
/// - duration: 动画的总持续时长,该值与floatingPanelAnimationConfigs中返回的值一致
/// - completeCallback: 当动画结束时需要调用该闭包通知transitioningManager动画已结束
func floatingPanelUpdateViews(for transitionType: TransitionType, duration: TimeInterval, completeCallback: @escaping () -> Void)
/// 转场动画结束时该方法将被调用,该方法有一个默认的空实现,因此该方法是可选的(optional)
///
/// - Parameters:
/// - type: 已结束的转场类型
/// - wasCancelled: 是否中途被取消
func floatingPanelDidEndTransition(type: TransitionType, wasCancelled: Bool)
}
public extension FloatingPanel where Self: UIViewController {
/// 隐藏浮动面板(可交互的)
///
/// - Parameters:
/// - interactiveTransition: 传入一个交互控制器,在外部通过该对象去控制当前dismiss的进度
/// - animated: 是否展示动画
/// - completion: dismiss结束的回调
func dismiss(with interactiveTransition: UIViewControllerInteractiveTransitioning,
animated: Bool,
completion: (() -> Void)?) {
transitioningManager?.interactiveDismissingTransition = interactiveTransition
dismiss(animated: animated) {
self.transitioningManager?.interactiveDismissingTransition = nil
completion?()
}
}
func floatingPanelWillBeginTransition(type: TransitionType) { }
func floatingPanelDidEndTransition(type: TransitionType, wasCancelled: Bool) { }
}
extension UIViewController {
public func present(_ floatingPanel: FloatingPanel,
animated: Bool,
completion: (() -> Void)?) {
floatingPanel.configFloatingPanelAnimator(with: nil)
present(floatingPanel as UIViewController, animated: animated) {
floatingPanel.transitioningManager?.interactivePresentingTransition = nil
completion?()
}
}
public func present(_ floatingPanel: FloatingPanel,
interactiveTransition: UIViewControllerInteractiveTransitioning,
animated: Bool,
completion: (() -> Void)?) {
floatingPanel.configFloatingPanelAnimator(with: interactiveTransition)
present(floatingPanel as UIViewController, animated: animated) {
floatingPanel.transitioningManager?.interactivePresentingTransition = nil
completion?()
}
}
}
extension FloatingPanel where Self: UIViewController {
fileprivate func configFloatingPanelAnimator(with interactiveTransition: UIViewControllerInteractiveTransitioning?) {
let config = floatingPanelAnimationConfigs()
let transitioningManager = FloatingPanelTransitioning(floatingPanel: self, config: config)
transitioningManager.interactivePresentingTransition = interactiveTransition
modalPresentationStyle = config.presentationStyle
transitioningDelegate = transitioningManager
modalPresentationCapturesStatusBarAppearance = true
self.transitioningManager = transitioningManager
}
}
private var TransitioningManagerKey = "TransitioningManagerKey"
extension FloatingPanel {
fileprivate var transitioningManager: FloatingPanelTransitioning? {
get {
return objc_getAssociatedObject(self, &TransitioningManagerKey) as? FloatingPanelTransitioning
}
set {
objc_setAssociatedObject(self, &TransitioningManagerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
private class FloatingPanelTransitioning: NSObject, UIViewControllerTransitioningDelegate {
var interactivePresentingTransition: UIViewControllerInteractiveTransitioning?
var interactiveDismissingTransition: UIViewControllerInteractiveTransitioning?
let animator: FloatingPanelAnimator
init(floatingPanel: FloatingPanel, config: AnimationConfig) {
animator = FloatingPanelAnimator(floatingPanel: floatingPanel, config: config)
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
animator.transitionType = .presenting
return animator
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
animator.transitionType = .dismissing
return animator
}
func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactivePresentingTransition
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactiveDismissingTransition
}
}
private class FloatingPanelAnimator: NSObject, UIViewControllerAnimatedTransitioning {
unowned var floatingPanel: FloatingPanel
var transitionType: TransitionType = .presenting
let config: AnimationConfig
init(floatingPanel: FloatingPanel, config: AnimationConfig) {
self.floatingPanel = floatingPanel
self.config = config
}
private lazy var maskView: UIView = UIView()
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return config.duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let transitionType = self.transitionType
guard let view = transitionContext.view(forKey: transitionType.viewKey) else {
return
}
let container = transitionContext.containerView
if let targetFrame = config.targetFrame {
container.frame = targetFrame
}
view.frame = container.bounds
updateMask(for: transitionType, container: container)
container.addSubview(view)
floatingPanel.floatingPanelWillBeginTransition(type: transitionType)
let duration: TimeInterval
switch transitionType {
case .presenting: duration = config.duration
case .dismissing: duration = config.durationForDismissing ?? config.duration
}
floatingPanel.floatingPanelUpdateViews(for: transitionType, duration: duration) {
let wasCancelled = transitionContext.transitionWasCancelled
transitionContext.completeTransition(!wasCancelled)
self.floatingPanel.floatingPanelDidEndTransition(type: transitionType, wasCancelled: wasCancelled)
}
}
private func updateMask(for transitionType: TransitionType, container: UIView) {
if case .none = config.maskType {
return
}
switch transitionType {
case .presenting:
maskView.backgroundColor = config.maskType.maskColor
maskView.frame = container.bounds
maskView.alpha = 0
container.addSubview(maskView)
UIView.animate(withDuration: config.duration) {
self.maskView.alpha = 1
}
case .dismissing:
UIView.animate(withDuration: config.durationForDismissing ?? config.duration) {
self.maskView.alpha = 0
}
}
}
}
private extension TransitionType {
var viewKey: UITransitionContextViewKey {
switch self {
case .presenting: return .to
case .dismissing: return .from
}
}
}
private extension AnimationConfig.MaskType {
var maskColor: UIColor {
switch self {
case .none: return .clear
case let .black(alpha): return UIColor(white: 0, alpha: alpha)
case let .color(color): return color
}
}
}
| gpl-3.0 |
thierrybucco/Eureka | Source/Core/Cell.swift | 5 | 4884 | // Cell.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 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
/// Base class for the Eureka cells
open class BaseCell: UITableViewCell, BaseCellType {
/// Untyped row associated to this cell.
public var baseRow: BaseRow! { return nil }
/// Block that returns the height for this cell.
public var height: (() -> CGFloat)?
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public required override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
/**
Function that returns the FormViewController this cell belongs to.
*/
public func formViewController() -> FormViewController? {
var responder: AnyObject? = self
while responder != nil {
if let formVC = responder as? FormViewController {
return formVC
}
responder = responder?.next
}
return nil
}
open func setup() {}
open func update() {}
open func didSelect() {}
/**
If the cell can become first responder. By default returns false
*/
open func cellCanBecomeFirstResponder() -> Bool {
return false
}
/**
Called when the cell becomes first responder
*/
@discardableResult
open func cellBecomeFirstResponder(withDirection: Direction = .down) -> Bool {
return becomeFirstResponder()
}
/**
Called when the cell resigns first responder
*/
@discardableResult
open func cellResignFirstResponder() -> Bool {
return resignFirstResponder()
}
}
/// Generic class that represents the Eureka cells.
open class Cell<T: Equatable> : BaseCell, TypedCellType {
public typealias Value = T
/// The row associated to this cell
public weak var row: RowOf<T>!
/// Returns the navigationAccessoryView if it is defined or calls super if not.
override open var inputAccessoryView: UIView? {
if let v = formViewController()?.inputAccessoryView(for: row) {
return v
}
return super.inputAccessoryView
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
height = { UITableViewAutomaticDimension }
}
/**
Function responsible for setting up the cell at creation time.
*/
open override func setup() {
super.setup()
}
/**
Function responsible for updating the cell each time it is reloaded.
*/
open override func update() {
super.update()
textLabel?.text = row.title
textLabel?.textColor = row.isDisabled ? .gray : .black
detailTextLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText
}
/**
Called when the cell was selected.
*/
open override func didSelect() {}
override open var canBecomeFirstResponder: Bool {
return false
}
open override func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
if result {
formViewController()?.beginEditing(of: self)
}
return result
}
open override func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
if result {
formViewController()?.endEditing(of: self)
}
return result
}
/// The untyped row associated to this cell.
public override var baseRow: BaseRow! { return row }
}
| mit |
ppoh71/motoRoutes | motoRoutes/motoRouteOptions.swift | 1 | 2409 | //
// motoRoutesOptions.swift
// motoRoutes
//
// Created by Peter Pohlmann on 10.05.16.
// Copyright © 2016 Peter Pohlmann. All rights reserved.
//
import UIKit
class motoRouteOptions: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
//Picker 1 Data Stuff
let pickerData = [
["1","2","3","4","5","8","10","25","50","80","100","150","250","500","750","1000","1250","1500","1800","2000","2500","3000","3500","4000","4500"],
["0.0001", "0.0003", "0.0005", "0.0007", "0.0009", "0.001","0.003", "0.005", "0.007", "0.009", "0.01", "0.03", "0.05", "0.07", "0.1", "0.3", "0.5", "0.7", "0.9","1.0","1.1","1.2","1.3","1.5","2","3","4","5"],
["1","2","3","4","5","8","10","25","50","80"]
]
//vars to set from root controller
var sliceAmount = 1
var timeIntervalMarker = 0.001
//picker outlet
@IBOutlet var amountPicker: UIPickerView!
//
// override func super init
//
override func viewDidLoad() {
super.viewDidLoad()
self.amountPicker.dataSource = self;
self.amountPicker.delegate = self;
}
//picker funcs
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return pickerData.count
}
//picker funcs
func pickerView(
_ pickerView: UIPickerView,
numberOfRowsInComponent component: Int
) -> Int {
return pickerData[component].count
}
//picker funcs
func pickerView(
_ pickerView: UIPickerView,
titleForRow row: Int,
forComponent component: Int
) -> String? {
return pickerData[component][row]
}
//picker funcs
func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if let sliceAmountPicker = Int(pickerData[0][amountPicker.selectedRow(inComponent: 0)]) {
sliceAmount = Int(sliceAmountPicker)
}
if let timeIntervalPicker = Double(pickerData[1][amountPicker.selectedRow(inComponent: 1)]) {
timeIntervalMarker = timeIntervalPicker
}
if let arrayStepPicker = Double(pickerData[2][amountPicker.selectedRow(inComponent: 2)]){
globalArrayStep.gArrayStep = Int(arrayStepPicker)
}
}
}
| apache-2.0 |
LittoCats/coffee-mobile | CoffeeMobile/Base/Utils/NSFundationExtension/CMNSObjectExtension.swift | 1 | 194 | //
// NSObjectExtension.swift
// CoffeeMobile
//
// Created by 程巍巍 on 5/21/15.
// Copyright (c) 2015 Littocats. All rights reserved.
//
import Foundation
extension NSObject {
} | apache-2.0 |
HackBomo/Bomo | VuforiaSampleSwift/AppDelegate.swift | 1 | 3014 | //
// AppDelegate.swift
// VuforiaSample
//
// Created by Yoshihiro Kato on 2016/07/02.
// Copyright © 2016年 Yoshihiro Kato. All rights reserved.
//
import UIKit
import RealmSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let config = Realm.Configuration(
// Set the new schema version. This must be greater than the previously used
// version (if you've never set a schema version before, the version is 0).
schemaVersion: 4,
// Set the block which will be called automatically when opening a Realm with
// a schema version lower than the one set above
migrationBlock: { migration, oldSchemaVersion in
// We haven’t migrated anything yet, so oldSchemaVersion == 0
if (oldSchemaVersion < 4) {
// Nothing to do!
// Realm will automatically detect new properties and removed properties
// And will update the schema on disk automatically
}
})
// Tell Realm to use this new configuration object for the default Realm
Realm.Configuration.defaultConfiguration = config
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 |
Mindera/Alicerce | Sources/PerformanceMetrics/Trackers/PerformanceMetrics+MultiTracker.swift | 1 | 6431 | import Foundation
#if canImport(AlicerceCore)
import AlicerceCore
#endif
public extension PerformanceMetrics {
/// A performance metrics tracker that forwards performance measuring events to multiple trackers, while not doing
/// any tracking on its own.
class MultiTracker: PerformanceMetricsTracker {
/// The configured sub trackers.
public let trackers: [PerformanceMetricsTracker]
/// The tracker's tokenizer.
private let tokenizer = Tokenizer<Tag>()
/// The tracker's token dictionary, containing the mapping between internal and sub trackers' tokens.
private let tokens = Atomic<[Token<Tag> : [Token<Tag>]]>([:])
/// Creates a new performance metrics multi trcker instance, with the specified sub trackers.
///
/// - Parameters:
/// -trackers: The sub trackers to forward performance measuring events to.
public init(trackers: [PerformanceMetricsTracker]) {
assert(trackers.isEmpty == false, "🙅♂️ Trackers shouldn't be empty, since it renders this tracker useless!")
self.trackers = trackers
}
// MARK: - PerformanceMetricsTracker
/// Starts measuring the execution time of a specific code block identified by a particular identifier, by
/// propagating it to all registered sub tracker.
///
/// - Parameters:
/// - identifier: The metric's identifier, to group multiple metrics on the provider.
/// - Returns: A token identifying this particular metric instance.
public func start(with identifier: Identifier) -> Token<Tag> {
let token = tokenizer.next
let subTokens = startTrackers(with: identifier)
tokens.modify { $0[token] = subTokens }
return token
}
/// Stops measuring the execution of a specific code block while attaching any additional metric metadata, by
/// propagating it to all registered sub trackers.
///
/// - Parameters:
/// - token: The metric's identifying token, returned by `start(with:)`.
/// - metadata: The metric's metadata dictionary.
public func stop(with token: Token<Tag>, metadata: Metadata? = nil) {
guard let subTokens = tokens.modify({ $0.removeValue(forKey: token) }) else {
assertionFailure("🔥 Missing sub tokens for token \(token)!")
return
}
stopTrackers(with: subTokens, metadata: metadata)
}
/// Measures a given closure's execution time once it returns or throws (i.e. *synchronously*). An optional
/// metadata dictionary can be provided to be associated with the recorded metric. The metric is calculated on
/// all sub trackers.
///
/// - Parameters:
/// - identifier: The metric's identifier.
/// - metadata: The metric's metadata dictionary. The default is `nil`.
/// - execute: The closure to measure the execution time of.
/// - Returns: The closure's return value, if any.
/// - Throws: The closure's thrown error, if any.
@discardableResult
public func measure<T>(with identifier: Identifier,
metadata: Metadata? = nil,
execute: () throws -> T) rethrows -> T {
let subTokens = startTrackers(with: identifier)
defer { stopTrackers(with: subTokens, metadata: metadata) }
let measureResult = try execute()
return measureResult
}
/// Measures a given closure's execution time *until* an inner `stop` closure is invoked by it with an optional
/// metadata dictionary to be associated with the recorded metric. The metric is calculated on all sub trackers.
///
/// Should be used for asynchronous code, or when the metric metadata is only available during execution.
///
/// - Important: The `stop` closure should be called *before* the `execute` either returns or throws.
///
/// - Parameters:
/// - identifier: The metric's identifier.
/// - execute: The closure to measure the execution time of.
/// - stop: The closure to be invoked by `execute` to stop measuring the execution time, along with any
/// additional metric metadata.
/// - metadata: The metric's metadata dictionary.
/// - Returns: The closure's return value, if any.
/// - Throws: The closure's thrown error, if any.
@discardableResult
public func measure<T>(with identifier: Identifier,
execute: (_ stop: @escaping (_ metadata: Metadata?) -> Void) throws -> T) rethrows -> T {
let subTokens = startTrackers(with: identifier)
return try execute { [weak self] metadata in
self?.stopTrackers(with: subTokens, metadata: metadata)
}
}
// MARK: - Private
/// Starts measuring the execution time of a specific code block identified by a particular identifier on all
/// sub trackers.
///
/// - Parameters:
/// - identifier: The metric's identifier.
/// - Returns: The metric's identifying tokens for each sub tracker, returned by each tracker's `start(with:)`
/// in the same order as `trackers`.
private func startTrackers(with identifier: Identifier) -> [Token<Tag>] {
return trackers.map { $0.start(with: identifier) }
}
/// Stops measuring the execution of a specific code block while attaching any additional metric metadata on
/// all sub trackers.
///
/// - Important: The provided tokens order *must* match the `trackers` order.
///
/// - Parameters:
/// - subTokens: The metric's identifying tokens for each sub tracker, returned by each tracker's
/// `start(with:)`.
/// - metadata: The metric's metadata dictionary.
private func stopTrackers(with subTokens: [Token<Tag>], metadata: Metadata?) {
assert(subTokens.count == trackers.count, "😱 Number of sub tokens and sub trackers must match!")
zip(trackers, subTokens).forEach { tracker, token in tracker.stop(with: token, metadata: metadata) }
}
}
}
| mit |
Johennes/firefox-ios | AccountTests/FxAClient10Tests.swift | 1 | 6620 | /* 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/. */
@testable import Account
import FxA
import Shared
import UIKit
import Deferred
import XCTest
class FxAClient10Tests: LiveAccountTest {
func testUnwrapKey() {
let stretchedPW = "e4e8889bd8bd61ad6de6b95c059d56e7b50dacdaf62bd84644af7e2add84345d".hexDecodedData
let unwrapKey = FxAClient10.computeUnwrapKey(stretchedPW)
XCTAssertEqual(unwrapKey.hexEncodedString, "de6a2648b78284fcb9ffa81ba95803309cfba7af583c01a8a1a63e567234dd28")
}
func testClientState() {
let kB = "fd5c747806c07ce0b9d69dcfea144663e630b65ec4963596a22f24910d7dd15d".hexDecodedData
let clientState = FxAClient10.computeClientState(kB)!
XCTAssertEqual(clientState, "6ae94683571c7a7c54dab4700aa3995f")
}
func testErrorOutput() {
// Make sure we don't hide error details.
let error = NSError(domain: "test", code: 123, userInfo: nil)
let localError = FxAClientError.Local(error)
XCTAssertEqual(
localError.description,
"<FxAClientError.Local Error Domain=test Code=123 \"The operation couldn’t be completed. (test error 123.)\">")
XCTAssertEqual(
"\(localError)",
"<FxAClientError.Local Error Domain=test Code=123 \"The operation couldn’t be completed. (test error 123.)\">")
let remoteError = FxAClientError.Remote(RemoteError(code: 401, errno: 104,
error: "error", message: "message", info: "info"))
XCTAssertEqual(
remoteError.description,
"<FxAClientError.Remote 401/104: error (message)>")
XCTAssertEqual(
"\(remoteError)",
"<FxAClientError.Remote 401/104: error (message)>")
}
func testLoginSuccess() {
withVerifiedAccount { emailUTF8, quickStretchedPW in
let e = self.expectationWithDescription("")
let client = FxAClient10()
let result = client.login(emailUTF8, quickStretchedPW: quickStretchedPW, getKeys: true)
result.upon { result in
if let response = result.successValue {
XCTAssertNotNil(response.uid)
XCTAssertEqual(response.verified, true)
XCTAssertNotNil(response.sessionToken)
XCTAssertNotNil(response.keyFetchToken)
} else {
XCTAssertEqual(result.failureValue!.description, "")
}
e.fulfill()
}
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
func testLoginFailure() {
withVerifiedAccount { emailUTF8, _ in
let e = self.expectationWithDescription("")
let badPassword = FxAClient10.quickStretchPW(emailUTF8, password: "BAD PASSWORD".utf8EncodedData)
let client = FxAClient10()
let result = client.login(emailUTF8, quickStretchedPW: badPassword, getKeys: true)
result.upon { result in
if let response = result.successValue {
XCTFail("Got response: \(response)")
} else {
if let error = result.failureValue as? FxAClientError {
switch error {
case let .Remote(remoteError):
XCTAssertEqual(remoteError.code, Int32(400)) // Bad auth.
XCTAssertEqual(remoteError.errno, Int32(103)) // Incorrect password.
case let .Local(error):
XCTAssertEqual(error.description, "")
}
} else {
XCTAssertEqual(result.failureValue!.description, "")
}
}
e.fulfill()
}
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
func testKeysSuccess() {
withVerifiedAccount { emailUTF8, quickStretchedPW in
let e = self.expectationWithDescription("")
let client = FxAClient10()
let login: Deferred<Maybe<FxALoginResponse>> = client.login(emailUTF8, quickStretchedPW: quickStretchedPW, getKeys: true)
let keys: Deferred<Maybe<FxAKeysResponse>> = login.bind { (result: Maybe<FxALoginResponse>) in
switch result {
case let .Failure(error):
return Deferred(value: .Failure(error))
case let .Success(loginResponse):
return client.keys(loginResponse.value.keyFetchToken)
}
}
keys.upon { result in
if let response = result.successValue {
XCTAssertEqual(32, response.kA.length)
XCTAssertEqual(32, response.wrapkB.length)
} else {
XCTAssertEqual(result.failureValue!.description, "")
}
e.fulfill()
}
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
func testSignSuccess() {
withVerifiedAccount { emailUTF8, quickStretchedPW in
let e = self.expectationWithDescription("")
let client = FxAClient10()
let login: Deferred<Maybe<FxALoginResponse>> = client.login(emailUTF8, quickStretchedPW: quickStretchedPW, getKeys: true)
let sign: Deferred<Maybe<FxASignResponse>> = login.bind { (result: Maybe<FxALoginResponse>) in
switch result {
case let .Failure(error):
return Deferred(value: .Failure(error))
case let .Success(loginResponse):
let keyPair = RSAKeyPair.generateKeyPairWithModulusSize(1024)
return client.sign(loginResponse.value.sessionToken, publicKey: keyPair.publicKey)
}
}
sign.upon { result in
if let response = result.successValue {
XCTAssertNotNil(response.certificate)
// A simple test that we got a reasonable certificate back.
XCTAssertEqual(3, response.certificate.componentsSeparatedByString(".").count)
} else {
XCTAssertEqual(result.failureValue!.description, "")
}
e.fulfill()
}
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
}
| mpl-2.0 |
ashfurrow/FunctionalReactiveAwesome | Pods/RxSwift/RxSwift/RxSwift/Observables/Implementations/Defer.swift | 2 | 1695 | //
// Defer.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/19/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Defer_<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.Element
typealias Parent = Defer<Element>
let parent: Parent
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let disposable = parent.eval().flatMap { result in
return success(result.subscribe(self))
}.recoverWith { e in
trySendError(observer, e)
self.dispose()
return success(DefaultDisposable())
}
return disposable.get()
}
func on(event: Event<Element>) {
trySend(observer, event)
switch event {
case .Next:
break
case .Error:
dispose()
case .Completed:
dispose()
}
}
}
class Defer<Element> : Producer<Element> {
typealias Factory = () -> RxResult<Observable<Element>>
let observableFactory : Factory
init(observableFactory: Factory) {
self.observableFactory = observableFactory
}
override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = Defer_(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
func eval() -> RxResult<Observable<Element>> {
return observableFactory()
}
} | mit |
austinzheng/swift-compiler-crashes | fixed/03773-swift-polymorphicfunctiontype-get.swift | 11 | 231 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct g<c{func f{}class d{class B:let:{class B<T where f:c>:B | mit |
hivinau/LivingElectro | iOS/LivingElectro/LivingElectro/TitleCell.swift | 1 | 1155 | //
// TitleCell.swift
// LivingElectro
//
// Created by Aude Sautier on 14/05/2017.
// Copyright © 2017 Hivinau GRAFFE. All rights reserved.
//
import UIKit
@objc(TitleCell)
public class TitleCell: UICollectionViewCell {
@IBOutlet weak var titleLabel: PaddingLabel!
public override var isSelected: Bool {
didSet {
titleLabel.textColor = isSelected ? .white : .gray
}
}
public var titleValue: String? {
didSet {
titleLabel.text = titleValue
titleLabel.sizeToFit()
}
}
public override func layoutSubviews() {
super.layoutSubviews()
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.textAlignment = .center
titleLabel.textColor = isSelected ? .white : .gray
if let font = UIFont(name: "Helvetica", size: 14.0) {
titleLabel.font = font
}
}
public override func prepareForReuse() {
super.prepareForReuse()
titleLabel.text?.removeAll()
}
}
| mit |
readium/r2-streamer-swift | r2-streamer-swift/Parser/EPUB/Extensions/Presentation+EPUB.swift | 1 | 2237 | //
// Presentation+EPUB.swift
// r2-streamer-swift
//
// Created by Mickaël on 24/02/2020.
//
// Copyright 2020 Readium Foundation. All rights reserved.
// Use of this source code is governed by a BSD-style license which is detailed
// in the LICENSE file present in the project repository where this source code is maintained.
//
import Foundation
import R2Shared
extension Presentation.Orientation {
/// Creates from an EPUB rendition:orientation property.
public init(epub: String, fallback: Presentation.Orientation? = nil) {
switch epub {
case "landscape":
self = .landscape
case "portrait":
self = .portrait
case "auto":
self = .auto
default:
self = fallback ?? .auto
}
}
}
extension Presentation.Overflow {
/// Creates from an EPUB rendition:flow property.
public init(epub: String, fallback: Presentation.Overflow? = nil) {
switch epub {
case "auto":
self = .auto
case "paginated":
self = .paginated
case "scrolled-doc", "scrolled-continuous":
self = .scrolled
default:
self = fallback ?? .auto
}
}
}
extension Presentation.Spread {
/// Creates from an EPUB rendition:spread property.
public init(epub: String, fallback: Presentation.Spread? = nil) {
switch epub {
case "none":
self = .none
case "auto":
self = .auto
case "landscape":
self = .landscape
// `portrait` is deprecated and should fallback to `both`.
// See. https://readium.org/architecture/streamer/parser/metadata#epub-3x-11
case "both", "portrait":
self = .both
default:
self = fallback ?? .auto
}
}
}
extension EPUBLayout {
/// Creates from an EPUB rendition:layout property.
public init(epub: String, fallback: EPUBLayout? = nil) {
switch epub {
case "reflowable":
self = .reflowable
case "pre-paginated":
self = .fixed
default:
self = fallback ?? .reflowable
}
}
}
| bsd-3-clause |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/25747-swift-genericsignature-get.swift | 13 | 236 | // 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 f=[[{class
case,
| apache-2.0 |
olaf-olaf/finalProject | drumPad/DistortionParameterViewController.swift | 1 | 2083 | //
// distortionParametersViewController.swift
// drumPad
//
// Created by Olaf Kroon on 25/01/17.
// Student number: 10787321
// Course: Programmeerproject
//
// DistortionParametersViewController consists of rotary knobs that are used to determine the parameters
// of the reverb object in AudioContoller.
//
// Copyright © 2017 Olaf Kroon. All rights reserved.
//
import UIKit
class distortionParametersViewController: UIViewController {
// MARK: - Variables.
let enabledColor = UIColor(red: (246/255.0), green: (124/255.0), blue: (113/255.0), alpha: 1.0)
var decimationKnob: Knob!
var roundingKnob: Knob!
// MARK: - Outlets.
@IBOutlet weak var setDistortion: UIButton!
@IBOutlet weak var roundingKnobPlaceholder: UIView!
@IBOutlet weak var decimationKnobPlaceholder: UIView!
// MARK: - UIViewController lifecycle.
override func viewDidLoad() {
super.viewDidLoad()
setDistortion.layer.cornerRadius = 5
decimationKnob = Knob(frame: decimationKnobPlaceholder.bounds)
decimationKnobPlaceholder.addSubview(decimationKnob)
decimationKnob.setKnobDisplay(largeButton: true, minimum: 0, maximum: 1)
decimationKnob.value = Float(AudioController.sharedInstance.distortion.decimation)
roundingKnob = Knob(frame: roundingKnobPlaceholder.bounds)
roundingKnobPlaceholder.addSubview(roundingKnob)
roundingKnob.setKnobDisplay(largeButton: true, minimum: 0, maximum: 1)
roundingKnob.value = Float(AudioController.sharedInstance.distortion.rounding)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Actions.
@IBAction func setDistortionParameters(_ sender: UIButton) {
setDistortion.backgroundColor = enabledColor
let decimation = Double(decimationKnob.value)
let rounding = Double(roundingKnob.value)
AudioController.sharedInstance.setDistortionParameters(distortionDecimation: decimation, distortionRouding: rounding)
}
}
| mit |
Sufi-Al-Hussaini/Swift-CircleMenu | CircleMenuDemo/CircleMenuDemo/DefaultRotatingViewController.swift | 1 | 1668 | //
// DefaultRotatingViewController.swift
// CircleMenuDemo
//
// Created by Shoaib Ahmed on 11/25/16.
// Copyright © 2016 Shoaib Ahmed / Sufi-Al-Hussaini. All rights reserved.
//
import UIKit
class DefaultRotatingViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
prepareView()
prepareDefaultCircleMenu()
}
func prepareView() {
view.backgroundColor = UIColor.lightGray
}
func prepareDefaultCircleMenu() {
// Create circle
let circle = Circle(with: CGRect(x: 10, y: 90, width: 300, height: 300), numberOfSegments: 10, ringWidth: 80.0)
// Set dataSource and delegate
circle.dataSource = self
circle.delegate = self
// Position and customize
circle.center = view.center
// Create overlay with circle
let overlay = CircleOverlayView(with: circle)
// Add to view
self.view.addSubview(circle)
self.view.addSubview(overlay!)
}
}
extension DefaultRotatingViewController: CircleDelegate, CircleDataSource {
func circle(_ circle: Circle, didMoveTo segment: Int, thumb: CircleThumb) {
let alert = UIAlertController(title: "Selected", message: "Item with tag: \(segment)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func circle(_ circle: Circle, iconForThumbAt row: Int) -> UIImage {
return UIImage(named: "icon_arrow_up")!
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/0165-swift-typebase-getdesugaredtype.swift | 13 | 331 | // 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
1, g(f, j)))
m k {
class h k()
}
struct i {
i d: k.l h k() {
n k
}
class g {
typealias k = k
}
| apache-2.0 |
noppoMan/aws-sdk-swift | scripts/create-modules.swift | 1 | 4753 | #!/usr/bin/env swift sh
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import ArgumentParser // apple/swift-argument-parser ~> 0.0.1
import Files // JohnSundell/Files
import Stencil // soto-project/Stencil
class GenerateProcess {
let parameters: GenerateProjects
let environment: Environment
let fsLoader: FileSystemLoader
var targetFolder: Folder!
var servicesFolder: Folder!
var extensionsFolder: Folder!
var zlibSourceFolder: Folder!
init(_ parameters: GenerateProjects) {
self.parameters = parameters
self.fsLoader = FileSystemLoader(paths: ["./scripts/templates/create-modules"])
self.environment = Environment(loader: self.fsLoader)
}
func createProject(_ serviceName: String) throws {
let serviceSourceFolder = try servicesFolder.subfolder(at: serviceName)
let extensionSourceFolder = try? self.extensionsFolder.subfolder(at: serviceName)
let includeZlib = (serviceName == "S3")
// create folders
let serviceTargetFolder = try targetFolder.createSubfolder(at: serviceName)
let workflowsTargetFolder = try serviceTargetFolder.createSubfolder(at: ".github/workflows")
let sourceTargetFolder = try serviceTargetFolder.createSubfolder(at: "Sources")
// delete folder if it already exists
if let folder = try? sourceTargetFolder.subfolder(at: serviceName) {
try folder.delete()
}
// copy source files across
try serviceSourceFolder.copy(to: sourceTargetFolder)
// if there is an extensions folder copy files across to target source folder
if let extensionSourceFolder = extensionSourceFolder {
let serviceSourceTargetFolder = try sourceTargetFolder.subfolder(at: serviceName)
try extensionSourceFolder.files.forEach { try $0.copy(to: serviceSourceTargetFolder) }
}
// if zlib is required copy CAWSZlib folder
if includeZlib {
try self.zlibSourceFolder.copy(to: sourceTargetFolder)
}
// Package.swift
let context = [
"name": serviceName,
"version": parameters.version,
]
let packageTemplate = includeZlib ? "Package_with_Zlib.stencil" : "Package.stencil"
let package = try environment.renderTemplate(name: packageTemplate, context: context)
let packageFile = try serviceTargetFolder.createFile(named: "Package.swift")
try packageFile.write(package)
// readme
let readme = try environment.renderTemplate(name: "README.md", context: context)
let readmeFile = try serviceTargetFolder.createFile(named: "README.md")
try readmeFile.write(readme)
// copy license
let templatesFolder = try Folder(path: "./scripts/templates/create-modules")
let licenseFile = try templatesFolder.file(named: "LICENSE")
try licenseFile.copy(to: serviceTargetFolder)
// gitIgnore
let gitIgnore = try templatesFolder.file(named: ".gitignore")
try gitIgnore.copy(to: serviceTargetFolder)
// copy ci.yml
let ciYml = try templatesFolder.file(named: "ci.yml")
try ciYml.copy(to: workflowsTargetFolder)
}
func run() throws {
self.servicesFolder = try Folder(path: "./Sources/Soto/Services")
self.extensionsFolder = try Folder(path: "./Sources/Soto/Extensions")
self.zlibSourceFolder = try Folder(path: "./Sources/CAWSZlib")
self.targetFolder = try Folder(path: ".").createSubfolder(at: self.parameters.targetPath)
// try Folder(path: "targetFolder").
try self.parameters.services.forEach { service in
try createProject(service)
}
}
}
struct GenerateProjects: ParsableCommand {
@Argument(help: "The folder to create projects inside.")
var targetPath: String
@Option(name: .shortAndLong, help: "SotoCore version to use.")
var version: String
let services = [
/* "APIGateway",
"CloudFront",
"CloudWatch",
"DynamoDB",
"EC2",
"ECR",
"ECS",
"IAM",
"Kinesis",
"Lambda",*/
"S3",
"SES",
]
func run() throws {
try GenerateProcess(self).run()
}
}
GenerateProjects.main()
| apache-2.0 |
boland25/ResearchKit | samples/ORKSample/ORKSample/AppDelegate.swift | 5 | 4440 | /*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import ResearchKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let healthStore = HKHealthStore()
var window: UIWindow?
var containerViewController: ResearchContainerViewController? {
return window?.rootViewController as? ResearchContainerViewController
}
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let standardDefaults = NSUserDefaults.standardUserDefaults()
if standardDefaults.objectForKey("ORKSampleFirstRun") == nil {
ORKPasscodeViewController.removePasscodeFromKeychain()
standardDefaults.setValue("ORKSampleFirstRun", forKey: "ORKSampleFirstRun")
}
// Appearance customization
let pageControlAppearance = UIPageControl.appearance()
pageControlAppearance.pageIndicatorTintColor = UIColor.lightGrayColor()
pageControlAppearance.currentPageIndicatorTintColor = UIColor.blackColor()
// Dependency injection.
containerViewController?.injectHealthStore(healthStore)
return true
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
lockApp()
return true
}
func applicationDidEnterBackground(application: UIApplication) {
if ORKPasscodeViewController.isPasscodeStoredInKeychain() {
// Hide content so it doesn't appear in the app switcher.
containerViewController?.contentHidden = true
}
}
func applicationWillEnterForeground(application: UIApplication) {
lockApp()
}
func lockApp() {
/*
Only lock the app if there is a stored passcode and a passcode
controller isn't already being shown.
*/
guard ORKPasscodeViewController.isPasscodeStoredInKeychain() && !(containerViewController?.presentedViewController is ORKPasscodeViewController) else { return }
window?.makeKeyAndVisible()
let passcodeViewController = ORKPasscodeViewController.passcodeAuthenticationViewControllerWithText("Welcome back to ResearchKit Sample App", delegate: self) as! ORKPasscodeViewController
containerViewController?.presentViewController(passcodeViewController, animated: false, completion: nil)
}
}
extension AppDelegate: ORKPasscodeDelegate {
func passcodeViewControllerDidFinishWithSuccess(viewController: UIViewController) {
containerViewController?.contentHidden = false
viewController.dismissViewControllerAnimated(true, completion: nil)
}
func passcodeViewControllerDidFailAuthentication(viewController: UIViewController) {
}
}
| bsd-3-clause |
qq456cvb/DeepLearningKitForiOS | iOSDeepLearningKitApp/iOSDeepLearningKitApp/iOSDeepLearningKitApp/BsonUtil.swift | 1 | 4457 | //
// BsonUtil.swift
// iOSDeepLearningKitApp
//
// Created by Neil on 15/11/2016.
// Copyright © 2016 DeepLearningKit. All rights reserved.
//
import Foundation
func readArr(stream: inout InputStream) -> Any {
let intBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: 4)
let byteBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
stream.read(byteBuf, maxLength: 1)
stream.read(intBuf, maxLength: 4)
let byte = byteBuf[0]
let cnt = Int(intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0])
if byte == 0 { // value
let arrBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: cnt * 4)
stream.read(arrBuf, maxLength: cnt * 4)
let floatArrBuf = arrBuf.deinitialize().assumingMemoryBound(to: Float.self)
var arr = Array(repeating: 0.0, count: cnt) as! [Float]
for i in 0...(cnt-1) {
arr[i] = floatArrBuf[i]
}
arrBuf.deinitialize().deallocate(bytes: cnt * 4, alignedTo: 1)
intBuf.deallocate(capacity: 4)
byteBuf.deallocate(capacity: 1)
return arr
} else if byte == 1 { // dictionary
var arr = [Any].init()
for _ in 0...(cnt-1) {
arr.append(readDic(stream: &stream))
}
intBuf.deallocate(capacity: 4)
byteBuf.deallocate(capacity: 1)
return arr
} else if byte == 3 { // string
var arr = [String].init()
for _ in 0...(cnt-1) {
stream.read(intBuf, maxLength: 4)
let strLen = Int(intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0])
// read string
let strBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: strLen)
stream.read(strBuf, maxLength: strLen)
let data = Data(bytes: strBuf, count: strLen)
let valStr = String(data: data, encoding: String.Encoding.ascii)
arr.append(valStr!)
strBuf.deallocate(capacity: strLen)
}
intBuf.deallocate(capacity: 4)
byteBuf.deallocate(capacity: 1)
return arr
} else { // never get here
assert(false)
}
assert(false)
return [Any].init()
}
func readDic(stream: inout InputStream) -> Dictionary<String, Any> {
var dic = Dictionary<String, Any>.init()
let intBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: 4)
let byteBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
stream.read(intBuf, maxLength: 4)
let num = intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0]
for _ in 0...(num-1) {
stream.read(intBuf, maxLength: 4)
let strLen = Int(intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0])
let strBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: strLen)
stream.read(strBuf, maxLength: strLen)
var data = Data(bytes: strBuf, count: strLen)
let str = String(data: data, encoding: String.Encoding.ascii)
stream.read(byteBuf, maxLength: 1)
let byte = byteBuf[0]
if byte == 0 { // value
stream.read(intBuf, maxLength: 4)
let f = intBuf.deinitialize().assumingMemoryBound(to: Float.self)[0]
dic[str!] = f
} else if byte == 1 { // dictionary
dic[str!] = readDic(stream: &stream)
} else if byte == 2 { // array
dic[str!] = readArr(stream: &stream)
} else if byte == 3 { // string
// read string length
stream.read(intBuf, maxLength: 4)
let innerStrLen = Int(intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0])
// read string
let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: innerStrLen)
stream.read(buf, maxLength: innerStrLen)
data = Data(bytes: buf, count: innerStrLen)
let valStr = String(data: data, encoding: String.Encoding.ascii)
dic[str!] = valStr
buf.deallocate(capacity: innerStrLen)
} else {
assert(false) // cannot get in
}
strBuf.deallocate(capacity: strLen)
}
intBuf.deallocate(capacity: 4)
byteBuf.deallocate(capacity: 1)
return dic
}
func readBson(file: String) -> Dictionary<String, Any> {
var stream = InputStream(fileAtPath: file)
stream?.open()
let dic = readDic(stream: &stream!)
stream?.close()
return dic
}
| apache-2.0 |
Vluxe/AnimationSeries | login/login/EndController.swift | 2 | 820 | //
// EndController.swift
// login
//
// Created by Dalton Cherry on 3/27/15.
// Copyright (c) 2015 Vluxe. All rights reserved.
//
import UIKit
class EndController: UIViewController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
let h: CGFloat = 30
let label = UILabel(frame: CGRectMake(0, (self.view.frame.size.height-h)/2, self.view.frame.size.width, h))
label.text = NSLocalizedString("Hello World!", comment: "")
self.view.addSubview(label)
}
}
| apache-2.0 |
svachmic/ios-url-remote | URLRemote/Classes/Model/Entry.swift | 1 | 2960 | //
// Entry.swift
// URLRemote
//
// Created by Michal Švácha on 13/12/16.
// Copyright © 2016 Svacha, Michal. All rights reserved.
//
import Foundation
import ObjectMapper
/// Enum for all the Entry types.
/// Represented by an integer in order for it to be easily serializable from/to online database.
enum EntryType: Int, EnumCollection {
/// Custom criteria type evaluated against a user-defined criteria.
case custom = 0
/// Simple HTTP type evaluated only by HTTP status code.
case simpleHTTP = 1
/// Quido I/O module type evaluated against specific criteria.
case quido = 2
/// Returns human-readable, localized name of the enum value.
///
/// - Returns: String object with the name of the EntryType.
func toString() -> String {
switch self {
case .custom:
return NSLocalizedString("TYPE_CUSTOM", comment: "")
case .simpleHTTP:
return NSLocalizedString("TYPE_SIMPLE_HTTP", comment: "")
case .quido:
return NSLocalizedString("TYPE_QUIDO", comment: "")
}
}
/// Returns human-readable, localized description of the enum value.
///
/// - Returns: String object with the description of the EntryType.
func description() -> String {
switch self {
case .custom:
return NSLocalizedString("TYPE_CUSTOM_DESC", comment: "")
case .simpleHTTP:
return NSLocalizedString("TYPE_SIMPLE_HTTP_DESC", comment: "")
case .quido:
return NSLocalizedString("TYPE_QUIDO_DESC", comment: "")
}
}
}
/// Model class for an Entry. An entry represents one callable IoT device action.
class Entry: FirebaseObject {
/// User-defined name for the entry.
var name: String?
/// Color of the entry from the application specific range of colors.
var color: ColorName?
/// Name of the icon in the icon set.
var icon: String?
/// URL for the action.
var url: String?
/// Type of the entry.
var type: EntryType?
/// Flag indicating whether the URL also needs HTTP Authentication.
var requiresAuthentication = false
/// Username for HTTP Authentication.
var user: String?
/// Password for HTTP Authentication.
var password: String?
/// User-defined criteria for EntryType Custom.
var customCriteria: String?
override init() {
super.init()
}
// MARK: - ObjectMapper methods
required init?(map: Map) {
super.init(map: map)
}
override func mapping(map: Map) {
super.mapping(map: map)
name <- map["name"]
color <- map["color"]
icon <- map["icon"]
url <- map["url"]
type <- map["type"]
requiresAuthentication <- map["requiresAuthentication"]
user <- map["user"]
password <- map["password"]
customCriteria <- map["customCriteria"]
}
}
| apache-2.0 |
pawan007/SmartZip | SmartZip/Library/Extensions/NSDate/NSDate+Components.swift | 1 | 2087 | //
// NSDate+Components.swift
//
// Created by Anish Kumar on 30/03/16.
// Copyright © 2016 Modi. All rights reserved.
//
import Foundation
public extension NSDate {
// MARK: Getter
/**
Date year
*/
public var year : Int {
get {
return getComponent(.Year)
}
}
/**
Date month
*/
public var month : Int {
get {
return getComponent(.Month)
}
}
/**
Date weekday
*/
public var weekday : Int {
get {
return getComponent(.Weekday)
}
}
/**
Date weekMonth
*/
public var weekMonth : Int {
get {
return getComponent(.WeekOfMonth)
}
}
/**
Date days
*/
public var days : Int {
get {
return getComponent(.Day)
}
}
/**
Date hours
*/
public var hours : Int {
get {
return getComponent(.Hour)
}
}
/**
Date minuts
*/
public var minutes : Int {
get {
return getComponent(.Minute)
}
}
/**
Date seconds
*/
public var seconds : Int {
get {
return getComponent(.Second)
}
}
/**
Returns the value of the NSDate component
- parameter component: NSCalendarUnit
- returns: the value of the component
*/
public func getComponent (component : NSCalendarUnit) -> Int {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(component, fromDate: self)
return components.valueForComponent(component)
}
/**
Returns the value of the NSDate component
- returns: the value of the component
*/
public func components() -> NSDateComponents {
return NSCalendar.currentCalendar().components([.Era, .Year, .Month, .WeekOfYear, .WeekOfMonth, .Weekday, .WeekdayOrdinal, .Day, .Hour, .Minute, .Second], fromDate: self)
}
} | mit |
netguru/inbbbox-ios | Inbbbox/Source Files/Defines.swift | 1 | 1556 | //
// Defines.swift
// Inbbbox
//
// Created by Peter Bruz on 04/01/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import SwiftyUserDefaults
/// Keys related to reminders and notifications.
enum NotificationKey: String {
case ReminderOn = "ReminderOn"
case ReminderDate = "ReminderDate"
case UserNotificationSettingsRegistered = "UserNotificationSettingsRegistered"
case LocalNotificationSettingsProvided = "LocalNotificationSettingsProvided"
}
/// Keys related to streams sources.
enum StreamSourceKey: String {
case streamSourceIsSet = "StreamSourceIsSet"
case followingStreamSourceOn = "FollowingStreamSourceOn"
case newTodayStreamSourceOn = "NewTodayStreamSourceOn"
case popularTodayStreamSourceOn = "PopularTodayStreamSourceOn"
case debutsStreamSourceOn = "DebutsStreamSourceOn"
case mySetStreamSourceOn = "MySetStreamSourceOn"
}
/// Keys related to customization settings.
enum CustomizationKey: String {
case showAuthorOnHomeScreen = "ShowAuthorOnHomeScreen"
case language = "CustomAppLanguage"
case nightMode = "NightModeStatus"
case autoNightMode = "AutoNightMode"
case colorMode = "CurrentColorMode"
case selectedStreamSource = "SelectedStreamSource"
}
extension DefaultsKeys {
static let onboardingPassed = DefaultsKey<Bool>("onboardingPassed")
}
/// Keys for NSNotifications about changing settings.
enum InbbboxNotificationKey: String {
case UserDidChangeStreamSourceSettings
case UserDidChangeNotificationsSettings
}
| gpl-3.0 |
SakuragiYoshimasa/PhotoCallender | PhotoCallender/AppDelegate.swift | 1 | 6115 | //
// AppDelegate.swift
// PhotoCallender
//
// Created by 櫻木善将 on 2015/06/22.
// Copyright © 2015年 YoshimasaSakuragi. 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 "kyoto.PhotoCallender" 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("PhotoCallender", 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
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 |
jessesquires/swift-proposal-analyzer | swift-proposal-analyzer.playground/Pages/SE-0022.xcplaygroundpage/Contents.swift | 1 | 7548 | /*:
# Referencing the Objective-C selector of a method
* Proposal: [SE-0022](0022-objc-selectors.md)
* Author: [Doug Gregor](https://github.com/DougGregor)
* Review Manager: [Joe Groff](https://github.com/jckarter)
* Status: **Implemented (Swift 2.2)**
* Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160125/007797.html)
* Implementation: [apple/swift#1170](https://github.com/apple/swift/pull/1170)
## Introduction
In Swift 2, Objective-C selectors are written as string literals
(e.g., `"insertSubview:aboveSubview:"`) in the type context of a
`Selector`. This proposal seeks to replace this error-prone approach
with `Selector` initialization syntax that refers to a specific method
via its Swift name.
Swift-evolution thread: [here](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160111/006282.html), [Review](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160118/006913.html), [Amendments after acceptance](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160523/018698.html)
## Motivation
The use of string literals for selector names is extremely
error-prone: there is no checking that the string is even a
well-formed selector, much less that it refers to any known method, or
a method of the intended class. Moreover, with the effort to perform
[automatic renaming of Objective-C
APIs](0005-objective-c-name-translation.md),
the link between Swift name and Objective-C selector is
non-obvious. By providing explicit "create a selector" syntax based on
the Swift name of a method, we eliminate the need for developers to
reason about the actual Objective-C selectors being used.
## Proposed solution
Introduce a new expression `#selector` that allows one to build a selector from a reference to a method, e.g.,
```swift
control.sendAction(#selector(MyApplication.doSomething), to: target, forEvent: event)
```
where “doSomething” is a method of MyApplication, which might even have a completely-unrelated name in Objective-C:
```swift
extension MyApplication {
@objc(jumpUpAndDown:)
func doSomething(sender: AnyObject?) { … }
}
```
By naming the Swift method and having the `#selector` expression do
the work to form the Objective-C selector, we free the developer from
having to do the naming translation manually and get static checking
that the method exists and is exposed to Objective-C.
This proposal composes with the [Naming Functions with Argument Labels
proposal](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160111/006262.html), which lets us name methods along with their argument labels, e.g.:
let sel = #selector(UIView.insertSubview(_:atIndex:)) // produces the Selector "insertSubview:atIndex:"
With the introduction of the `#selector` syntax, we should deprecate
the use of string literals to form selectors. Ideally, we could
perform the deprecation in Swift 2.2 and remove the syntax entirely
from Swift 3.
Additionally, we should introduce specific migrator support to
translate string-literals-as-selectors into method references. Doing
this well is non-trivial, requiring the compiler/migrator to find all
of the declarations with a particular Objective-C selector and
determine which one to reference. However, it should be feasible, and
we can migrate other references to a specific, string-based
initialization syntax (e.g., `Selector("insertSubview:atIndex:")`).
## Detailed design
The subexpression of the `#selector` expression must be a reference to an `objc` method. Specifically, the input expression must be a direct reference to an Objective-C method, possibly parenthesized and possibly with an "as" cast (which can be used to disambiguate same-named Swift methods). For example, here is a "highly general" example:
```swift
let sel = #selector(((UIView.insertSubview(_:at:)) as (UIView) -> (UIView, Int) -> Void))
```
The expression inside `#selector` is limited to be a series of instance
or class members separated by `.` where the last component may be
disambiguated using `as`. In particular, this prohibits performing
method calls inside `#selector`, clarifying that the subexpression of
`#selector` will not be evaluated and no side effects occur because of it.
The complete grammar of `#selector` is:
<pre>
selector → #selector(<i>selector-path</i>)
selector-path → <i>type-identifier</i> . <i>selector-member-path</i> <i>as-disambiguation<sub>opt</sub></i>
selector-path → <i>selector-member-path</i> <i>as-disambiguation<sub>opt</sub></i>
selector-member-path → <i>identifier</i>
selector-member-path → <i>unqualified-name</i>
selector-member-path → <i>identifier</i> . <i>selector-member-path</i>
as-disambiguation → as <i>type-identifier</i>
</pre>
## Impact on existing code
The introduction of the `#selector` expression has no
impact on existing code. However, deprecating and removing the
string-literal-as-selector syntax is a source-breaking
change. We can migrate the uses to either the new `#selector`
expression or to explicit initialization of a `Selector`
from a string.
## Alternatives considered
The primary alternative is [type-safe
selectors](https://lists.swift.org/pipermail/swift-evolution/2015-December/000233.html),
which would introduce a new "selector" calling convetion to capture
the type of an `@objc` method, including its selector. One major
benefit of type-safe selectors is that they can carry type
information, improving type safety. From that discussion, referencing
`MyClass.observeNotification` would produce a value of type:
```swift
@convention(selector) (MyClass) -> (NSNotification) -> Void
```
Objective-C APIs that accept selectors could provide type information
(e.g., via Objective-C attributes or new syntax for a typed `SEL`),
improving type safety for selector-based APIs. Personally, I feel that
type-safe selectors are a well-designed feature that isn't worth
doing: one would probably not use them outside of interoperability
with existing Objective-C APIs, because closures are generally
preferable (in both Swift and Objective-C). The cost of adding this
feature to both Swift and Clang is significant, and we would also need
adoption across a significant number of Objective-C APIs to make it
worthwhile. On iOS, we are talking about a relatively small number of
APIs (100-ish), and many of those have blocks/closure-based variants
that are preferred anyway. Therefore, we should implement the simpler
feature in this proposal rather than the far more complicated (but
admittedly more type-safe) alternative approach.
Syntactically, `@selector(method reference)` would match Objective-C
more closely, but it doesn't make sense in Swift where `@` always
refers to attributes.
The original version of this proposal suggested using a magic
`Selector` initializer, e.g.:
```swift
let sel = Selector(((UIView.insertSubview(_:at:)) as (UIView) -> (UIView, Int) -
```
However, concerns over this being magic syntax that looks like
instance construction (but is not actually representable in Swift as
an initializer), along with existing uses of `#` to denote special
expressions (e.g., `#available`), caused the change to the `#selector`
syntax at the completion of the public review.
## Revision history
- 2016-05-20: The proposal was amended post-acceptance to limit the
syntax inside the subexpression of `#selector`, in particular disallowing
methods calls. Originally any valid Swift expression was supported.
----------
[Previous](@previous) | [Next](@next)
*/
| mit |
congnt24/AwesomeMVVM | AwesomeMVVM/Classes/Base/AwesomeToggleViewByHeight.swift | 1 | 939 | //
// AwesomeToggleViewByHeight.swift
// Pods
//
// Created by Cong Nguyen on 8/19/17.
//
//
import UIKit
open class AwesomeToggleViewByHeight: BaseCustomView {
@IBInspectable var isHide: Bool = false
var heightConstraint: NSLayoutConstraint?
var height: CGFloat!
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
heightConstraint = (self.constraints.filter { $0.firstAttribute == .height }.first)
height = heightConstraint?.constant
}
override open func awakeFromNib() {
if isHide {
heightConstraint?.constant = 0
self.alpha = 0
}
}
open func toggleHeight() {
if heightConstraint?.constant == 0 {
heightConstraint?.constant = height
self.alpha = 1
} else {
heightConstraint?.constant = 0
self.alpha = 0
}
}
}
| mit |
yangyu2010/DouYuZhiBo | DouYuZhiBo/DouYuZhiBo/Class/Home/View/RecycleHeaderView.swift | 1 | 3966 | //
// RecycleHeaderView.swift
// DouYuZhiBo
//
// Created by Young on 2017/2/21.
// Copyright © 2017年 YuYang. All rights reserved.
//
import UIKit
fileprivate let kRecycleCellID = "kRecycleCellID"
class RecycleHeaderView: UIView {
// MARK: -xib控件
@IBOutlet weak var recycleCollecView: UICollectionView!
@IBOutlet weak var pageController: UIPageControl!
// MARK: -系统回调函数
override func awakeFromNib() {
super.awakeFromNib()
// 设置该控件不随着父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
recycleCollecView.register(UINib(nibName: "RecycleHeaderCell", bundle: nil), forCellWithReuseIdentifier: kRecycleCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
//设置layout 不能在xib里设置 因为xib里的大小还没固定下来
let layout = recycleCollecView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = recycleCollecView.bounds.size
}
// MARK: -自定义属性
var recycleModelArr : [RecycleModel]? {
didSet {
guard recycleModelArr != nil else { return }
// 1.刷新数据
recycleCollecView.reloadData()
// 2.设置pageController的总个数
pageController.numberOfPages = recycleModelArr!.count
// 3.设置collectionView滚动到中间某个位置
let path = IndexPath(item: recycleModelArr!.count * 50, section: 0)
recycleCollecView.scrollToItem(at: path, at: .left, animated: false)
// 4.添加定时器
addTimer()
}
}
/// 定时器
fileprivate var timer : Timer?
}
// MARK: -数据源
extension RecycleHeaderView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (recycleModelArr?.count ?? 0) * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kRecycleCellID, for: indexPath) as! RecycleHeaderCell
cell.model = recycleModelArr?[indexPath.item % recycleModelArr!.count]
return cell
}
}
// MARK: -代理
extension RecycleHeaderView : UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
let count = Int(offsetX / scrollView.bounds.width)
pageController.currentPage = count % recycleModelArr!.count
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
stopTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addTimer()
}
}
// MARK: -提供个类方法创建view
extension RecycleHeaderView {
class func creatView() -> RecycleHeaderView {
return Bundle.main.loadNibNamed("RecycleHeaderView", owner: nil, options: nil)?.first as! RecycleHeaderView
}
}
// MARK: -处理timer
extension RecycleHeaderView {
fileprivate func addTimer() {
timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode: .commonModes)
}
fileprivate func stopTimer() {
timer?.invalidate()
timer = nil
}
@objc fileprivate func scrollToNext() {
let currentOffsetX = recycleCollecView.contentOffset.x
let offset = currentOffsetX + recycleCollecView.bounds.width
recycleCollecView.setContentOffset(CGPoint(x: offset, y: 0), animated: true)
}
}
| mit |
grizzly/AppShare | AppShareTests/AppShareTests.swift | 1 | 992 | //
// AppShareTests.swift
// AppShareTests
//
// Created by Stefan Mayr on 05.03.17.
// Copyright © 2017 Grizzly New Technologies GmbH. All rights reserved.
//
import XCTest
@testable import AppShare
class AppShareTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
kirayamato1989/KYPhotoBrowser | KYPhotoBrowser/KYPhotoItem.swift | 1 | 1900 | //
// KYPhotoItem.swift
// KYPhotoBrowser
//
// Created by 郭帅 on 2016/11/8.
// Copyright © 2016年 郭帅. All rights reserved.
//
import UIKit
import Kingfisher
/// 照片模型类
public class KYPhotoItem: KYPhotoSource {
public var url: URL?
public var placeholder: UIImage?
public var image: UIImage?
public var des: String?
public init(url: URL?, placeholder: UIImage?, image: UIImage?, des: String?) {
self.image = image
self.url = url
self.placeholder = placeholder
self.des = des
}
public func loadIfNeed(progress: ((KYPhotoSource, Int64, Int64) -> ())?, complete: ((KYPhotoSource, UIImage?, Error?) -> ())?) {
if image == nil, let _ = url {
if url!.isFileURL {
let localImage = UIImage(contentsOfFile: url!.path)
var error: Error?
if localImage == nil {
error = NSError()
}
image = localImage
complete?(self, localImage, error)
}
else {
// 抓取image
KingfisherManager.shared.retrieveImage(with: url!, options: [.preloadAllAnimationData], progressBlock: { [weak self](current, total) in
if let _ = self {
progress?(self!, current, total)
}
}, completionHandler: {[weak self](image, error, cacheType, url) in
if let _ = self {
self!.image = image
complete?(self!, image, error)
}
})
}
}
else {
let error: Error? = image == nil ? NSError() : nil
complete?(self, image, error)
}
}
public func releaseImage() {
self.image = nil
}
}
| mit |
february29/Learning | swift/ARDemo/ARDemo/ViewController.swift | 1 | 8396 | //
// ViewController.swift
// ARDemo
//
// Created by bai on 2019/5/28.
// Copyright © 2019 北京仙指信息技术有限公司. All rights reserved.
//
import UIKit
import ARKit
import SceneKit
class ViewController: UIViewController ,ARSCNViewDelegate,ARSessionDelegate{
//场景
lazy var sceneView: ARSCNView = {
let sceneView = ARSCNView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height));
sceneView.showsStatistics = true;
sceneView.autoenablesDefaultLighting = true
return sceneView;
}()
// 会话
lazy var sesson: ARSession = {
let temp = ARSession();
temp.delegate = self;
return temp;
}()
lazy var scene: SCNScene = {
// 存放所有 3D 几何体的容器
let scene = SCNScene()
return scene;
}()
//小树人
lazy var treeNode: SCNNode = {
let temp = SCNNode();
guard let url = Bundle.main.url(forResource: "linglang", withExtension: "max") else {
fatalError("baby_groot.dae not exit.")
}
guard let customNode = SCNReferenceNode(url: url) else {
fatalError("load baby_groot error.")
}
customNode.load();
temp.addChildNode(customNode)
temp.position = SCNVector3Make(0, 0, -0.5);
return temp;
}()
//红色立方体
lazy var redNode: SCNNode = {
// 想要绘制的 3D 立方体
let boxGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.0)
boxGeometry.firstMaterial?.diffuse.contents = UIColor.red;
// 将几何体包装为 node 以便添加到 scene
let boxNode = SCNNode(geometry: boxGeometry)
boxNode.position = SCNVector3Make(0, 0, -0.5);
return boxNode;
}()
//相机节点 代表第一视角的位置。 空节点
lazy var selfNode: SCNNode = {
let temp = SCNNode()
return temp;
}()
//
lazy var boxNode: SCNNode = {
// 想要绘制的 3D 立方体
let boxGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.0)
// 将几何体包装为 node 以便添加到 scene
let boxNode = SCNNode(geometry: boxGeometry)
return boxNode;
}()
lazy var configuration:ARWorldTrackingConfiguration = {
let temp = ARWorldTrackingConfiguration();
temp.isLightEstimationEnabled = true;
temp.planeDetection = .horizontal;
return temp
}()
override func viewDidLoad() {
super.viewDidLoad()
self.sceneView.session = self.sesson;
self.sceneView.delegate = self;
self.view.addSubview(sceneView);
// rootNode 是一个特殊的 node,它是所有 node 的起始点
self.scene.rootNode.addChildNode(self.redNode)
self.sceneView.scene = self.scene
self.scene.rootNode.addChildNode(self.treeNode)
//ARSCNView 的scene 为 SCNScene ,SCNScene的rootNode 添加子node
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.sceneView.session.run(self.configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
self.sceneView.session.pause()
}
//MARK:ARSCNViewDelegate 继承自 ARSessionObserver
func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
print("添加锚点")
}
func session(_ session: ARSession, didUpdate frame: ARFrame) {
// print("相机移动: (x: \(frame.camera.transform.columns.3.x) y:\(frame.camera.transform.columns.3.y) z:\(frame.camera.transform.columns.3.z))")
// if self.node != nil {
// self.node.position = SCNVector3Make(frame.camera.transform.columns.3.x,frame.camera.transform.columns.3.y,frame.camera.transform.columns.3.z);
// }
selfNode.position = SCNVector3Make(frame.camera.transform.columns.3.x,frame.camera.transform.columns.3.y,frame.camera.transform.columns.3.z);
}
func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) {
print("更新锚点")
}
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
//MARK:ARSCNViewDelegate
////添加节点时候调用(当开启平地捕捉模式之后,如果捕捉到平地,ARKit会自动添加一个平地节点)
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
print("添加节点");
// if anchor.isMember(of: ARPlaneAnchor.self) {
// print("捕捉到平地");
//
//
// let planeAnchor = anchor as! ARPlaneAnchor;
// self.boxNode.position = SCNVector3Make(planeAnchor.center.x, 0, planeAnchor.center.z)
// node.addChildNode(self.boxNode)
// }
//
}
//点击屏幕。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super .touchesBegan(touches, with: event);
self.nodeAroundAnimation();
self.treeRotation();
}
func treeRotation() {
//旋转核心动画
let moonRotationAnimation = CABasicAnimation(keyPath: "rotation");
//旋转周期
moonRotationAnimation.duration = 5;
//围绕Y轴旋转360度
moonRotationAnimation.toValue = NSValue(scnVector4: SCNVector4Make(0, 1, 0, Float(M_PI*2)));
//无限旋转 重复次数为无穷大
moonRotationAnimation.repeatCount = Float.greatestFiniteMagnitude;
//开始旋转 !!!:切记这里是让空节点旋转,而不是台灯节点。 理由同上
treeNode.addAnimation(moonRotationAnimation, forKey: "tree rotation around self");
}
func nodeAroundAnimation() {
//3.绕相机旋转
//绕相机旋转的关键点在于:在相机的位置创建一个空节点,然后将台灯添加到这个空节点,最后让这个空节点自身旋转,就可以实现台灯围绕相机旋转
//1.为什么要在相机的位置创建一个空节点呢?因为你不可能让相机也旋转
//2.为什么不直接让台灯旋转呢? 这样的话只能实现台灯的自转,而不能实现公转
//空节点位置与相机节点位置一致
selfNode.position = self.sceneView.scene.rootNode.position;
//将空节点添加到相机的根节点
self.sceneView.scene.rootNode.addChildNode(selfNode)
// !!!将移动节点作为自己节点的子节点,如果不这样,那么你将看到的是台灯自己在转,而不是围着你转
selfNode.addChildNode(self.redNode)
//旋转核心动画
let moonRotationAnimation = CABasicAnimation(keyPath: "rotation");
//旋转周期
moonRotationAnimation.duration = 5;
//围绕Y轴旋转360度
moonRotationAnimation.toValue = NSValue(scnVector4: SCNVector4Make(0, 1, 0, Float(M_PI*2)));
//无限旋转 重复次数为无穷大
moonRotationAnimation.repeatCount = Float.greatestFiniteMagnitude;
//开始旋转 !!!:切记这里是让空节点旋转,而不是台灯节点。 理由同上
selfNode.addAnimation(moonRotationAnimation, forKey: "moon rotation around earth");
}
}
| mit |
milseman/swift | test/Constraints/array_literal.swift | 5 | 9535 | // RUN: %target-typecheck-verify-swift
struct IntList : ExpressibleByArrayLiteral {
typealias Element = Int
init(arrayLiteral elements: Int...) {}
}
struct DoubleList : ExpressibleByArrayLiteral {
typealias Element = Double
init(arrayLiteral elements: Double...) {}
}
struct IntDict : ExpressibleByArrayLiteral {
typealias Element = (String, Int)
init(arrayLiteral elements: Element...) {}
}
final class DoubleDict : ExpressibleByArrayLiteral {
typealias Element = (String, Double)
init(arrayLiteral elements: Element...) {}
}
final class List<T> : ExpressibleByArrayLiteral {
typealias Element = T
init(arrayLiteral elements: T...) {}
}
final class Dict<K,V> : ExpressibleByArrayLiteral {
typealias Element = (K,V)
init(arrayLiteral elements: (K,V)...) {}
}
infix operator =>
func => <K, V>(k: K, v: V) -> (K,V) { return (k,v) }
func useIntList(_ l: IntList) {}
func useDoubleList(_ l: DoubleList) {}
func useIntDict(_ l: IntDict) {}
func useDoubleDict(_ l: DoubleDict) {}
func useList<T>(_ l: List<T>) {}
func useDict<K,V>(_ d: Dict<K,V>) {}
useIntList([1,2,3])
useIntList([1.0,2,3]) // expected-error{{cannot convert value of type 'Double' to expected element type 'Int'}}
useIntList([nil]) // expected-error {{nil is not compatible with expected element type 'Int'}}
useDoubleList([1.0,2,3])
useDoubleList([1.0,2.0,3.0])
useIntDict(["Niners" => 31, "Ravens" => 34])
useIntDict(["Niners" => 31, "Ravens" => 34.0]) // expected-error{{cannot convert value of type '(String, Double)' to expected element type '(String, Int)'}}
// <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands
useDoubleDict(["Niners" => 31, "Ravens" => 34.0])
useDoubleDict(["Niners" => 31.0, "Ravens" => 34])
useDoubleDict(["Niners" => 31.0, "Ravens" => 34.0])
// Generic slices
useList([1,2,3])
useList([1.0,2,3])
useList([1.0,2.0,3.0])
useDict(["Niners" => 31, "Ravens" => 34])
useDict(["Niners" => 31, "Ravens" => 34.0])
useDict(["Niners" => 31.0, "Ravens" => 34.0])
// Fall back to [T] if no context is otherwise available.
var a = [1,2,3]
var a2 : [Int] = a
var b = [1,2,3.0]
var b2 : [Double] = b
var arrayOfStreams = [1..<2, 3..<4]
struct MyArray : ExpressibleByArrayLiteral {
typealias Element = Double
init(arrayLiteral elements: Double...) {
}
}
var myArray : MyArray = [2.5, 2.5]
// Inference for tuple elements.
var x1 = [1]
x1[0] = 0
var x2 = [(1, 2)]
x2[0] = (3, 4)
var x3 = [1, 2, 3]
x3[0] = 4
func trailingComma() {
_ = [1, ]
_ = [1, 2, ]
_ = ["a": 1, ]
_ = ["a": 1, "b": 2, ]
}
func longArray() {
var _=["1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]
}
[1,2].map // expected-error {{expression type '((Int) throws -> _) throws -> [_]' is ambiguous without more context}}
// <rdar://problem/25563498> Type checker crash assigning array literal to type conforming to _ArrayProtocol
func rdar25563498<T : ExpressibleByArrayLiteral>(t: T) {
var x: T = [1] // expected-error {{cannot convert value of type '[Int]' to specified type 'T'}}
// expected-warning@-1{{variable 'x' was never used; consider replacing with '_' or removing it}}
}
func rdar25563498_ok<T : ExpressibleByArrayLiteral>(t: T) -> T
where T.ArrayLiteralElement : ExpressibleByIntegerLiteral {
let x: T = [1]
return x
}
class A { }
class B : A { }
class C : A { }
/// Check for defaulting the element type to 'Any' / 'Any?'.
func defaultToAny(i: Int, s: String) {
let a1 = [1, "a", 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
let _: Int = a1 // expected-error{{value of type '[Any]'}}
let a2: Array = [1, "a", 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
let _: Int = a2 // expected-error{{value of type 'Array<Any>'}}
let a3 = [1, "a", nil, 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
let _: Int = a3 // expected-error{{value of type '[Any?]'}}
let a4: Array = [1, "a", nil, 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
let _: Int = a4 // expected-error{{value of type 'Array<Any?>'}}
let a5 = []
// expected-error@-1{{empty collection literal requires an explicit type}}
let _: Int = a5 // expected-error{{value of type '[Any]'}}
let _: [Any] = [1, "a", 3.5]
let _: [Any] = [1, "a", [3.5, 3.7, 3.9]]
let _: [Any] = [1, "a", [3.5, "b", 3]]
let _: [Any?] = [1, "a", nil, 3.5]
let _: [Any?] = [1, "a", nil, [3.5, 3.7, 3.9]]
let _: [Any?] = [1, "a", nil, [3.5, "b", nil]]
let a6 = [B(), C()]
let _: Int = a6 // expected-error{{value of type '[A]'}}
}
func noInferAny(iob: inout B, ioc: inout C) {
var b = B()
var c = C()
let _ = [b, c, iob, ioc] // do not infer [Any] when elements are lvalues or inout
let _: [A] = [b, c, iob, ioc] // do not infer [Any] when elements are lvalues or inout
b = B()
c = C()
}
/// Check handling of 'nil'.
protocol Proto1 {}
protocol Proto2 {}
struct Nilable: ExpressibleByNilLiteral {
init(nilLiteral: ()) {}
}
func joinWithNil<T>(s: String, a: Any, t: T, m: T.Type, p: Proto1 & Proto2, arr: [Int], opt: Int?, iou: Int!, n: Nilable) {
let a1 = [s, nil]
let _: Int = a1 // expected-error{{value of type '[String?]'}}
let a2 = [nil, s]
let _: Int = a2 // expected-error{{value of type '[String?]'}}
let a3 = ["hello", nil]
let _: Int = a3 // expected-error{{value of type '[String?]'}}
let a4 = [nil, "hello"]
let _: Int = a4 // expected-error{{value of type '[String?]'}}
let a5 = [(s, s), nil]
let _: Int = a5 // expected-error{{value of type '[(String, String)?]'}}
let a6 = [nil, (s, s)]
let _: Int = a6 // expected-error{{value of type '[(String, String)?]'}}
let a7 = [("hello", "world"), nil]
let _: Int = a7 // expected-error{{value of type '[(String, String)?]'}}
let a8 = [nil, ("hello", "world")]
let _: Int = a8 // expected-error{{value of type '[(String, String)?]'}}
let a9 = [{ $0 * 2 }, nil]
let _: Int = a9 // expected-error{{value of type '[((Int) -> Int)?]'}}
let a10 = [nil, { $0 * 2 }]
let _: Int = a10 // expected-error{{value of type '[((Int) -> Int)?]'}}
let a11 = [a, nil]
let _: Int = a11 // expected-error{{value of type '[Any?]'}}
let a12 = [nil, a]
let _: Int = a12 // expected-error{{value of type '[Any?]'}}
let a13 = [t, nil]
let _: Int = a13 // expected-error{{value of type '[T?]'}}
let a14 = [nil, t]
let _: Int = a14 // expected-error{{value of type '[T?]'}}
let a15 = [m, nil]
let _: Int = a15 // expected-error{{value of type '[T.Type?]'}}
let a16 = [nil, m]
let _: Int = a16 // expected-error{{value of type '[T.Type?]'}}
let a17 = [p, nil]
let _: Int = a17 // expected-error{{value of type '[(Proto1 & Proto2)?]'}}
let a18 = [nil, p]
let _: Int = a18 // expected-error{{value of type '[(Proto1 & Proto2)?]'}}
let a19 = [arr, nil]
let _: Int = a19 // expected-error{{value of type '[[Int]?]'}}
let a20 = [nil, arr]
let _: Int = a20 // expected-error{{value of type '[[Int]?]'}}
let a21 = [opt, nil]
let _: Int = a21 // expected-error{{value of type '[Int?]'}}
let a22 = [nil, opt]
let _: Int = a22 // expected-error{{value of type '[Int?]'}}
let a23 = [iou, nil]
let _: Int = a23 // expected-error{{value of type '[Int?]'}}
let a24 = [nil, iou]
let _: Int = a24 // expected-error{{value of type '[Int?]'}}
let a25 = [n, nil]
let _: Int = a25 // expected-error{{value of type '[Nilable]'}}
let a26 = [nil, n]
let _: Int = a26 // expected-error{{value of type '[Nilable]'}}
}
struct OptionSetLike : ExpressibleByArrayLiteral {
typealias Element = OptionSetLike
init() { }
init(arrayLiteral elements: OptionSetLike...) { }
static let option: OptionSetLike = OptionSetLike()
}
func testOptionSetLike(b: Bool) {
let _: OptionSetLike = [ b ? [] : OptionSetLike.option, OptionSetLike.option]
let _: OptionSetLike = [ b ? [] : .option, .option]
}
// Join of class metatypes - <rdar://problem/30233451>
class Company<T> {
init(routes: [() -> T]) { }
}
class Person { }
class Employee: Person { }
class Manager: Person { }
let router = Company(
routes: [
{ () -> Employee.Type in
_ = ()
return Employee.self
},
{ () -> Manager.Type in
_ = ()
return Manager.self
}
]
)
// Same as above but with existentials
protocol Fruit {}
protocol Tomato : Fruit {}
struct Chicken : Tomato {}
protocol Pear : Fruit {}
struct Beef : Pear {}
let router = Company(
routes: [
// FIXME: implement join() for existentials
// expected-error@+1 {{cannot convert value of type '() -> Tomato.Type' to expected element type '() -> _'}}
{ () -> Tomato.Type in
_ = ()
return Chicken.self
},
{ () -> Pear.Type in
_ = ()
return Beef.self
}
]
)
// Infer [[Int]] for SR3786aa.
// FIXME: As noted in SR-3786, this was the behavior in Swift 3, but
// it seems like the wrong choice and is less by design than by
// accident.
let SR3786a: [Int] = [1, 2, 3]
let SR3786aa = [SR3786a.reversed(), SR3786a]
| apache-2.0 |
evgenyneu/SigmaSwiftStatistics | SigmaSwiftStatisticsTests/RankTests.swift | 1 | 1729 | //
// RanksTest.swift
// SigmaSwiftStatistics
//
// Created by Alan James Salmoni on 21/01/2017.
// Copyright © 2017 Evgenii Neumerzhitckii. All rights reserved.
//
import XCTest
import SigmaSwiftStatistics
class RankTests: XCTestCase {
func testRank() {
let result = Sigma.rank([2, 3, 6, 5, 3])
XCTAssertEqual([1, 2.5, 5, 4, 2.5], result)
}
func testRank_decimals() {
let data = [0.98, 1.11, 1.27, 1.32, 1.44, 1.56, 1.56, 1.76, 2.56, 3.07,
0.37, 0.38, 0.61, 0.78, 0.83, 0.86, 0.9, 0.95, 1.63, 1.97]
let result = Sigma.rank(data)
let expected: [Double] = [9, 10, 11, 12, 13, 14.5, 14.5, 17, 19, 20,
1, 2, 3, 4, 5, 6, 7, 8, 16, 18]
XCTAssertEqual(expected, result)
}
func testRank_singleValue() {
let result = Sigma.rank([50])
XCTAssertEqual([1.0], result)
}
func testRank_empty() {
let result = Sigma.rank([])
XCTAssertEqual([], result)
}
// MARK: ties
func testRank_tiesMean() {
let result = Sigma.rank([100, 100, 100, 100], ties: .average)
XCTAssertEqual([2.5, 2.5, 2.5, 2.5], result)
}
func testRanksTiesMin() {
let result = Sigma.rank([100, 100, 100, 100], ties: .min)
XCTAssertEqual([1, 1, 1, 1], result)
}
func testRanksTiesMax() {
let result = Sigma.rank([100, 100, 100, 100], ties: .max)
XCTAssertEqual([4, 4, 4, 4], result)
}
func testRank_tiesFirst() {
let result = Sigma.rank([100, 100, 100, 100], ties: .first)
XCTAssertEqual([1, 2, 3, 4], result)
}
func testRank_tiesLast() {
let result = Sigma.rank([100, 100, 100, 100], ties: .last)
XCTAssertEqual([4, 3, 2, 1], result)
}
}
| mit |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Parse Dashboard for iOS/Views/ConsoleView.swift | 1 | 3731 | //
// ConsoleView.swift
// Parse Dashboard for iOS
//
// Copyright © 2017 Nathan Tannar.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by Nathan Tannar on 12/20/17.
//
import UIKit
class ConsoleView: UIView {
enum LogKind {
case error, success, info
}
// MARK: - Properties
static var shared = ConsoleView()
private var textView: UITextView = {
let textView = UITextView()
textView.textContainerInset = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 6)
textView.textColor = .white
textView.font = UIFont(name: "Menlo", size: 11.0)!
textView.backgroundColor = .clear
textView.isEditable = false
textView.isSelectable = false
return textView
}()
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Setup View
func setupView() {
backgroundColor = .black
layer.shadowRadius = 3
layer.shadowOffset = CGSize(width: 0, height: -1)
layer.shadowOpacity = 0.3
layer.shadowColor = UIColor.darkGray.cgColor
addSubview(textView)
textView.fillSuperview()
}
// MARK: - Methods
public func scrollToBottom() {
if textView.bounds.height < textView.contentSize.height {
textView.layoutManager.ensureLayout(for: textView.textContainer)
let offset = CGPoint(x: 0, y: (textView.contentSize.height - textView.frame.size.height))
textView.setContentOffset(offset, animated: true)
}
}
func log(message: String, kind: LogKind = .info) {
DispatchQueue.main.async {
let dateString = Date().string(dateStyle: .none, timeStyle: .medium)
let newText = NSMutableAttributedString(attributedString: self.textView.attributedText)
newText.normal("\(dateString) > ", font: UIFont(name: "Menlo", size: 11.0)!, color: .white)
switch kind {
case .info: newText.normal(message + "\n", font: UIFont(name: "Menlo", size: 11.0)!, color: .white)
case .error: newText.normal(message + "\n", font: UIFont(name: "Menlo", size: 11.0)!, color: .red)
case .success: newText.normal(message + "\n", font: UIFont(name: "Menlo", size: 11.0)!, color: .green)
}
self.textView.attributedText = newText
self.scrollToBottom()
}
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/Tool/Sources/ToolKit/DIKit.swift | 1 | 352 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import Foundation
extension DependencyContainer {
// MARK: - ToolKit Module
public static var toolKit = module {
factory { UserDefaults.standard as CacheSuite }
// MARK: - Internal Feature Flag
factory { FileIO() as FileIOAPI }
}
}
| lgpl-3.0 |
ioscreator/ioscreator | SwiftUISecureTextFieldTutorial/SwiftUISecureTextFieldTutorial/ContentView.swift | 1 | 615 | //
// ContentView.swift
// SwiftUISecureTextFieldTutorial
//
// Created by Arthur Knopper on 13/10/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State private var password: String = ""
var body: some View {
Form {
Section(header: Text("Authentication")) {
SecureField("Enter a password", text: $password)
Text("You entered: \(password)")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| mit |
OrRon/NexmiiHack | NexmiiHackTests/NexmiiHackTests.swift | 1 | 966 | //
// NexmiiHackTests.swift
// NexmiiHackTests
//
// Created by Or on 27/10/2016.
// Copyright © 2016 Or. All rights reserved.
//
import XCTest
@testable import NexmiiHack
class NexmiiHackTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
shawnirvin/Terminal-iOS-Swift | Terminal/Models/MainProgram.swift | 1 | 633 | //
// MainProgram.swift
// Terminal
//
// Created by Shawn Irvin on 11/25/15.
// Copyright © 2015 Shawn Irvin. All rights reserved.
//
import Foundation
class MainProgram: Program {
init() {
super.init(name: "System")
loadFunctions()
}
private func loadFunctions() {
self.registerFunction(RunFunction())
self.registerFunction(DefaultsFunction())
self.registerFunction(DeviceFunction())
}
override func help() -> String {
let help = "\trun\t\t[program]" +
"\n\t\tdevice\t[property]"
return help
}
}
| mit |
voyages-sncf-technologies/Collor | Example/Collor/PantoneSample/cell/PantoneColorAdapter.swift | 1 | 1117 | //
// PantoneColorAdapter.swift
// Collor
//
// Created by Guihal Gwenn on 08/08/2017.
// Copyright (c) 2017-present, Voyages-sncf.com. All rights reserved.. All rights reserved.
//
import Foundation
import Collor
struct PantoneColorAdapter: CollectionAdapter {
let hexaColor:Int
let color:UIColor
init(hexaColor:Int) {
self.hexaColor = hexaColor
color = UIColor(rgb: hexaColor)
}
}
// from https://stackoverflow.com/questions/24263007/how-to-use-hex-colour-values-in-swift-ios
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
}
| bsd-3-clause |