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 |
---|---|---|---|---|---|
ashfurrow/eidolon | Kiosk/Help/HelpViewController.swift | 2 | 7825 | import UIKit
import ORStackView
import Artsy_UILabels
import Artsy_UIButtons
import Action
import RxSwift
import RxCocoa
class HelpViewController: UIViewController {
var positionConstraints: [NSLayoutConstraint]?
var dismissTapGestureRecognizer: UITapGestureRecognizer?
fileprivate let stackView = ORTagBasedAutoStackView()
fileprivate var buyersPremiumButton: UIButton!
fileprivate let sideMargin: Float = 90.0
fileprivate let topMargin: Float = 45.0
fileprivate let headerMargin: Float = 25.0
fileprivate let inbetweenMargin: Float = 10.0
var showBuyersPremiumCommand = { () -> CocoaAction in
appDelegate().showBuyersPremiumCommand()
}
var registerToBidCommand = { (enabled: Observable<Bool>) -> CocoaAction in
appDelegate().registerToBidCommand(enabled: enabled)
}
var requestBidderDetailsCommand = { (enabled: Observable<Bool>) -> CocoaAction in
appDelegate().requestBidderDetailsCommand(enabled: enabled)
}
var showPrivacyPolicyCommand = { () -> CocoaAction in
appDelegate().showPrivacyPolicyCommand()
}
var showConditionsOfSaleCommand = { () -> CocoaAction in
appDelegate().showConditionsOfSaleCommand()
}
lazy var hasBuyersPremium: Observable<Bool> = {
return appDelegate()
.appViewController
.sale
.value
.rx.observe(String.self, "buyersPremium")
.map { $0.hasValue }
}()
class var width: Float {
get {
return 415.0
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Configure view
view.backgroundColor = .white
addSubviews()
}
}
private extension HelpViewController {
enum SubviewTag: Int {
case assistanceLabel = 0
case stuckLabel, stuckExplainLabel
case bidLabel, bidExplainLabel
case registerButton
case bidderDetailsLabel, bidderDetailsExplainLabel, bidderDetailsButton
case conditionsOfSaleButton, buyersPremiumButton, privacyPolicyButton
}
func addSubviews() {
// Configure subviews
let assistanceLabel = ARSerifLabel()
assistanceLabel.font = assistanceLabel.font.withSize(35)
assistanceLabel.text = "Assistance"
assistanceLabel.tag = SubviewTag.assistanceLabel.rawValue
let stuckLabel = titleLabel(tag: .stuckLabel, title: "Stuck in the process?")
let stuckExplainLabel = wrappingSerifLabel(tag: .stuckExplainLabel, text: "Find the nearest Artsy representative and they will assist you.")
let bidLabel = titleLabel(tag: .bidLabel, title: "How do I place a bid?")
let bidExplainLabel = wrappingSerifLabel(tag: .bidExplainLabel, text: "Enter the amount you would like to bid. You will confirm this bid in the next step. Enter your mobile number or bidder number and PIN that you received when you registered.")
bidExplainLabel.makeSubstringsBold(["mobile number", "bidder number", "PIN"])
var registerButton = blackButton(tag: .registerButton, title: "Register")
registerButton.rx.action = registerToBidCommand(connectedToInternetOrStubbing())
let bidderDetailsLabel = titleLabel(tag: .bidderDetailsLabel, title: "What Are Bidder Details?")
let bidderDetailsExplainLabel = wrappingSerifLabel(tag: .bidderDetailsExplainLabel, text: "The bidder number is how you can identify yourself to bid and see your place in bid history. The PIN is a four digit number that authenticates your bid.")
bidderDetailsExplainLabel.makeSubstringsBold(["bidder number", "PIN"])
var sendDetailsButton = blackButton(tag: .bidderDetailsButton, title: "Send me my details")
sendDetailsButton.rx.action = requestBidderDetailsCommand(connectedToInternetOrStubbing())
var conditionsButton = serifButton(tag: .conditionsOfSaleButton, title: "Conditions of Sale")
conditionsButton.rx.action = showConditionsOfSaleCommand()
buyersPremiumButton = serifButton(tag: .buyersPremiumButton, title: "Buyers Premium")
buyersPremiumButton.rx.action = showBuyersPremiumCommand()
var privacyButton = serifButton(tag: .privacyPolicyButton, title: "Privacy Policy")
privacyButton.rx.action = showPrivacyPolicyCommand()
// Add subviews
view.addSubview(stackView)
stackView.alignTop("0", leading: "0", bottom: nil, trailing: "0", to: view)
stackView.addSubview(assistanceLabel, withTopMargin: "\(topMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(stuckLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(stuckExplainLabel, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(bidLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(bidExplainLabel, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(registerButton, withTopMargin: "20", sideMargin: "\(sideMargin)")
stackView.addSubview(bidderDetailsLabel, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(bidderDetailsExplainLabel, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(sendDetailsButton, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(conditionsButton, withTopMargin: "\(headerMargin)", sideMargin: "\(sideMargin)")
stackView.addSubview(privacyButton, withTopMargin: "\(inbetweenMargin)", sideMargin: "\(self.sideMargin)")
hasBuyersPremium
.subscribe(onNext: { [weak self] hasBuyersPremium in
if hasBuyersPremium {
self?.stackView.addSubview(self!.buyersPremiumButton, withTopMargin: "\(self!.inbetweenMargin)", sideMargin: "\(self!.sideMargin)")
} else {
self?.stackView.removeSubview(self!.buyersPremiumButton)
}
})
.disposed(by: rx.disposeBag)
}
func blackButton(tag: SubviewTag, title: String) -> ARBlackFlatButton {
let button = ARBlackFlatButton()
button.setTitle(title, for: .normal)
button.tag = tag.rawValue
return button
}
func serifButton(tag: SubviewTag, title: String) -> ARUnderlineButton {
let button = ARUnderlineButton()
button.setTitle(title, for: .normal)
button.setTitleColor(.artsyGrayBold(), for: .normal)
button.titleLabel?.font = UIFont.serifFont(withSize: 18)
button.contentHorizontalAlignment = .left
button.tag = tag.rawValue
return button
}
func wrappingSerifLabel(tag: SubviewTag, text: String) -> UILabel {
let label = ARSerifLabel()
label.font = label.font.withSize(18)
label.lineBreakMode = .byWordWrapping
label.preferredMaxLayoutWidth = CGFloat(HelpViewController.width - sideMargin)
label.tag = tag.rawValue
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4
label.attributedText = NSAttributedString(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle])
return label
}
func titleLabel(tag: SubviewTag, title: String) -> ARSerifLabel {
let label = ARSerifLabel()
label.font = label.font.withSize(24)
label.text = title
label.tag = tag.rawValue
return label
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/FeatureKYC/Sources/FeatureKYCUI/KYCBaseViewController.swift | 1 | 3998 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import FeatureKYCDomain
import Localization
import PlatformKit
import PlatformUIKit
import SafariServices
import ToolKit
class KYCBaseViewController: UIViewController, KYCRouterDelegate, KYCOnboardingNavigationControllerDelegate {
private let webViewService: WebViewServiceAPI = resolve()
var router: KYCRouter!
var pageType: KYCPageType = .welcome
class func make(with coordinator: KYCRouter) -> KYCBaseViewController {
assertionFailure("Should be implemented by subclasses")
return KYCBaseViewController()
}
func apply(model: KYCPageModel) {
Logger.shared.debug("Should be overriden to do something with KYCPageModel.")
}
override func viewDidLoad() {
super.viewDidLoad()
// TICKET: IOS-1236 - Refactor KYCBaseViewController NavigationBarItem Titles
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
setupBarButtonItem()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupBarButtonItem()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
router.delegate = self
router.handle(event: .pageWillAppear(pageType))
}
override func viewWillDisappear(_ animated: Bool) {
router.delegate = nil
super.viewWillDisappear(animated)
}
// MARK: Private Functions
fileprivate func setupBarButtonItem() {
guard let navController = navigationController as? KYCOnboardingNavigationController else { return }
let appearance = UINavigationBarAppearance()
appearance.backgroundColor = .white
navController.navigationBar.standardAppearance = appearance
navController.navigationBar.compactAppearance = appearance
navController.navigationBar.scrollEdgeAppearance = appearance
navController.onboardingDelegate = self
navController.setupBarButtonItem()
}
fileprivate func presentNeedSomeHelpAlert() {
let confirm = AlertAction(style: .confirm(LocalizationConstants.KYC.readNow))
let cancel = AlertAction(style: .default(LocalizationConstants.KYC.contactSupport))
let model = AlertModel(
headline: LocalizationConstants.KYC.needSomeHelp,
body: LocalizationConstants.KYC.helpGuides,
actions: [confirm, cancel]
)
let alert = AlertView.make(with: model) { [weak self] action in
guard let this = self else { return }
switch action.style {
case .confirm:
let url = "https://blockchain.zendesk.com/hc/en-us/categories/360001135512-Identity-Verification"
this.webViewService.openSafari(url: url, from: this)
case .default:
let url = "https://blockchain.zendesk.com/hc/en-us/requests/new?ticket_form_id=360000186571"
this.webViewService.openSafari(url: url, from: this)
case .dismiss:
break
}
}
alert.show()
}
func navControllerCTAType() -> NavigationCTA {
guard let navController = navigationController as? KYCOnboardingNavigationController else { return .none }
return navController.viewControllers.count == 1 ? .dismiss : .help
}
func navControllerRightBarButtonTapped(_ navController: KYCOnboardingNavigationController) {
switch navControllerCTAType() {
case .none:
break
case .dismiss:
onNavControllerRightBarButtonWillDismiss()
router.stop()
case .help:
presentNeedSomeHelpAlert()
case .skip:
onNavControllerRightBarButtonSkip()
}
}
// MARK: - Optionally override
func onNavControllerRightBarButtonWillDismiss() {}
func onNavControllerRightBarButtonSkip() {}
}
| lgpl-3.0 |
joywt/SPFilterPicker | SPFilterPicker/FilterPicker/OnOffSwitch.swift | 1 | 417 | //
// OnOffSwitch.swift
// SPFilterPicker
//
// Created by wang tie on 2017/3/10.
// Copyright © 2017年 360jk. All rights reserved.
//
import Foundation
protocol Togglable {
mutating func toggle()
}
public enum OnOffSwitch:Togglable {
case Off, On
mutating func toggle() {
switch self {
case .Off:
self = .On
case .On:
self = .Off
}
}
}
| gpl-3.0 |
jsw0528/ios-learning | ios-learning/AppDelegate.swift | 1 | 2290 | import UIKit
import HexColors
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let rootViewController = UINavigationController(rootViewController: TabBarController())
// 隐藏 Root Navigation Bar,方便自定义子 Controller 的 Navigation Bar
rootViewController.navigationBarHidden = true
window!.rootViewController = rootViewController
window!.backgroundColor = UIColor(hex: "#fff")
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 |
touchvie/sdk-front-ios | SDKFrontiOS/SDKFrontiOS/Biography.swift | 1 | 484 | //
// Biography.swift
// SDKFrontiOS
//
// Created by Carlos Bailon Perez on 17/10/16.
// Copyright © 2016 Tagsonomy. All rights reserved.
//
import UIKit
class Biography: TextModule {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 |
yangfeiyu/iOSDesignPatterns | iOSDesignPatterns/外观模式/Facade.swift | 1 | 697 | //
// Facade.swift
// iOSDesignPatterns
//
// Created by 杨飞宇 on 2017/1/11.
// Copyright © 2017年 FY. All rights reserved.
//
import Foundation
class SubSystemA {
public func methodA() {
}
}
class SubSystemB {
public func methodB() {
}
}
class SubSystemC {
public func methodC() {
}
}
// 外观类
class Facade {
private let obj1 = SubSystemA()
private let obj2 = SubSystemB()
private let obj3 = SubSystemC()
public func method() {
obj1.methodA()
obj2.methodB()
obj3.methodC()
}
}
// 使用
class Usex {
func usex() {
let facade = Facade()
facade.method()
}
}
| mit |
thoughtbot/Swish | Sources/Swish/Protocols/Client.swift | 1 | 207 | import Foundation
public protocol Client {
@discardableResult
func perform<T: Request>(_ request: T, completionHandler: @escaping (Result<T.ResponseObject, SwishError>) -> Void) -> URLSessionDataTask
}
| mit |
daisukenagata/BLEView | BLEView/Classes/BLNotification.swift | 1 | 1868 | //
// BLNotification.swift
// Pods
//
// Created by 永田大祐 on 2017/02/12.
//
//
import UIKit
import CoreLocation
extension BLBeacon {
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion)
{
if(beacons.count > 0){
for i in 0 ..< beacons.count {
let beacon = beacons[i]
let rssi = beacon.rssi;
var proximity = ""
switch (beacon.proximity) {
case CLProximity.unknown :
print("Proximity: Unknown");
proximity = "Unknown"
break
case CLProximity.far:
print("Proximity: Far");
proximity = "Far"
break
case CLProximity.near:
print("Proximity: Near");
proximity = "Near"
break
case CLProximity.immediate:
print("Proximity: Immediate");
proximity = "Immediate"
break
@unknown default: break
}
BlModel.sharedBLEBeacon.blLocationManager = blLocationManager
BlModel.sharedBLEBeacon.statusStr = (rssi * -1 ).description
BlModel.sharedBLEBeacon.proximity = proximity
if BlModel.sharedBLEBeacon.statusStr != ""{
BlModel.sharedBLETableView.update()
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "beaconReceive"), object: self )
}
}
}
}
| mit |
mirego/taylor-ios | TaylorTests/Types/StringTexts.swift | 1 | 4008 | // Copyright (c) 2016, Mirego
// 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 the Mirego 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 XCTest
import Taylor
class StringTests: XCTestCase {
func testRegExp()
{
let emailRegExp = "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,63}$"
XCTAssertTrue("genius@mirego.com".matches(emailRegExp))
XCTAssertFalse("genius@mirego".matches(emailRegExp))
XCTAssertFalse("genius@mirego".matches(""))
XCTAssertFalse("".matches(""))
XCTAssertFalse("".matches(emailRegExp))
// Case sensitive
XCTAssertTrue("genius".matches("GENIUS", caseSensitive: false) )
XCTAssertFalse("genius".matches("GENIUS", caseSensitive: true))
}
func testIsEmailAddress()
{
// General
XCTAssertTrue("genius@mirego.com".isEmailAddress())
XCTAssertTrue("GENIUS@MIREGO.COM".isEmailAddress())
XCTAssertTrue("genius@mirego.newtldwithlongname".isEmailAddress())
XCTAssertFalse("genius_!mirego1q2312@mirego".isEmailAddress())
XCTAssertFalse("@mirego".isEmailAddress())
// Missing parts
XCTAssertFalse("@mirego.com".isEmailAddress())
XCTAssertFalse("genius.mirego.com".isEmailAddress())
XCTAssertFalse("genius@mirego".isEmailAddress())
XCTAssertFalse("genius@.com".isEmailAddress())
// With Spaces
XCTAssertTrue("genius mirego@mirego.com".isEmailAddress())
XCTAssertFalse("genius mirego@mirego domain.com".isEmailAddress())
}
func testTrim() {
let trimmedString = "This is a string"
let stringWithSpaces = "\t \(trimmedString) \t "
var string = String(stringWithSpaces)
XCTAssertEqual(string.trimmed, trimmedString)
// Should not mutate the string
XCTAssertEqual(string, stringWithSpaces)
// Should mutate the string
string.trim()
XCTAssertEqual(string, trimmedString)
// Test empty string
XCTAssertEqual("".trimmed, "")
}
func testCapitalizeFirstLetter() {
let capitalizedString = "Capitalize first letter only"
var string = "capitalize first letter only"
XCTAssertEqual(string.capitalizedFirstLetter, capitalizedString)
// Should not mutate the string
XCTAssertEqual(string, "capitalize first letter only")
// Should mutate the string
string.capitalizeFirstLetter()
XCTAssertEqual(string, capitalizedString)
// Test empty string
XCTAssertEqual("".capitalizedFirstLetter, "")
}
}
| bsd-3-clause |
silence0201/Swift-Study | SwiftLearn/MySwift13_subscripts_operator_overloading.playground/Contents.swift | 1 | 6654 | //: Playground - noun: a place where people can play
import UIKit
/**
Swift_subscripts_operator_overloading
*/
var arr = [0,1,2,3]
arr[1]
var dict = ["北京":"Beijing", "纽约":"New York", "巴黎":"Paris"]
dict["北京"]
struct Vector3{
var x:Double = 0.0
var y:Double = 0.0
var z:Double = 0.0
subscript(index:Int) -> Double?{
get{
switch index{
case 0: return x
case 1: return y
case 2: return z
default: return nil
}
}
/// 默认新值是newValue, 其类型与get的返回类型相同
set{
guard let newValue = newValue else{ return }
switch index{
case 0: x = newValue
case 1: y = newValue
case 2: z = newValue
default: return
}
}
}
subscript(axis:String) -> Double?{
get{
switch axis{
case "x","X": return x
case "y","Y": return y
case "z","Z": return z
default: return nil
}
}
set{
guard let newValue = newValue else{ return }
switch axis{
case "x","X": x = newValue
case "y","Y": y = newValue
case "z","Z": z = newValue
default: return
}
}
}
//返回向量的模
func lenght() -> Double{
return sqrt(x * x + y * y + z * z)
}
}
var v = Vector3(x: 1.0, y: 2.0, z: 3.0)
v.x
let xxx = v[0] //xxx is Double?
let aaa = v[100] //aaa is nil
v["z"]
v["Y"]
v["Hello"]
v[0] = 100.0
v["Y"] = 30
v
///Swift支持有任意多个参数的下标.
struct Matrix{
var data:[[Double]]
let r:Int
let c:Int
init(row:Int, col:Int){
self.r = row
self.c = col
data = [[Double]]()
for _ in 0..<r{
let aRow = Array(repeating: 0.0, count: col)
data.append(aRow)
}
}
//m[1,1]
subscript(x: Int, y: Int) -> Double{
get{
assert( x >= 0 && x < r && y >= 0 && y < c , "Index Out of Range")
return data[x][y]
}
set{ //内置函数 assert
assert( x >= 0 && x < r && y >= 0 && y < c , "Index Out of Range")
data[x][y] = newValue
}
}
// 如果想使用 m[1][1]
subscript(row: Int) -> [Double]{
get{
assert( row >= 0 && row < r , "Index Out of Range")
return data[row]
}
set(vector){ //newValue应该是get的返回值类型
assert( vector.count == c , "Column Number does NOT match")
data[row] = vector
}
}
}
var m = Matrix(row: 2, col: 2)
//m[2,2] //EXC_BAD_INSTRUCTION
m[1,1]
// 如果想使用 m[1][1]
m[1][1]
m[1]
m[0] = [1.5,4.5]
m[0][0]
m[0][1]
// 更多关于assert,留在错误处理进行讲解
// 对于下标的使用
// 实现魔方
// 实现数据结构,如链表
// 实现数据Table,等等等等
//运算符重载, 运算符本质就是函数. *** = 等号是不能被重载的, 是由系统所保留的, 因为它在低层是内存管理相关的.
//重载的运算符函数要定义在结构外面.
func + (left: Vector3, right: Vector3) -> Vector3{
return Vector3(x: left.x + right.x, y: left.y + right.y, z: left.z + right.z)
}
var va = Vector3(x: 1.0, y: 2.0, z: 3.0)
let vb = Vector3(x: 3.0, y: 4.0, z: 5.0)
va + vb
func - (left: Vector3, right: Vector3) -> Vector3{
return Vector3(x: left.x - right.x, y: left.y - right.y, z: left.z - right.z)
}
va - vb
//内积
func * (left: Vector3, right: Vector3) -> Double{
return left.x * right.x + left.y * right.y + left.z * right.z
}
va * vb
func * (left: Vector3, a: Double) -> Vector3{
return Vector3(x: left.x * a, y: left.y * a, z: left.z * a)
}
va * -1.0
func * (a: Double, right: Vector3) -> Vector3{
return right * a
}
-1.0 * va
//left必须inout, 返回值就不需要了.
func +=( left: inout Vector3, right: Vector3){
left = left + right
}
va += vb
//-号加了prefix, 只能用在前面.
prefix func - (vector: Vector3) -> Vector3{
return Vector3(x: -vector.x, y: -vector.y, z: -vector.z)
}
-va
//比较运算符的重载
func == (left: Vector3, right: Vector3) -> Bool{
return left.x == right.x && left.y == right.y && left.z == right.z
}
va == vb
func != (left: Vector3, right: Vector3) -> Bool{
return !(left == right)
}
va != vb
func < (left: Vector3, right: Vector3) -> Bool{
if left.x != right.x{ return left.x < right.x}
if left.y != right.y{ return left.y < right.y}
if left.z != right.z{ return left.z < right.z}
return false
}
va < vb
func <= (left: Vector3, right: Vector3) -> Bool{
return left < right || left == right
}
func > (left: Vector3, right: Vector3) -> Bool{
return !(left <= right)
}
func >= (left: Vector3, right: Vector3) -> Bool{
return !(left < right)
}
let a = [2, 3, 1, 5]
a.sorted(by: >)
//自定义的运算符重载
// Custom operators can begin with one of the ASCII characters
// ASCII characters /, =, -, +, !, *, %, <, >, &, |, ^, ~, or with one of the Unicode characters
//自定义单目运算符
postfix operator +++ //声明+++将会是一个单目运算符
postfix func +++ ( vector: inout Vector3) -> Vector3 {
vector += Vector3(x: 1.0, y: 1.0, z: 1.0)
return vector
}
va+++
//前置的+++操作
prefix operator +++
prefix func +++( vector: inout Vector3) -> Vector3{
let ret = vector
vector += Vector3(x: 1.0, y: 1.0, z: 1.0)
return ret
}
+++va
va
//双目运算符
//associativity 结合性, 左结合
//precedence 优先级[0~255] 默认是140, 140是与加法平行的优先级,
//infix operator ^{associativity left precedence 140} //swift2
infix operator ^: AAA
precedencegroup AAA {
associativity: left
higherThan: AdditionPrecedence
lowerThan: MultiplicationPrecedence
}
func ^ (left: Vector3, right: Vector3) -> Double{
return acos( (left * right) / (left.lenght() * right.lenght()) )
}
va ^ vb
//优先级设置参考Swift官方文档 乘法优先级是150
//infix operator **{associativity right precedence 155} //swift2
infix operator **: BBB
precedencegroup BBB{
associativity: left
higherThan: AdditionPrecedence
lowerThan: MultiplicationPrecedence
}
func **(x: Double, p:Double) -> Double{
return pow(x, p)
}
2**3
2 ** 3 ** 2 //因为associativity结合性是右结合, 所以先计算3**2=9, 再计算2**9=512
1+2 ** 3 ** 2
5*2 ** 3 ** 2
| mit |
segura2010/exodobb-for-iOS | exodobbSiriIntent/IntentHandler.swift | 1 | 9152 | //
// IntentHandler.swift
// exodobbSiriIntent
//
// Created by Alberto on 10/9/16.
// Copyright © 2016 Alberto. All rights reserved.
//
import Intents
// As an example, this class is set up to handle Message intents.
// You will want to replace this or add other intents as appropriate.
// The intents you wish to handle must be declared in the extension's Info.plist.
// You can test your example integration by saying things to Siri like:
// "Send a message using <myApp>"
// "<myApp> John saying hello"
// "Search for messages in <myApp>"
class IntentHandler: INExtension, INSendMessageIntentHandling, INSearchForMessagesIntentHandling, INSetMessageAttributeIntentHandling {
var message = ""
var thread = ""
var threadId = ""
override func handler(for intent: INIntent) -> Any {
// This is the default implementation. If you want different objects to handle different intents,
// you can override this and return the handler you want for that particular intent.
print("COOKIE: \(getCookie())")
return self
}
// MARK: - INSendMessageIntentHandling
// Implement resolution methods to provide additional information about your intent (optional).
func resolveRecipients(forSendMessage intent: INSendMessageIntent, with completion: @escaping ([INPersonResolutionResult]) -> Void) {
if let recipients = intent.recipients {
// If no recipients were provided we'll need to prompt for a value.
if recipients.count == 0 {
completion([INPersonResolutionResult.needsValue()])
return
}
var resolutionResults = [INPersonResolutionResult]()
print(recipients)
for recipient in recipients {
var matchingContacts = [INPerson]() // Implement your contact matching logic here to create an array of matching contacts
// Here we must search the topic
// Search endpoint https://exo.do/api/search/keyword?in=titles
print("\(recipient.spokenPhrase)")
print("IDENTIFIER: \(recipient.contactIdentifier)")
print("DIS: \(recipient.displayName)")
print("REC: \(recipient)")
NodeBBAPI.sharedInstance.searchTopicByTitle(recipient.spokenPhrase!, cookie: getCookie()){(error:NSError?, responseObject:[String:AnyObject]?) in
if(error != nil)
{
resolutionResults += [INPersonResolutionResult.unsupported()]
completion(resolutionResults)
return print("error")
}
var person = recipient
//print(responseObject)
if let posts = responseObject?["posts"] as? [[String:AnyObject]]
{
/* We should give the user the option to chose the topic, but now it creates an infinite loop in Siri..
for p in posts
{
let title = p["topic"]?["title"]
let tid = "\(p["topic"]?["tid"])"
//print("\(p["topic"]?["title"])")
var person = INPerson(handle: tid, displayName: title as! String?, contactIdentifier: tid)
matchingContacts.append(person)
}
*/
// So we use the first one
let title = posts[0]["topic"]?["title"]
let tid = "\(posts[0]["topic"]!["tid"]!)" as! String
print("Selected: \(title)")
person = INPerson(handle: tid, displayName: title as! String?, contactIdentifier: tid as! String)
matchingContacts.append(person)
}
switch matchingContacts.count {
case 2 ... Int.max:
// We need Siri's help to ask user to pick one from the matches.
resolutionResults += [INPersonResolutionResult.disambiguation(with: matchingContacts)]
case 1:
// We have exactly one matching contact
resolutionResults += [INPersonResolutionResult.success(with: person)]
case 0:
// We have no contacts matching the description provided
resolutionResults += [INPersonResolutionResult.unsupported()]
default:
break
}
completion(resolutionResults)
}
}
}
}
func resolveContent(forSendMessage intent: INSendMessageIntent, with completion: @escaping (INStringResolutionResult) -> Void) {
if let text = intent.content, !text.isEmpty {
message = text
completion(INStringResolutionResult.success(with: text))
} else {
completion(INStringResolutionResult.needsValue())
}
}
// Once resolution is completed, perform validation on the intent and provide confirmation (optional).
func confirm(sendMessage intent: INSendMessageIntent, completion: @escaping (INSendMessageIntentResponse) -> Void) {
// Verify user is authenticated and your app is ready to send a message.
NodeBBAPI.sharedInstance.initWSEvents()
let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendMessageIntent.self))
let response = INSendMessageIntentResponse(code: .ready, userActivity: userActivity)
completion(response)
}
// Handle the completed intent (required).
func handle(sendMessage intent: INSendMessageIntent, completion: @escaping (INSendMessageIntentResponse) -> Void) {
// Implement your application logic to send a message here.
message = intent.content!
let tid = intent.recipients![0].contactIdentifier!
//let tid = intent.recipients?[0].contactIdentifier
print("SENDING: \(message) to TID: \(tid)")
NodeBBAPI.sharedInstance.sendPost(message, tid:String(tid)!)
let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendMessageIntent.self))
let response = INSendMessageIntentResponse(code: .success, userActivity: userActivity)
completion(response)
}
// Implement handlers for each intent you wish to handle. As an example for messages, you may wish to also handle searchForMessages and setMessageAttributes.
// MARK: - INSearchForMessagesIntentHandling
func handle(searchForMessages intent: INSearchForMessagesIntent, completion: @escaping (INSearchForMessagesIntentResponse) -> Void) {
// Implement your application logic to find a message that matches the information in the intent.
let userActivity = NSUserActivity(activityType: NSStringFromClass(INSearchForMessagesIntent.self))
let response = INSearchForMessagesIntentResponse(code: .success, userActivity: userActivity)
// Initialize with found message's attributes
response.messages = [INMessage(
identifier: "identifier",
content: "I am so excited about SiriKit!",
dateSent: Date(),
sender: INPerson(personHandle: INPersonHandle(value: "sarah@example.com", type: .emailAddress), nameComponents: nil, displayName: "Sarah", image: nil, contactIdentifier: nil, customIdentifier: nil),
recipients: [INPerson(personHandle: INPersonHandle(value: "+1-415-555-5555", type: .phoneNumber), nameComponents: nil, displayName: "John", image: nil, contactIdentifier: nil, customIdentifier: nil)]
)]
completion(response)
}
// MARK: - INSetMessageAttributeIntentHandling
func handle(setMessageAttribute intent: INSetMessageAttributeIntent, completion: @escaping (INSetMessageAttributeIntentResponse) -> Void) {
// Implement your application logic to set the message attribute here.
let userActivity = NSUserActivity(activityType: NSStringFromClass(INSetMessageAttributeIntent.self))
let response = INSetMessageAttributeIntentResponse(code: .success, userActivity: userActivity)
completion(response)
}
func getCookie() -> String
{
let defaults = UserDefaults(suiteName: "group.exodobb")
if let cookie = defaults?.string(forKey: "cookie") {
print("getCookie() -> \(cookie)")
return cookie
}
else{
return ""
}
}
}
| gpl-2.0 |
eurofurence/ef-app_ios | Eurofurence/SwiftUI/Modules/Schedule/ScheduleCollectionView.swift | 1 | 7461 | import EurofurenceKit
import SwiftUI
struct ScheduleCollectionView: View {
@EnvironmentObject var model: EurofurenceModel
@ObservedObject var schedule: Schedule
@Environment(\.showScheduleFilterButton) private var showScheduleFilter
@State private var isPresentingFilter = false
@State private var selectedEvent: Event?
var body: some View {
ScheduleEventsList(schedule: schedule)
.searchable(text: $schedule.query.animation())
.toolbar {
ToolbarItem(placement: .status) {
statusView
}
ToolbarItem(placement: .bottomBar) {
if showScheduleFilter {
ScheduleFilterButton(isPresentingFilter: $isPresentingFilter, schedule: schedule)
}
}
}
}
@ViewBuilder
private var statusView: some View {
VStack {
Text(
"\(schedule.matchingEventsCount) matching events",
comment: "Format for presenting the number of matching events in a schedule"
)
.font(.caption)
if let localizedFilterDescription = schedule.localizedFilterDescription {
Text(verbatim: localizedFilterDescription)
.font(.caption2)
}
}
}
}
private struct ScheduleFilterButton: View {
@Binding var isPresentingFilter: Bool
var schedule: Schedule
var body: some View {
Button {
isPresentingFilter.toggle()
} label: {
Label {
Text("Filter")
} icon: {
if isPresentingFilter {
Image(systemName: "line.3.horizontal.decrease.circle.fill")
} else {
Image(systemName: "line.3.horizontal.decrease.circle")
}
}
}
.popover(isPresented: $isPresentingFilter) {
NavigationView {
ScheduleFilterView(schedule: schedule)
}
.sensiblePopoverFrame()
.filteringInterfaceDetents()
}
}
}
private struct ScheduleFilterView: View {
@ObservedObject var schedule: Schedule
@Environment(\.dismiss) private var dismiss
var body: some View {
Form {
Toggle(isOn: $schedule.favouritesOnly.animation()) {
Label {
Text("Favourites Only")
} icon: {
FavouriteIcon(filled: true)
}
}
if schedule.availableDays.isEmpty == false {
Section {
ScheduleDayPicker(schedule: schedule)
} header: {
Text("Day")
}
}
if schedule.availableTracks.isEmpty == false {
Section {
ScheduleTrackPicker(schedule: schedule)
} header: {
Text("Track")
}
}
if schedule.availableRooms.isEmpty == false {
Section {
ScheduleRoomPicker(schedule: schedule)
} header: {
Text("Room")
}
}
}
.listStyle(.insetGrouped)
.navigationTitle("Filters")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button {
dismiss()
} label: {
Text("Done")
}
}
}
}
}
private struct ScheduleDayPicker: View {
@ObservedObject var schedule: Schedule
var body: some View {
SelectableRow(tag: nil, selection: $schedule.selectedDay.animation()) {
Label {
Text("Entire Convention")
} icon: {
if schedule.selectedTrack == nil {
Image(systemName: "calendar.circle.fill")
} else {
Image(systemName: "calendar.circle")
}
}
}
ForEach(schedule.availableDays) { day in
SelectableRow(tag: day, selection: $schedule.selectedDay.animation()) {
DayLabel(day: day, isSelected: schedule.selectedDay == day)
}
}
}
}
private struct ScheduleTrackPicker: View {
@ObservedObject var schedule: Schedule
var body: some View {
SelectableRow(tag: nil, selection: $schedule.selectedTrack.animation()) {
Label {
Text("All Tracks")
} icon: {
if schedule.selectedTrack == nil {
Image(systemName: "square.stack.fill")
} else {
Image(systemName: "square.stack")
}
}
}
ForEach(schedule.availableTracks) { track in
SelectableRow(tag: track, selection: $schedule.selectedTrack.animation()) {
TrackLabel(track, isSelected: schedule.selectedTrack == track)
}
}
}
}
private struct ScheduleRoomPicker: View {
@ObservedObject var schedule: Schedule
var body: some View {
SelectableRow(tag: nil, selection: $schedule.selectedRoom.animation()) {
Text("Everywhere")
}
ForEach(schedule.availableRooms) { room in
SelectableRow(tag: room, selection: $schedule.selectedRoom.animation()) {
Text(room.shortName)
}
}
}
}
struct ScheduleCollectionView_Previews: PreviewProvider {
static var previews: some View {
EurofurenceModel.preview { model in
NavigationView {
ScheduleCollectionView(schedule: model.makeSchedule())
.navigationTitle("Preview")
}
.previewDisplayName("Unconfigured Schedule")
NavigationView {
let dayConfiguration = EurofurenceModel.ScheduleConfiguration(day: model.day(for: .conDayTwo))
ScheduleCollectionView(schedule: model.makeSchedule(configuration: dayConfiguration))
.navigationTitle("Preview")
}
.previewDisplayName("Day Specific Schedule")
NavigationView {
let trackConfiguration = EurofurenceModel.ScheduleConfiguration(track: model.track(for: .clubStage))
ScheduleCollectionView(schedule: model.makeSchedule(configuration: trackConfiguration))
.navigationTitle("Preview")
}
.previewDisplayName("Track Specific Schedule")
NavigationView {
let dayAndTrackConfiguration = EurofurenceModel.ScheduleConfiguration(
day: model.day(for: .conDayTwo),
track: model.track(for: .clubStage)
)
let scheduleController = model.makeSchedule(configuration: dayAndTrackConfiguration)
ScheduleCollectionView(schedule: scheduleController)
.navigationTitle("Preview")
}
.previewDisplayName("Day + Track Specific Schedule")
}
}
}
| mit |
danwatco/mega-liker | MegaLiker/SettingsViewController.swift | 1 | 2117 | //
// SettingsViewController.swift
// MegaLiker
//
// Created by Dan Watkinson on 27/11/2015.
// Copyright © 2015 Dan Watkinson. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
var clientID = "[INSTAGRAM_CLIENT_ID]"
var defaults = NSUserDefaults.standardUserDefaults()
@IBOutlet weak var statusLabel: UILabel!
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.
}
override func viewWillAppear(animated: Bool) {
let accessCode = defaults.objectForKey("accessCode")
if(accessCode != nil){
statusLabel.text = "You are now signed in."
}
}
@IBAction func signInBtn(sender: UIButton) {
let userScope = "&scope=likes"
let instagramURL = "https://instagram.com/oauth/authorize/?client_id=" + clientID + "&redirect_uri=megaliker://callback&response_type=token" + userScope
UIApplication.sharedApplication().openURL(NSURL(string: instagramURL)!)
}
@IBAction func signOutBtn(sender: UIButton) {
defaults.removeObjectForKey("accessCode")
statusLabel.textColor = UIColor.redColor()
statusLabel.text = "You are now signed out."
let navController:CustomNavigationController = self.parentViewController as! CustomNavigationController
let viewController:ViewController = navController.viewControllers.first as! ViewController
viewController.userStatus = false
viewController.accessCode = nil
}
/*
// 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 |
taketo1024/SwiftyAlgebra | Sources/SwmCore/Matrix/MatrixImpl.swift | 1 | 10729 | //
// MatrixImpl.swift
// Sample
//
// Created by Taketo Sano on 2019/10/04.
//
public protocol MatrixImpl: Equatable, CustomStringConvertible {
associatedtype BaseRing: Ring
typealias Initializer = (Int, Int, BaseRing) -> Void
init(size: MatrixSize, initializer: (Initializer) -> Void)
init<S: Sequence>(size: MatrixSize, grid: S) where S.Element == BaseRing
init<S: Sequence>(size: MatrixSize, entries: S) where S.Element == MatrixEntry<BaseRing>
static func zero(size: MatrixSize) -> Self
static func identity(size: MatrixSize) -> Self
static func unit(size: MatrixSize, at: (Int, Int)) -> Self
static func scalar(size: MatrixSize, value: BaseRing) -> Self
subscript(i: Int, j: Int) -> BaseRing { get set }
var size: (rows: Int, cols: Int) { get }
var isZero: Bool { get }
var isIdentity: Bool { get }
var isInvertible: Bool { get }
var inverse: Self? { get }
var transposed: Self { get }
var determinant: BaseRing { get }
var trace: BaseRing { get }
func rowVector(_ i: Int) -> Self
func colVector(_ j: Int) -> Self
func submatrix(rowRange: Range<Int>) -> Self
func submatrix(colRange: Range<Int>) -> Self
func submatrix(rowRange: Range<Int>, colRange: Range<Int>) -> Self
func concat(_ B: Self) -> Self
func stack(_ B: Self) -> Self
func permuteRows(by p: Permutation<anySize>) -> Self
func permuteCols(by q: Permutation<anySize>) -> Self
func permute(rowsBy p: Permutation<anySize>, colsBy q: Permutation<anySize>) -> Self
var nonZeroEntries: AnySequence<MatrixEntry<BaseRing>> { get }
func mapNonZeroEntries(_ f: (Int, Int, BaseRing) -> BaseRing) -> Self
func serialize() -> [BaseRing]
static func ==(a: Self, b: Self) -> Bool
static func +(a: Self, b: Self) -> Self
static prefix func -(a: Self) -> Self
static func -(a: Self, b: Self) -> Self
static func *(r: BaseRing, a: Self) -> Self
static func *(a: Self, r: BaseRing) -> Self
static func *(a: Self, b: Self) -> Self
static func ⊕(a: Self, b: Self) -> Self
static func ⊗(a: Self, b: Self) -> Self
}
// MEMO: default implementations are provided,
// but conforming types should override them for performance.
extension MatrixImpl {
public init<S: Sequence>(size: MatrixSize, grid: S) where S.Element == BaseRing {
let m = size.cols
self.init(size: size, entries: grid.enumerated().lazy.compactMap{ (idx, a) in
if !a.isZero {
let (i, j) = (idx / m, idx % m)
return (i, j, a)
} else {
return nil
}
})
}
public init<S: Sequence>(size: MatrixSize, entries: S) where S.Element == MatrixEntry<BaseRing> {
self.init(size: size) { setEntry in
entries.forEach { (i, j, a) in setEntry(i, j, a) }
}
}
public static func zero(size: MatrixSize) -> Self {
.init(size: size) { _ in () }
}
public static func identity(size: MatrixSize) -> Self {
scalar(size: size, value: .identity)
}
public static func unit(size: MatrixSize, at: (Int, Int)) -> Self {
.init(size: size) { setEntry in
setEntry(at.0, at.1, .identity)
}
}
public static func scalar(size: MatrixSize, value: BaseRing) -> Self {
.init(size: size) { setEntry in
let r = min(size.0, size.1)
for i in 0 ..< r {
setEntry(i, i, value)
}
}
}
@inlinable
public subscript(rowRange: Range<Int>, colRange: Range<Int>) -> Self {
self.submatrix(rowRange: rowRange, colRange: colRange)
}
public var isSquare: Bool {
size.rows == size.cols
}
public var isIdentity: Bool {
isSquare && nonZeroEntries.allSatisfy { (i, j, a) in i == j && a.isIdentity }
}
public var isInvertible: Bool {
isSquare && determinant.isInvertible
}
public var inverse: Self? {
if isSquare, let dInv = determinant.inverse {
return .init(size: size) { setEntry in
((0 ..< size.rows) * (0 ..< size.cols)).forEach { (i, j) in
let a = dInv * cofactor(j, i)
setEntry(i, j, a)
}
}
} else {
return nil
}
}
public var transposed: Self {
.init(size: (size.cols, size.rows)) { setEntry in
nonZeroEntries.forEach { (i, j, a) in setEntry(j, i, a) }
}
}
public var trace: BaseRing {
assert(isSquare)
return (0 ..< size.rows).sum { i in
self[i, i]
}
}
public var determinant: BaseRing {
assert(isSquare)
if size.rows == 0 {
return .identity
} else {
return nonZeroEntries
.filter{ (i, j, a) in i == 0 }
.sum { (_, j, a) in a * cofactor(0, j) }
}
}
private func cofactor(_ i0: Int, _ j0: Int) -> BaseRing {
let ε = (-BaseRing.identity).pow(i0 + j0)
let minor = Self(size: (size.rows - 1, size.cols - 1)) { setEntry in
nonZeroEntries.forEach { (i, j, a) in
if i == i0 || j == j0 { return }
let i1 = i < i0 ? i : i - 1
let j1 = j < j0 ? j : j - 1
setEntry(i1, j1, a)
}
}
return ε * minor.determinant
}
@inlinable
public func rowVector(_ i: Int) -> Self {
submatrix(rowRange: i ..< i + 1, colRange: 0 ..< size.cols)
}
@inlinable
public func colVector(_ j: Int) -> Self {
submatrix(rowRange: 0 ..< size.rows, colRange: j ..< j + 1)
}
@inlinable
public func submatrix(rowRange: Range<Int>) -> Self {
submatrix(rowRange: rowRange, colRange: 0 ..< size.cols)
}
@inlinable
public func submatrix(colRange: Range<Int>) -> Self {
submatrix(rowRange: 0 ..< size.rows, colRange: colRange)
}
public func submatrix(rowRange: Range<Int>, colRange: Range<Int>) -> Self {
let size = (rowRange.upperBound - rowRange.lowerBound, colRange.upperBound - colRange.lowerBound)
return .init(size: size ) { setEntry in
nonZeroEntries.forEach { (i, j, a) in
if rowRange.contains(i) && colRange.contains(j) {
setEntry(i - rowRange.lowerBound, j - colRange.lowerBound, a)
}
}
}
}
public func concat(_ B: Self) -> Self {
assert(size.rows == B.size.rows)
let A = self
return .init(size: (A.size.rows, A.size.cols + B.size.cols)) { setEntry in
A.nonZeroEntries.forEach { (i, j, a) in setEntry(i, j, a) }
B.nonZeroEntries.forEach { (i, j, a) in setEntry(i, j + A.size.cols, a) }
}
}
public func stack(_ B: Self) -> Self {
assert(size.cols == B.size.cols)
let A = self
return .init(size: (A.size.rows + B.size.rows, A.size.cols)) { setEntry in
A.nonZeroEntries.forEach { (i, j, a) in setEntry(i, j, a) }
B.nonZeroEntries.forEach { (i, j, a) in setEntry(i + A.size.rows, j, a) }
}
}
@inlinable
public func permuteRows(by p: Permutation<anySize>) -> Self {
permute(rowsBy: p, colsBy: .identity(length: size.cols))
}
@inlinable
public func permuteCols(by q: Permutation<anySize>) -> Self {
permute(rowsBy: .identity(length: size.rows), colsBy: q)
}
public func permute(rowsBy p: Permutation<anySize>, colsBy q: Permutation<anySize>) -> Self {
.init(size: size) { setEntry in
nonZeroEntries.forEach{ (i, j, a) in
setEntry(p[i], q[j], a)
}
}
}
@inlinable
public static prefix func - (a: Self) -> Self {
a.mapNonZeroEntries{ (_, _, a) in -a }
}
@inlinable
public static func -(a: Self, b: Self) -> Self {
assert(a.size == b.size)
return a + (-b)
}
@inlinable
public static func * (r: BaseRing, a: Self) -> Self {
a.mapNonZeroEntries{ (_, _, a) in r * a }
}
@inlinable
public static func * (a: Self, r: BaseRing) -> Self {
a.mapNonZeroEntries{ (_, _, a) in a * r }
}
public static func ⊕ (A: Self, B: Self) -> Self {
.init(size: (A.size.rows + B.size.rows, A.size.cols + B.size.cols)) { setEntry in
A.nonZeroEntries.forEach { (i, j, a) in setEntry(i, j, a) }
B.nonZeroEntries.forEach { (i, j, a) in setEntry(i + A.size.rows, j + A.size.cols, a) }
}
}
public static func ⊗ (A: Self, B: Self) -> Self {
.init(size: (A.size.rows * B.size.rows, A.size.cols * B.size.cols)) { setEntry in
A.nonZeroEntries.forEach { (i, j, a) in
B.nonZeroEntries.forEach { (k, l, b) in
let p = i * B.size.rows + k
let q = j * B.size.cols + l
let c = a * b
setEntry(p, q, c)
}
}
}
}
public func mapNonZeroEntries(_ f: (Int, Int, BaseRing) -> BaseRing) -> Self {
.init(size: size) { setEntry in
nonZeroEntries.forEach { (i, j, a) in
let b = f(i, j, a)
if !b.isZero {
setEntry(i, j, b)
}
}
}
}
public func serialize() -> [BaseRing] {
((0 ..< size.rows) * (0 ..< size.cols)).map{ (i, j) in
self[i, j]
}
}
public var description: String {
"[" + (0 ..< size.rows).map({ i in
(0 ..< size.cols).map({ j in
"\(self[i, j])"
}).joined(separator: ", ")
}).joined(separator: "; ") + "]"
}
public var detailDescription: String {
if size.rows == 0 || size.cols == 0 {
return "[\(size)]"
} else {
return "[\t" + (0 ..< size.rows).map({ i in
(0 ..< size.cols).map({ j in
"\(self[i, j])"
}).joined(separator: ",\t")
}).joined(separator: "\n\t") + "]"
}
}
}
public protocol SparseMatrixImpl: MatrixImpl {
var numberOfNonZeros: Int { get }
var density: Double { get }
}
extension SparseMatrixImpl {
public var isZero: Bool {
numberOfNonZeros == 0
}
public var density: Double {
let N = numberOfNonZeros
return N > 0 ? Double(N) / Double(size.rows * size.cols) : 0
}
}
| cc0-1.0 |
calexity/tabulate | TabulateTests/Tabulate.swift | 1 | 902 | //
// Tip_itTests.swift
// Tip itTests
//
// Created by Alexa Roman on 1/2/15.
// Copyright (c) 2015 Alexa Roman. All rights reserved.
//
import UIKit
/*import XCTest
class TabulateTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}*/
| mpl-2.0 |
jseanj/SwiftMapping | Demo/SwiftMappingDemo/SwiftMappingDemoTests/SwiftMappingDemoTests.swift | 1 | 923 | //
// SwiftMappingDemoTests.swift
// SwiftMappingDemoTests
//
// Created by jins on 14/10/29.
// Copyright (c) 2014年 BlackWater. All rights reserved.
//
import UIKit
import XCTest
class SwiftMappingDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
diogot/MyWeight | MyWeight/Services/UserActivityService.swift | 1 | 358 | //
// UserActivityService.swift
// MyWeight
//
// Created by Diogo on 02/04/17.
// Copyright © 2017 Diogo Tridapalli. All rights reserved.
//
import Foundation
public struct UserActivityService {
public enum ActivityType: String {
case list = "com.diogot.health.My-Weight.list"
case add = "com.diogot.health.My-Weight.add"
}
}
| mit |
maail/MMImageLoader | MMImageLoader/ImageDetailsViewController.swift | 1 | 3454 | //
// ImageDetailsViewController.swift
// MMImageLoader
//
// Created by Mohamed Maail on 5/29/16.
// Copyright © 2016 Mohamed Maail. All rights reserved.
//
import UIKit
class ImageDetailsViewController: UIViewController {
@IBOutlet weak var PictureImageView: UIImageView!
@IBOutlet weak var AuthorLabel: UILabel!
@IBOutlet weak var ProfileImageView: UIImageView!
@IBOutlet weak var AuthorURLLabel: UILabel!
var imageDetails : UnsplashModel!
var imageLoader = MMImageLoader()
var activityIndicator = UIActivityIndicatorView()
override func viewDidLoad() {
super.viewDidLoad()
self.setDefault()
self.setStyle()
self.setData()
}
func setDefault(){
self.title = "Image Details"
//add activity indicator on load
activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50);
activityIndicator.center.x = self.view.center.x
activityIndicator.center.y = self.PictureImageView.center.y - 65
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge
self.PictureImageView.addSubview(activityIndicator)
}
func setStyle(){
self.view.backgroundColor = UIColor(red: 0.797, green: 0.797, blue: 0.797, alpha: 1)
self.ProfileImageView.layer.cornerRadius = self.ProfileImageView.frame.size.width / 2
self.PictureImageView.contentMode = .center
self.PictureImageView.layer.masksToBounds = true
self.navigationController?.navigationBar.tintColor = UIColor.gray
}
func setData(){
self.AuthorLabel.text = imageDetails.Author
self.AuthorURLLabel.text = imageDetails.AuthorURL
//show low res image first
self.activityIndicator.startAnimating()
let lowResImageURL = API.Resize(Width: 200, Height: 0, ImageID: imageDetails.ID)
imageLoader.requestImage(lowResImageURL) { (Status, Image) in
hideStatusBarActivity()
if Status{
self.PictureImageView.contentMode = .scaleAspectFill
self.PictureImageView.image = Image
}
}
//download and set image
showStatusBarActivity()
let resizeImageURL = API.Resize(Width: 1700, Height: 1200, ImageID: imageDetails.ID)
imageLoader.requestImage(resizeImageURL) { (Status, Image) in
hideStatusBarActivity()
self.activityIndicator.stopAnimating()
self.activityIndicator.isHidden = true
if Status{
self.PictureImageView.alpha = 0
UIView.animate(withDuration: 0.5, delay: 0.12, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.PictureImageView.contentMode = .scaleAspectFill
self.PictureImageView.image = Image
self.PictureImageView.alpha = 1
}, completion: nil)
}
}
}
override func viewWillDisappear(_ animated: Bool) {
self.PictureImageView.image = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
manavgabhawala/swift | test/SILGen/rethrows.swift | 1 | 4820 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-sil -verify %s | %FileCheck %s
@discardableResult
func rethrower(_ fn: () throws -> Int) rethrows -> Int {
return try fn()
}
func thrower() throws -> Int { return 0 }
func nonthrower() -> Int { return 0 }
// CHECK-LABEL: sil hidden @_T08rethrows5test0yyKF : $@convention(thin) () -> @error Error {
// CHECK: [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethrowerS2iyKcKF : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (Int, @error Error)
// CHECK: [[THROWER:%.*]] = function_ref @_T08rethrows7throwerSiyKF : $@convention(thin) () -> (Int, @error Error)
// CHECK: [[T0:%.*]] = thin_to_thick_function [[THROWER]]
// CHECK: try_apply [[RETHROWER]]([[T0]]) : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (Int, @error Error), normal [[NORMAL:bb1]], error [[ERROR:bb2]]
// CHECK: [[NORMAL]]([[T0:%.*]] : $Int):
// CHECK-NEXT: [[T1:%.*]] = tuple ()
// CHECK-NEXT: return [[T1]]
// CHECK: [[ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: throw [[T0]]
func test0() throws {
try rethrower(thrower)
}
// CHECK-LABEL: sil hidden @_T08rethrows5test1yyKF : $@convention(thin) () -> @error Error {
// CHECK: [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethrowerS2iyKcKF : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (Int, @error Error)
// CHECK: [[CLOSURE:%.*]] = function_ref @_T08rethrows5test1yyKFSiyKcfU_ : $@convention(thin) () -> (Int, @error Error)
// CHECK: [[T0:%.*]] = thin_to_thick_function [[CLOSURE]]
// CHECK: try_apply [[RETHROWER]]([[T0]]) : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (Int, @error Error), normal [[NORMAL:bb1]], error [[ERROR:bb2]]
// CHECK: [[NORMAL]]([[T0:%.*]] : $Int):
// CHECK-NEXT: [[T1:%.*]] = tuple ()
// CHECK-NEXT: return [[T1]]
// CHECK: [[ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: throw [[T0]]
// Closure.
// CHECK-LABEL: sil shared @_T08rethrows5test1yyKFSiyKcfU_ : $@convention(thin) () -> (Int, @error Error) {
// CHECK: [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethrowerS2iyKcKF : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (Int, @error Error)
// CHECK: [[THROWER:%.*]] = function_ref @_T08rethrows7throwerSiyKF : $@convention(thin) () -> (Int, @error Error)
// CHECK: [[T0:%.*]] = thin_to_thick_function [[THROWER]]
// CHECK: try_apply [[RETHROWER]]([[T0]]) : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (Int, @error Error), normal [[NORMAL:bb1]], error [[ERROR:bb2]]
// CHECK: [[NORMAL]]([[T0:%.*]] : $Int):
// CHECK-NEXT: return [[T0]]
// CHECK: [[ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: throw [[T0]]
func test1() throws {
try rethrower { try rethrower(thrower) }
}
// CHECK-LABEL: sil hidden @_T08rethrows5test2yyF : $@convention(thin) () -> () {
// CHECK: [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethrowerS2iyKcKF : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (Int, @error Error)
// CHECK: [[NONTHROWER:%.*]] = function_ref @_T08rethrows10nonthrowerSiyF : $@convention(thin) () -> Int
// CHECK: [[T0:%.*]] = thin_to_thick_function [[NONTHROWER]]
// CHECK: [[T1:%.*]] = convert_function [[T0]] : $@callee_owned () -> Int to $@callee_owned () -> (Int, @error Error)
// CHECK: try_apply [[RETHROWER]]([[T1]]) : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (Int, @error Error), normal [[NORMAL:bb1]], error [[ERROR:bb2]]
// CHECK: [[NORMAL]]([[T0:%.*]] : $Int):
// CHECK-NEXT: [[T1:%.*]] = tuple ()
// CHECK-NEXT: return [[T1]]
// CHECK: [[ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: unreachable
func test2() {
rethrower(nonthrower)
}
// CHECK-LABEL: sil hidden @_T08rethrows5test3yyF : $@convention(thin) () -> () {
// CHECK: [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethrowerS2iyKcKF : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (Int, @error Error)
// CHECK: [[CLOSURE:%.*]] = function_ref @_T08rethrows5test3yyFSiycfU_ : $@convention(thin) () -> Int
// CHECK: [[T0:%.*]] = thin_to_thick_function [[NONTHROWER]]
// CHECK: [[T1:%.*]] = convert_function [[T0]] : $@callee_owned () -> Int to $@callee_owned () -> (Int, @error Error)
// CHECK: try_apply [[RETHROWER]]([[T1]]) : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (Int, @error Error), normal [[NORMAL:bb1]], error [[ERROR:bb2]]
// CHECK: [[NORMAL]]([[T0:%.*]] : $Int):
// CHECK-NEXT: [[T1:%.*]] = tuple ()
// CHECK-NEXT: return [[T1]]
// CHECK: [[ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: unreachable
func test3() {
rethrower { rethrower(nonthrower) }
}
| apache-2.0 |
nekrich/Localize-Swift | examples/LanguageSwitch/Sample/AppDelegate.swift | 2 | 2167 | //
// AppDelegate.swift
// Sample
//
// Created by Roy Marmelstein on 05/08/2015.
// Copyright (c) 2015 Roy Marmelstein. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
rnystrom/GitHawk | Classes/Login/LoginSplashViewController.swift | 1 | 5755 | //
// LoginSplashViewController.swift
// Freetime
//
// Created by Ryan Nystrom on 7/8/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SafariServices
import GitHubAPI
import GitHubSession
private let loginURL = URLBuilder.github()
.add(paths: ["login", "oauth", "authorize"])
.add(item: "client_id", value: Secrets.GitHub.clientId)
.add(item: "scope", value: "user+repo+notifications")
.url!
private let callbackURLScheme = "freetime://"
protocol LoginSplashViewControllerDelegate: class {
func finishLogin(token: String, authMethod: GitHubUserSession.AuthMethod, username: String)
}
final class LoginSplashViewController: UIViewController {
enum State {
case idle
case fetchingToken
}
private var client: Client!
@IBOutlet weak var splashView: SplashView!
@IBOutlet weak var signInButton: UIButton!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
private weak var delegate: LoginSplashViewControllerDelegate?
@available(iOS 11.0, *)
private var authSession: SFAuthenticationSession? {
get {
return _authSession as? SFAuthenticationSession
}
set {
_authSession = newValue
}
}
private var _authSession: Any?
var state: State = .idle {
didSet {
let hideSpinner: Bool
switch state {
case .idle: hideSpinner = true
case .fetchingToken: hideSpinner = false
}
signInButton.isEnabled = hideSpinner
activityIndicator.isHidden = hideSpinner
let title = hideSpinner
? NSLocalizedString("Sign in with GitHub", comment: "")
: NSLocalizedString("Signing in...", comment: "")
signInButton.setTitle(title, for: .normal)
}
}
override func viewDidLoad() {
super.viewDidLoad()
state = .idle
signInButton.layer.cornerRadius = Styles.Sizes.cardCornerRadius
signInButton.addTouchEffect()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupSplashView()
}
// MARK: Public API
static func make(client: Client, delegate: LoginSplashViewControllerDelegate) -> LoginSplashViewController? {
let controller = UIStoryboard(
name: "OauthLogin",
bundle: Bundle(for: AppDelegate.self))
.instantiateInitialViewController() as? LoginSplashViewController
controller?.client = client
controller?.delegate = delegate
controller?.modalPresentationStyle = .formSheet
return controller
}
// MARK: Private API
@IBAction func onSignInButton(_ sender: Any) {
self.authSession = SFAuthenticationSession(url: loginURL, callbackURLScheme: callbackURLScheme, completionHandler: { [weak self] (callbackUrl, error) in
guard error == nil, let callbackUrl = callbackUrl else {
switch error! {
case SFAuthenticationError.canceledLogin: break
default: self?.handleError()
}
return
}
guard let items = URLComponents(url: callbackUrl, resolvingAgainstBaseURL: false)?.queryItems,
let index = items.index(where: { $0.name == "code" }),
let code = items[index].value
else { return }
self?.state = .fetchingToken
self?.client.requestAccessToken(code: code) { [weak self] result in
switch result {
case .error:
self?.handleError()
case .success(let user):
self?.delegate?.finishLogin(token: user.token, authMethod: .oauth, username: user.username)
}
}
})
self.authSession?.start()
}
@IBAction func onPersonalAccessTokenButton(_ sender: Any) {
let alert = UIAlertController.configured(
title: NSLocalizedString("Personal Access Token", comment: ""),
message: NSLocalizedString("Sign in with a Personal Access Token with both repo and user scopes.", comment: ""),
preferredStyle: .alert
)
alert.addTextField { (textField) in
textField.placeholder = NSLocalizedString("Personal Access Token", comment: "")
}
alert.addActions([
AlertAction.cancel(),
AlertAction.login({ [weak alert, weak self] _ in
alert?.actions.forEach { $0.isEnabled = false }
self?.state = .fetchingToken
let token = alert?.textFields?.first?.text ?? ""
self?.client.send(V3VerifyPersonalAccessTokenRequest(token: token)) { result in
switch result {
case .failure:
self?.handleError()
case .success(let user):
self?.delegate?.finishLogin(token: token, authMethod: .pat, username: user.data.login)
}
}
})
])
present(alert, animated: trueUnlessReduceMotionEnabled)
}
private func handleError() {
state = .idle
let alert = UIAlertController.configured(
title: NSLocalizedString("Error", comment: ""),
message: NSLocalizedString("There was an error signing in to GitHub. Please try again.", comment: ""),
preferredStyle: .alert
)
alert.addAction(AlertAction.ok())
present(alert, animated: trueUnlessReduceMotionEnabled)
}
private func setupSplashView() {
splashView.configureView()
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/16669-no-stacktrace.swift | 11 | 242 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
case
let {
enum b {
var d =
{
class B {
deinit {
func a
{
class
case ,
| mit |
KyoheiG3/RxSwift | RxExample/RxExample/Examples/TableViewWithEditingCommands/User.swift | 14 | 744 | //
// User.swift
// RxExample
//
// Created by Krunoslav Zaher on 12/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
struct User: Equatable, CustomDebugStringConvertible {
var firstName: String
var lastName: String
var imageURL: String
init(firstName: String, lastName: String, imageURL: String) {
self.firstName = firstName
self.lastName = lastName
self.imageURL = imageURL
}
}
extension User {
var debugDescription: String {
return firstName + " " + lastName
}
}
func ==(lhs: User, rhs:User) -> Bool {
return lhs.firstName == rhs.firstName &&
lhs.lastName == rhs.lastName &&
lhs.imageURL == rhs.imageURL
} | mit |
cnoon/swift-compiler-crashes | crashes-fuzzing/06542-swift-unqualifiedlookup-unqualifiedlookup.swift | 11 | 230 | // 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 Q<H{var b{struct d<T where k=b{}struct d<T where H.g:d | mit |
otoshimono/mamorio-reception | ReceptionKit/Models/Contacts.swift | 1 | 3745 | //
// Contacts.swift
// ReceptionKit
//
// Created by Andy Cho on 2015-04-23.
// Copyright (c) 2015 Andy Cho. All rights reserved.
//
import Foundation
import AddressBook
class ContactPhone {
var type: String
var number: String
init(type: String, number: String) {
self.type = type
self.number = number
}
func isWorkPhone() -> Bool {
return self.type == "_$!<Work>!$_"
}
func isMobilePhone() -> Bool {
return self.type == "_$!<Mobile>!$_"
}
}
class Contact {
var name: String
var phones: [ContactPhone]
var picture: UIImage?
init(name: String, phones: [ContactPhone], picture: UIImage?) {
self.name = name
self.phones = phones
self.picture = picture
}
// Check to see if the user has granted the address book permission, ask for permission if not
// Returns true if authorized, false if not
static func isAuthorized() -> Bool {
// Get the authorization if needed
let authStatus = ABAddressBookGetAuthorizationStatus()
if authStatus == .denied || authStatus == .restricted {
Logger.error("No permission to access the contacts")
} else if authStatus == .notDetermined {
ABAddressBookRequestAccessWithCompletion(nil) { (granted: Bool, error: CFError?) in
Logger.debug("Successfully got permission for the contacts")
}
}
// Need to refetch the status if it was updated
return ABAddressBookGetAuthorizationStatus() == ABAuthorizationStatus.authorized
}
// Search for all contacts that match a name
static func search(_ name: String) -> [Contact] {
guard isAuthorized() else {
return []
}
let addressBook: ABAddressBook = ABAddressBookCreateWithOptions(nil, nil).takeUnretainedValue()
let query = name as CFString
let people = ABAddressBookCopyPeopleWithName(addressBook, query).takeRetainedValue() as Array
var contacts = [Contact]()
for person: ABRecord in people {
let contactName: String = ABRecordCopyCompositeName(person).takeRetainedValue() as String
let contactPhoneNumbers = getPhoneNumbers(person, property: kABPersonPhoneProperty)
var contactPicture: UIImage?
if let contactPictureDataOptional = ABPersonCopyImageData(person) {
let contactPictureData = contactPictureDataOptional.takeRetainedValue() as Data
contactPicture = UIImage(data: contactPictureData)
}
contacts.append(Contact(name: contactName, phones: contactPhoneNumbers, picture: contactPicture))
}
return contacts
}
//
// Private functions
//
// Get a property from a ABPerson, returns an array of Strings that matches the value
private static func getPhoneNumbers(_ person: ABRecord, property: ABPropertyID) -> [ContactPhone] {
let personProperty = ABRecordCopyValue(person, property).takeRetainedValue()
guard let personPropertyValues = ABMultiValueCopyArrayOfAllValues(personProperty) else {
return []
}
var propertyValues = [ContactPhone]()
let properties = personPropertyValues.takeUnretainedValue() as NSArray
for (index, property) in properties.enumerated() {
let propertyLabel = ABMultiValueCopyLabelAtIndex(personProperty, index).takeRetainedValue() as String
if let propertyValue = property as? String {
let phone = ContactPhone(type: propertyLabel, number: propertyValue)
propertyValues.append(phone)
}
}
return propertyValues
}
}
| mit |
DylanSecreast/uoregon-cis-portfolio | uoregon-cis-399/examples/W3Example_W17/W3Example/Source/Controller/SecondViewController.swift | 1 | 2808 | //
// SecondViewController.swift
// W3Example
//
// Created by Charles Augustine on 1/27/17.
// Copyright © 2017 Charles. All rights reserved.
//
import UIKit
class SecondViewController : UIViewController {
// MARK: IBAction
@IBAction private func buttonPressed(sender: AnyObject) {
// Only show the third view controller if the system time seconds are even
// and show an alert otherwise.
if Int(Date.timeIntervalSinceReferenceDate) % 2 == 1 {
let alertController = UIAlertController(title: "Unavailable", message: "This button only works on even seconds.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
present(alertController, animated: true)
}
else {
performSegue(withIdentifier: "ThirdViewControllerSegue", sender: sender)
}
}
// MARK: IBAction (Unwind Segue)
@IBAction private func done(sender: UIStoryboardSegue) {
// This method is a special IBAction used as a destination of an unwind segue.
// This is not how you should dismiss your modally presented view controller in
// assignment3. In assignment3 you should put the commented out line of code
// shown below in your delegate method implementation in MainViewController.
// dismiss(animated: true)
}
// MARK: View Management
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// The sender parameter provided to this method is what was passed to performSegue,
// or it is the control that triggered the segue if it was not manually triggered
if segue.identifier == "ThirdViewControllerSegue" {
// Here we can configure the view controller(s) that are about to be presented.
// This is an appropriate place to set any properties relevant for the function
// of the view controllers. A common thing to set here is the delegate of the
// view controller being presented to self.
// Note that the segue parameter has a destination property that allow us to get
// the view controller about to be presented. The properties are of type
// UIViewController so casting is necessary to access a more specific type's
// properties.
let navigationController = segue.destination as! UINavigationController
let thirdViewController = navigationController.topViewController as! ThirdViewController
// Now that we have a reference to the view controller, set its fancyBackgroundColor
// property to a color determined based on the system clock.
let color: UIColor
let timeValue = Int(Date.timeIntervalSinceReferenceDate) % 4
switch timeValue {
case 0:
color = UIColor.lightGray
case 1:
color = UIColor.cyan
default:
color = UIColor.red
}
thirdViewController.fancyBackgroundColor = color
}
else {
super.prepare(for: segue, sender: sender)
}
}
}
| gpl-3.0 |
ktakayama/SimpleRSSReader | Pods/RealmResultsController/Source/RealmResultsController.swift | 1 | 13365 | //
// RealmResultsController.swift
// redbooth-ios-sdk
//
// Created by Isaac Roldan on 4/8/15.
// Copyright © 2015 Redbooth Inc.
//
import Foundation
import UIKit
import RealmSwift
enum RRCError: ErrorType {
case InvalidKeyPath
case EmptySortDescriptors
}
public enum RealmResultsChangeType: String {
case Insert
case Delete
case Update
case Move
}
public protocol RealmResultsControllerDelegate: class {
/**
Notifies the receiver that the realm results controller is about to start processing of one or more changes due to an add, remove, move, or update.
:param: controller The realm results controller that sent the message.
*/
func willChangeResults(controller: AnyObject)
/**
Notifies the receiver that a fetched object has been changed due to an add, remove, move, or update.
:param: controller The realm results controller that sent the message.
:param: object The object in controller’s fetched results that changed.
:param: oldIndexPath The index path of the changed object (this value is the same as newIndexPath for insertions).
:param: newIndexPath The destination path for the object for insertions or moves (this value is the same as oldIndexPath for a deletion).
:param: changeType The type of change. For valid values see RealmResultsChangeType.
*/
func didChangeObject<U>(controller: AnyObject, object: U, oldIndexPath: NSIndexPath, newIndexPath: NSIndexPath, changeType: RealmResultsChangeType)
/**
Notifies the receiver of the addition or removal of a section.
:param: controller The realm results controller that sent the message.
:param: section The section that changed.
:param: index The index of the changed section.
:param: changeType The type of change (insert or delete).
*/
func didChangeSection<U>(controller: AnyObject, section: RealmSection<U>, index: Int, changeType: RealmResultsChangeType)
/**
Notifies the receiver that the realm results controller has completed processing of one or more changes due to an add, remove, move, or update.
:param: controller The realm results controller that sent the message.
*/
func didChangeResults(controller: AnyObject)
}
public class RealmResultsController<T: Object, U> : RealmResultsCacheDelegate {
public weak var delegate: RealmResultsControllerDelegate?
var _test: Bool = false
var populating: Bool = false
var observerAdded: Bool = false
var cache: RealmResultsCache<T>!
private(set) public var request: RealmRequest<T>
private(set) public var filter: (T -> Bool)?
var mapper: T -> U
var sectionKeyPath: String? = ""
var queueManager: RealmQueueManager = RealmQueueManager()
var temporaryAdded: [T] = []
var temporaryUpdated: [T] = []
var temporaryDeleted: [T] = []
/**
All results separated by the sectionKeyPath in RealmSection<U>
Warning: This is computed variable that maps all the avaliable sections using the mapper. Could be an expensive operation
Warning2: The RealmSections contained in the array do not contain objects, only its keyPath
*/
public var sections: [RealmSection<U>] {
return cache.sections.map(realmSectionMapper)
}
/// Number of sections in the RealmResultsController
public var numberOfSections: Int {
return cache.sections.count
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
observerAdded = false
}
//MARK: Initializers
/**
Create a RealmResultsController with a Request, a SectionKeypath to group the results and a mapper.
This init NEEDS a mapper, and all the Realm Models (T) will be transformed using the mapper
to objects of type (U). Done this way to avoid using Realm objects that are not thread safe.
And to decouple the Model layer of the View Layer.
If you want the RRC to return Realm objects that are thread safe, you should use the init
that doesn't require a mapper.
NOTE: If sectionKeyPath is used, it must be equal to the property used in the first SortDescriptor
of the RealmRequest. If not, RRC will throw an error.
NOTE2: Realm does not support sorting by KeyPaths, so you must only use properties of the model
you want to fetch and not KeyPath to any relationship
NOTE3: The RealmRequest needs at least one SortDescriptor
- param: request Request to fetch objects
- param: sectionKeyPath KeyPath to group the results by sections
- param: mapper Mapper to map the results.
- returns: Self
*/
public init(request: RealmRequest<T>, sectionKeyPath: String? ,mapper: T -> U, filter: (T -> Bool)? = nil) throws {
self.request = request
self.mapper = mapper
self.sectionKeyPath = sectionKeyPath
self.cache = RealmResultsCache<T>(request: request, sectionKeyPath: sectionKeyPath)
self.filter = filter
if sortDescriptorsAreEmpty(request.sortDescriptors) {
throw RRCError.EmptySortDescriptors
}
if !keyPathIsValid(sectionKeyPath, sorts: request.sortDescriptors) {
throw RRCError.InvalidKeyPath
}
self.cache?.delegate = self
}
/**
This INIT does not require a mapper, instead will use an empty mapper.
If you plan to use this INIT, you should create the RRC specifiyng T = U
Ex: let RRC = RealmResultsController<TaskModel, TaskModel>....
All objects sent to the delegate of the RRC will be of the model type but
they will be "mirrors", i.e. they don't belong to any Realm DB.
NOTE: If sectionKeyPath is used, it must be equal to the property used in the first SortDescriptor
of the RealmRequest. If not, RRC will throw an error
NOTE2: The RealmRequest needs at least one SortDescriptor
- param: request Request to fetch objects
- param: sectionKeyPath keyPath to group the results of the request
- returns: self
*/
public convenience init(request: RealmRequest<T>, sectionKeyPath: String?) throws {
try self.init(request: request, sectionKeyPath: sectionKeyPath, mapper: {$0 as! U})
}
internal convenience init(forTESTRequest request: RealmRequest<T>, sectionKeyPath: String?, mapper: (T)->(U)) throws {
try self.init(request: request, sectionKeyPath: sectionKeyPath, mapper: mapper)
self._test = true
}
/**
Update the filter currently used in the RRC by a new one.
This func resets completetly the RRC, so:
- It will force the RRC to clean all its cache and refetch all the objects.
- You MUST do a reloadData() in your UITableView after calling this method.
- Not refreshing the table could cause a crash because the indexes changed.
:param: newFilter A Filter closure applied to T: Object
*/
public func updateFilter(newFilter: T -> Bool) {
filter = newFilter
performFetch()
}
//MARK: Fetch
/**
Fetches the initial data for the RealmResultsController
Atention: Must be called after the initialization and should be called only once
*/
public func performFetch() {
populating = true
var objects = self.request.execute().toArray().map{ $0.getMirror() }
if let filter = filter {
objects = objects.filter(filter)
}
self.cache.reset(objects)
populating = false
if !observerAdded { self.addNotificationObservers() }
}
//MARK: Helpers
/**
Returns the number of objects at a given section index
- param: sectionIndex Int
- returns: the objects count at the sectionIndex
*/
public func numberOfObjectsAt(sectionIndex: Int) -> Int {
if cache.sections.count == 0 { return 0 }
return cache.sections[sectionIndex].objects.count
}
/**
Returns the mapped object at a given NSIndexPath
- param: indexPath IndexPath for the desired object
- returns: the object as U (mapped)
*/
public func objectAt(indexPath: NSIndexPath) -> U {
let object = cache.sections[indexPath.section].objects[indexPath.row] as! T
return self.mapper(object)
}
private func sortDescriptorsAreEmpty(sorts: [SortDescriptor]) -> Bool {
return sorts.first == nil
}
// At this point, we are sure sorts.first always has a SortDescriptor
private func keyPathIsValid(keyPath: String?, sorts: [SortDescriptor]) -> Bool {
if keyPath == nil { return true }
return keyPath == sorts.first!.property
}
private func realmSectionMapper<S>(section: Section<S>) -> RealmSection<U> {
return RealmSection<U>(objects: nil, keyPath: section.keyPath)
}
//MARK: Cache delegate
func didInsert<T: Object>(object: T, indexPath: NSIndexPath) {
Threading.executeOnMainThread {
self.delegate?.didChangeObject(self, object: object, oldIndexPath: indexPath, newIndexPath: indexPath, changeType: .Insert)
}
}
func didUpdate<T: Object>(object: T, oldIndexPath: NSIndexPath, newIndexPath: NSIndexPath, changeType: RealmResultsChangeType) {
Threading.executeOnMainThread {
self.delegate?.didChangeObject(self, object: object, oldIndexPath: oldIndexPath, newIndexPath: newIndexPath, changeType: changeType)
}
}
func didDelete<T: Object>(object: T, indexPath: NSIndexPath) {
Threading.executeOnMainThread {
self.delegate?.didChangeObject(self, object: object, oldIndexPath: indexPath, newIndexPath: indexPath, changeType: .Delete)
}
}
func didInsertSection<T : Object>(section: Section<T>, index: Int) {
if populating { return }
Threading.executeOnMainThread {
self.delegate?.didChangeSection(self, section: self.realmSectionMapper(section), index: index, changeType: .Insert)
}
}
func didDeleteSection<T : Object>(section: Section<T>, index: Int) {
Threading.executeOnMainThread {
self.delegate?.didChangeSection(self, section: self.realmSectionMapper(section), index: index, changeType: .Delete)
}
}
//MARK: Realm Notifications
private func addNotificationObservers() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveRealmChanges:", name: "realmChanges", object: nil)
observerAdded = true
}
@objc func didReceiveRealmChanges(notification: NSNotification) {
guard case let notificationObject as [String : [RealmChange]] = notification.object
where notificationObject.keys.first == request.realm.path,
let objects = notificationObject[self.request.realm.path] else { return }
queueManager.addOperation {
self.refetchObjects(objects)
self.finishWriteTransaction()
}
}
private func refetchObjects(objects: [RealmChange]) {
for object in objects {
guard String(object.type) == String(T.self), let mirrorObject = object.mirror as? T else { continue }
if object.action == RealmAction.Delete {
temporaryDeleted.append(mirrorObject)
continue
}
var passesFilter = true
var passesPredicate = true
Threading.executeOnMainThread(true) {
passesPredicate = self.request.predicate.evaluateWithObject(mirrorObject)
if let filter = self.filter {
passesFilter = filter(mirrorObject)
}
}
if object.action == RealmAction.Create && passesPredicate && passesFilter {
temporaryAdded.append(mirrorObject)
}
else if object.action == RealmAction.Update {
if passesFilter && passesPredicate {
temporaryUpdated.append(mirrorObject)
}
else {
temporaryDeleted.append(mirrorObject)
}
}
}
}
func pendingChanges() -> Bool{
return temporaryAdded.count > 0 ||
temporaryDeleted.count > 0 ||
temporaryUpdated.count > 0
}
private func finishWriteTransaction() {
if !pendingChanges() { return }
Threading.executeOnMainThread(true) {
self.delegate?.willChangeResults(self)
}
var objectsToMove: [T] = []
var objectsToUpdate: [T] = []
for object in temporaryUpdated {
cache.updateType(object) == .Move ? objectsToMove.append(object) : objectsToUpdate.append(object)
}
temporaryDeleted.appendContentsOf(objectsToMove)
temporaryAdded.appendContentsOf(objectsToMove)
cache.update(objectsToUpdate)
cache.delete(temporaryDeleted)
cache.insert(temporaryAdded)
temporaryAdded.removeAll()
temporaryDeleted.removeAll()
temporaryUpdated.removeAll()
Threading.executeOnMainThread(true) {
self.delegate?.didChangeResults(self)
}
}
}
| mit |
gewill/Feeyue | Feeyue/Main/Weibo/Views/StatusFooterView.swift | 1 | 6383 | //
// StatusFooterView.swift
// Feeyue
//
// Created by Will on 3/1/16.
// Copyright © 2016 gewill.org. All rights reserved.
//
import UIKit
protocol StatusFooterViewDelegate {
func numberOfCommentCount(_ footerView: StatusFooterView) -> Int
func numberOfRetweetCount(_ footerView: StatusFooterView) -> Int
func footerView(_ footerView: StatusFooterView, didClickRetweenButton: UIButton)
func footerView(_ footerView: StatusFooterView, didClickCommentsButton: UIButton)
}
class StatusFooterView: UITableViewHeaderFooterView {
var delegate: StatusFooterViewDelegate?
var retweetCount = 0
var commentsCount = 0
var retweetButton = UIButton(type: .system)
var commentsButton = UIButton(type: .system)
var buttonUnderline = UIView()
var toRetweetbuttonUnderlineLeadingConstraint: NSLayoutConstraint!
var toRetweetbuttonUnderlineTrailingConstraint: NSLayoutConstraint!
var toCommentsbuttonUnderlineLeadingConstraint: NSLayoutConstraint!
var toCommentsbuttonUnderlineTrailingConstraint: NSLayoutConstraint!
fileprivate let commonGargin: CGFloat = 8
override func draw(_ rect: CGRect) {
self.contentView.backgroundColor = UIColor.white
retweetButton.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14)
commentsButton.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14)
retweetButton.contentHorizontalAlignment = .left
commentsButton.contentHorizontalAlignment = .left
buttonUnderline.backgroundColor = SystemTintColor
let separator = UIView()
separator.backgroundColor = SeparatorColor
self.contentView.addSubview(separator)
self.contentView.addSubview(retweetButton)
self.contentView.addSubview(commentsButton)
self.contentView.addSubview(buttonUnderline)
retweetButton.translatesAutoresizingMaskIntoConstraints = false
commentsButton.translatesAutoresizingMaskIntoConstraints = false
buttonUnderline.translatesAutoresizingMaskIntoConstraints = false
separator.translatesAutoresizingMaskIntoConstraints = false
toCommentsbuttonUnderlineLeadingConstraint = NSLayoutConstraint(item: buttonUnderline, attribute: .leading, relatedBy: .equal, toItem: commentsButton, attribute: .leading, multiplier: 1, constant: 0)
toCommentsbuttonUnderlineTrailingConstraint = NSLayoutConstraint(item: buttonUnderline, attribute: .trailing, relatedBy: .equal, toItem: commentsButton, attribute: .trailing, multiplier: 1, constant: 0)
toRetweetbuttonUnderlineLeadingConstraint = NSLayoutConstraint(item: buttonUnderline, attribute: .leading, relatedBy: .equal, toItem: retweetButton, attribute: .leading, multiplier: 1, constant: 0)
toRetweetbuttonUnderlineTrailingConstraint = NSLayoutConstraint(item: buttonUnderline, attribute: .trailing, relatedBy: .equal, toItem: retweetButton, attribute: .trailing, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([
retweetButton.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: commonGargin),
retweetButton.trailingAnchor.constraint(equalTo: commentsButton.leadingAnchor, constant: -commonGargin),
retweetButton.centerYAnchor.constraint(equalTo: self.centerYAnchor),
commentsButton.centerYAnchor.constraint(equalTo: self.centerYAnchor),
buttonUnderline.heightAnchor.constraint(equalToConstant: 3),
buttonUnderline.bottomAnchor.constraint(equalTo: self.bottomAnchor),
separator.bottomAnchor.constraint(equalTo: self.bottomAnchor),
separator.leadingAnchor.constraint(equalTo: self.leadingAnchor),
separator.trailingAnchor.constraint(equalTo: self.trailingAnchor),
separator.heightAnchor.constraint(equalToConstant: 1)
])
self.underlineAlignToCommentsButton()
// self.ChangeRetweetCountAndCommentCount()
retweetButton.addTarget(self, action: #selector(StatusFooterView.retweetButtonClick), for: .touchDown)
commentsButton.addTarget(self, action: #selector(StatusFooterView.commentsButtonClick), for: .touchDown)
}
override func layoutSubviews() {
super.layoutSubviews()
self.ChangeRetweetCountAndCommentCount()
}
// MARK: - response methods
@objc func retweetButtonClick() {
self.underlineAlignToRetweenButton()
delegate?.footerView(self, didClickRetweenButton: retweetButton)
}
@objc func commentsButtonClick() {
self.underlineAlignToCommentsButton()
delegate?.footerView(self, didClickCommentsButton: commentsButton)
}
// MARK: - private methods
func ChangeRetweetCountAndCommentCount() {
if let count = delegate?.numberOfRetweetCount(self) {
retweetCount = count
}
if let count = delegate?.numberOfCommentCount(self) {
commentsCount = count
}
retweetButton.setTitle("Retweet: \(retweetCount)", for: UIControl.State())
commentsButton.setTitle("Comment: \(commentsCount)", for: UIControl.State())
}
fileprivate func underlineAlignToRetweenButton() {
self.retweetButton.setTitleColor(SystemTintColor, for: UIControl.State())
self.commentsButton.setTitleColor(HalfSystemTintColor, for: UIControl.State())
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.toRetweetbuttonUnderlineLeadingConstraint.isActive = true
self.toRetweetbuttonUnderlineTrailingConstraint.isActive = true
self.toCommentsbuttonUnderlineLeadingConstraint.isActive = false
self.toCommentsbuttonUnderlineTrailingConstraint.isActive = false
})
}
fileprivate func underlineAlignToCommentsButton() {
self.commentsButton.setTitleColor(SystemTintColor, for: UIControl.State())
self.retweetButton.setTitleColor(HalfSystemTintColor, for: UIControl.State())
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.toRetweetbuttonUnderlineLeadingConstraint.isActive = false
self.toRetweetbuttonUnderlineTrailingConstraint.isActive = false
self.toCommentsbuttonUnderlineLeadingConstraint.isActive = true
self.toCommentsbuttonUnderlineTrailingConstraint.isActive = true
})
}
}
| mit |
dmitryelj/SDR-Frequency-Plotter-OSX | FrequencyPlotter/ViewControllerSettings.swift | 1 | 1564 | //
// ViewControllerSettings.swift
// SpectrumGraph
//
// Created by Dmitrii Eliuseev on 21/03/16.
// Copyright © 2016 Dmitrii Eliuseev. All rights reserved.
// dmitryelj@gmail.com
import Cocoa
class ViewControllerSettings: NSViewController {
@IBOutlet weak var labelGain1: NSTextField!
@IBOutlet weak var sliderGain1: NSSlider!
@IBOutlet weak var labelGain2: NSTextField!
@IBOutlet weak var sliderGain2: NSSlider!
var titleGain1:String = ""
var valueGain1:CGFloat = 0
var valueGain1Low:CGFloat = 0
var valueGain1High:CGFloat = 100
var titleGain2:String = ""
var valueGain2:CGFloat = 0
var valueGain2Low:CGFloat = 0
var valueGain2High:CGFloat = 100
var onDidChangedGain1: ((CGFloat) -> Void)?
var onDidChangedGain2: ((CGFloat) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
labelGain1.stringValue = titleGain1
sliderGain1.minValue = Double(valueGain1Low)
sliderGain1.maxValue = Double(valueGain1High)
sliderGain1.floatValue = Float(valueGain1)
labelGain2.stringValue = titleGain2
sliderGain2.minValue = Double(valueGain2Low)
sliderGain2.maxValue = Double(valueGain2High)
sliderGain2.floatValue = Float(valueGain2)
}
@IBAction func onSliderGain1ValueChanged(sender: AnyObject) {
let val = CGFloat(sliderGain1.floatValue)
if let ch = onDidChangedGain1 {
ch(val)
}
}
@IBAction func onSliderGain2ValueChanged(sender: AnyObject) {
let val = CGFloat(sliderGain2.floatValue)
if let ch = onDidChangedGain2 {
ch(val)
}
}
}
| gpl-3.0 |
tardieu/swift | test/Generics/same_type_constraints.swift | 2 | 7196 | // RUN: %target-typecheck-verify-swift
protocol Fooable {
associatedtype Foo
var foo: Foo { get }
}
protocol Barrable {
associatedtype Bar: Fooable
var bar: Bar { get }
}
struct X {}
struct Y: Fooable {
typealias Foo = X
var foo: X { return X() }
}
struct Z: Barrable {
typealias Bar = Y
var bar: Y { return Y() }
}
protocol TestSameTypeRequirement {
func foo<F1: Fooable>(_ f: F1) where F1.Foo == X
}
struct SatisfySameTypeRequirement : TestSameTypeRequirement {
func foo<F2: Fooable>(_ f: F2) where F2.Foo == X {}
}
protocol TestSameTypeAssocTypeRequirement {
associatedtype Assoc
func foo<F1: Fooable>(_ f: F1) where F1.Foo == Assoc
}
struct SatisfySameTypeAssocTypeRequirement : TestSameTypeAssocTypeRequirement {
typealias Assoc = X
func foo<F2: Fooable>(_ f: F2) where F2.Foo == X {}
}
struct SatisfySameTypeAssocTypeRequirementDependent<T>
: TestSameTypeAssocTypeRequirement
{
typealias Assoc = T
func foo<F3: Fooable>(_ f: F3) where F3.Foo == T {}
}
// Pulled in from old standard library to keep the following test
// (LazySequenceOf) valid.
public struct GeneratorOf<T> : IteratorProtocol, Sequence {
/// Construct an instance whose `next()` method calls `nextElement`.
public init(_ nextElement: @escaping () -> T?) {
self._next = nextElement
}
/// Construct an instance whose `next()` method pulls its results
/// from `base`.
public init<I : IteratorProtocol>(_ base: I) where I.Element == T {
var base = base
self._next = { base.next() }
}
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> T? {
return _next()
}
/// `GeneratorOf<T>` is also a `Sequence`, so it `generate`\ s
/// a copy of itself
public func makeIterator() -> GeneratorOf {
return self
}
let _next: () -> T?
}
// rdar://problem/19009056
public struct LazySequenceOf<S : Sequence, A> : Sequence where S.Iterator.Element == A {
public func makeIterator() -> GeneratorOf<A> {
return GeneratorOf<A>({ return nil })
}
public subscript(i : A) -> A { return i }
}
public func iterate<A>(_ f : @escaping (A) -> A) -> (_ x : A) -> LazySequenceOf<Iterate<A>, A>? {
return { x in nil }
}
public final class Iterate<A> : Sequence {
typealias IteratorProtocol = IterateGenerator<A>
public func makeIterator() -> IterateGenerator<A> {
return IterateGenerator<A>()
}
}
public final class IterateGenerator<A> : IteratorProtocol {
public func next() -> A? {
return nil
}
}
// rdar://problem/18475138
public protocol Observable : class {
associatedtype Output
func addObserver(_ obj : @escaping (Output) -> Void)
}
public protocol Bindable : class {
associatedtype Input
func foo()
}
class SideEffect<In> : Bindable {
typealias Input = In
func foo() { }
}
struct Composed<Left: Bindable, Right: Observable> where Left.Input == Right.Output {}
infix operator <- : AssignmentPrecedence
func <- <
Right : Observable
>(lhs: @escaping (Right.Output) -> Void, rhs: Right) -> Composed<SideEffect<Right>, Right>?
{
return nil
}
// rdar://problem/17855378
struct Pair<T, U> {
typealias Type_ = (T, U)
}
protocol Seq {
associatedtype Element
func zip<OtherSeq: Seq, ResultSeq: Seq> (_ otherSeq: OtherSeq) -> ResultSeq
where ResultSeq.Element == Pair<Element, OtherSeq.Element>.Type_
}
// rdar://problem/18435371
extension Dictionary {
func multiSubscript<S : Sequence>(_ seq: S) -> [Value?] where S.Iterator.Element == Key {
var result = [Value?]()
for seqElt in seq {
result.append(self[seqElt])
}
return result
}
}
// rdar://problem/19245317
protocol P {
associatedtype T: P // expected-error{{type may not reference itself as a requirement}}
}
struct S<A: P> {
init<Q: P>(_ q: Q) where Q.T == A {}
}
// rdar://problem/19371678
protocol Food { }
class Grass : Food { }
protocol Animal {
associatedtype EdibleFood:Food
func eat(_ f:EdibleFood)
}
class Cow : Animal {
func eat(_ f: Grass) { }
}
struct SpecificAnimal<F:Food> : Animal {
typealias EdibleFood=F
let _eat:(_ f:F) -> ()
init<A:Animal>(_ selfie:A) where A.EdibleFood == F {
_eat = { selfie.eat($0) }
}
func eat(_ f:F) {
_eat(f)
}
}
// rdar://problem/18803556
struct Something<T> {
var items: [T] = []
}
extension Something {
init<S : Sequence>(_ s: S) where S.Iterator.Element == T {
for item in s {
items.append(item)
}
}
}
// rdar://problem/18120419
func TTGenWrap<T, I : IteratorProtocol>(_ iterator: I) where I.Element == (T,T)
{
var iterator = iterator
_ = iterator.next()
}
func IntIntGenWrap<I : IteratorProtocol>(_ iterator: I) where I.Element == (Int,Int)
{
var iterator = iterator
_ = iterator.next()
}
func GGWrap<I1 : IteratorProtocol, I2 : IteratorProtocol>(_ i1: I1, _ i2: I2) where I1.Element == I2.Element
{
var i1 = i1
var i2 = i2
_ = i1.next()
_ = i2.next()
}
func testSameTypeTuple(_ a: Array<(Int,Int)>, s: ArraySlice<(Int,Int)>) {
GGWrap(a.makeIterator(), s.makeIterator())
TTGenWrap(a.makeIterator())
IntIntGenWrap(s.makeIterator())
}
// rdar://problem/20256475
protocol FooProtocol {
associatedtype Element
func getElement() -> Element
}
protocol Bar {
associatedtype Foo : FooProtocol
func getFoo() -> Foo
mutating func extend<C : FooProtocol>(_ elements: C)
where C.Element == Foo.Element
}
// rdar://problem/21620908
protocol P1 { }
protocol P2Base { }
protocol P2 : P2Base {
associatedtype Q : P1
func getQ() -> Q
}
struct XP1<T : P2Base> : P1 {
func wibble() { }
}
func sameTypeParameterizedConcrete<C : P2>(_ c: C) where C.Q == XP1<C> {
c.getQ().wibble()
}
// rdar://problem/21621421
protocol P3 {
associatedtype AssocP3 : P1
}
protocol P4 {
associatedtype AssocP4 : P3
}
struct X1 : P1 { }
struct X3 : P3 {
typealias AssocP3 = X1
}
func foo<C : P4>(_ c: C) where C.AssocP4 == X3 {}
struct X4 : P4 {
typealias AssocP4 = X3
}
func testFoo(_ x3: X4) {
foo(x3)
}
// rdar://problem/21625478
struct X6<T> { }
protocol P6 { }
protocol P7 {
associatedtype AssocP7
}
protocol P8 {
associatedtype AssocP8 : P7
associatedtype AssocOther
}
func testP8<C : P8>(_ c: C) where C.AssocOther == X6<C.AssocP8.AssocP7> {}
// setGenericSignature() was getting called twice here
struct Ghost<T> {}
protocol Timewarp {
associatedtype Wormhole
}
struct Teleporter<A, B> where A : Timewarp, A.Wormhole == Ghost<B> {}
struct Beam {}
struct EventHorizon : Timewarp {
typealias Wormhole = Ghost<Beam>
}
func activate<T>(_ t: T) {}
activate(Teleporter<EventHorizon, Beam>())
// rdar://problem/29288428
class C {}
protocol P9 {
associatedtype A
}
struct X7<T: P9> where T.A : C { }
extension X7 where T.A == Int { } // expected-error {{'T.A' requires that 'Int' inherit from 'C'}}
struct X8<T: C> { }
extension X8 where T == Int { } // expected-error {{'T' requires that 'Int' inherit from 'C'}}
| apache-2.0 |
tardieu/swift | test/decl/protocol/req/name_mismatch.swift | 21 | 1764 | // RUN: %target-typecheck-verify-swift
protocol P {
func foo(_ i: Int, x: Float) // expected-note 4{{requirement 'foo(_:x:)' declared here}}
}
struct S1 : P {
func foo(_ i: Int, x: Float) { }
}
struct S2 : P {
func foo(_ i: Int, _ x: Float) { } // expected-error{{method 'foo' has different argument names from those required by protocol 'P' ('foo(_:x:)')}}{{22-24=}}
}
struct S3 : P {
func foo(_ i: Int, y: Float) { } // expected-error{{method 'foo(_:y:)' has different argument names from those required by protocol 'P' ('foo(_:x:)')}}{{22-22=x }}
}
struct S4 : P {
func foo(_ i: Int, _: Float) { } // expected-error{{method 'foo' has different argument names from those required by protocol 'P' ('foo(_:x:)')}}{{22-22=x }}
}
struct S5 : P {
func foo(_ i: Int, z x: Float) { } // expected-error{{method 'foo(_:z:)' has different argument names from those required by protocol 'P' ('foo(_:x:)')}}{{22-24=}}
}
struct Loadable { }
protocol LabeledRequirement {
func method(x: Loadable)
}
struct UnlabeledWitness : LabeledRequirement {
func method(x _: Loadable) {}
}
// rdar://problem/21333445
protocol P2 {
init(_ : Int) // expected-note{{requirement 'init' declared here}}
}
struct XP2 : P2 { // expected-error{{initializer 'init(foo:)' has different argument names from those required by protocol 'P2' ('init')}}
let foo: Int
}
// rdar://problem/22981205
protocol P3 {
subscript(val: String, label arg: String) -> Int { get } // expected-note{{requirement 'subscript(_:label:)' declared here}}
}
class MislabeledSubscript : P3 {
subscript(val: String, label: String) -> Int { // expected-error{{method 'subscript' has different argument names from those required by protocol 'P3' ('subscript(_:label:)')}}
return 1
}
}
| apache-2.0 |
burakustn/BUSimplePopup | Example/Tests/Tests.swift | 1 | 763 | import UIKit
import XCTest
import BUSimplePopup
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
hejunbinlan/Carlos | Tests/CacheRequestTests.swift | 2 | 13478 | import Foundation
import Quick
import Nimble
import Carlos
class CacheRequestTests: QuickSpec {
override func spec() {
describe("CacheRequest") {
var request: CacheRequest<String>!
var successSentinels: [String?]!
var failureSentinels: [NSError?]!
context("when initialized with the empty initializer") {
beforeEach {
request = CacheRequest<String>()
successSentinels = [nil, nil, nil]
failureSentinels = [nil, nil, nil]
}
context("when calling onSuccess") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onSuccess({ result in
successSentinels[idx] = result
})
}
}
it("should not immediately call the closures") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
context("when calling succeed") {
let value = "success value"
beforeEach {
request.succeed(value)
}
it("should call the closures") {
expect(successSentinels).to(allPass({ $0! == value }))
}
context("when calling onSuccess again") {
var subsequentSuccessSentinel: String?
beforeEach {
request.onSuccess({ result in
subsequentSuccessSentinel = result
})
}
it("should immediately call the closures") {
expect(subsequentSuccessSentinel).to(equal(value))
}
}
}
context("when calling fail") {
beforeEach {
request.fail(nil)
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
}
}
context("when calling onFailure") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onFailure({ error in
failureSentinels[idx] = error
})
}
}
it("should not immediately call the closures") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
context("when calling fail") {
let errorCode = -1100
beforeEach {
request.fail(NSError(domain: "test", code: errorCode, userInfo: nil))
}
it("should call the closures") {
expect(failureSentinels).to(allPass({ $0!?.code == errorCode }))
}
context("when calling onFailure again") {
var subsequentFailureSentinel: NSError?
beforeEach {
request.onFailure({ error in
subsequentFailureSentinel = error
})
}
it("should immediately call the closures") {
expect(subsequentFailureSentinel?.code).to(equal(errorCode))
}
}
}
context("when calling succeed") {
beforeEach {
request.succeed("test")
}
it("should not call any closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
}
}
context("when calling onCompletion") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onCompletion({ value, error in
failureSentinels[idx] = error
successSentinels[idx] = value
})
}
}
it("should not immediately call the closures passing an error") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
it("should not immediately call the closures passing a value") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
context("when calling fail") {
let errorCode = -1100
beforeEach {
request.fail(NSError(domain: "test", code: errorCode, userInfo: nil))
}
it("should call the closures passing an error") {
expect(failureSentinels).to(allPass({ $0!?.code == errorCode }))
}
it("should not call the closures passing a value") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
context("when calling onCompletion again") {
var subsequentFailureSentinel: NSError?
var subsequentSuccessSentinel: String?
beforeEach {
request.onCompletion({ value, error in
subsequentSuccessSentinel = value
subsequentFailureSentinel = error
})
}
it("should immediately call the closure passing an error") {
expect(subsequentFailureSentinel?.code).to(equal(errorCode))
}
it("should not immediately call the closure passing a value") {
expect(subsequentSuccessSentinel).to(beNil())
}
}
}
context("when calling succeed") {
let value = "success value"
beforeEach {
request.succeed(value)
}
it("should call the closures passing a value") {
expect(successSentinels).to(allPass({ $0! == value }))
}
it("should not call the closures passing an error") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
context("when calling onCompletion again") {
var subsequentSuccessSentinel: String?
var subsequentFailureSentinel: NSError?
beforeEach {
request.onCompletion({ result, error in
subsequentSuccessSentinel = result
subsequentFailureSentinel = error
})
}
it("should immediately call the closure passing a value") {
expect(subsequentSuccessSentinel).to(equal(value))
}
it("should not immediately call the closure passing an error") {
expect(subsequentFailureSentinel).to(beNil())
}
}
}
}
}
context("when initialized with a value") {
let value = "this is a sync success value"
beforeEach {
request = CacheRequest(value: value)
successSentinels = [nil, nil, nil]
failureSentinels = [nil, nil, nil]
}
context("when calling onSuccess") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onSuccess({ result in
successSentinels[idx] = result
})
}
}
it("should immediately call the closures") {
expect(successSentinels.filter({ $0 != nil }).count).to(equal(successSentinels.count))
}
it("should pass the right value") {
expect(successSentinels).to(allPass({ $0! == value }))
}
}
context("when calling onFailure") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onFailure({ error in
failureSentinels[idx] = error
})
}
}
it("should not call the closures") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
}
context("when calling onCompletion") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onCompletion({ value, error in
successSentinels[idx] = value
failureSentinels[idx] = error
})
}
}
it("should not call the closures passing an error") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
it("should call the closures passing a value") {
expect(successSentinels).to(allPass({ $0! == value }))
}
}
}
context("when initialized with an error") {
context("when the error is not nil") {
let error = NSError(domain: "Test", code: 10, userInfo: nil)
beforeEach {
request = CacheRequest<String>(error: error)
successSentinels = [nil, nil, nil]
failureSentinels = [nil, nil, nil]
}
context("when calling onSuccess") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onSuccess({ result in
successSentinels[idx] = result
})
}
}
it("should not call the closures") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
}
context("when calling onFailure") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onFailure({ error in
failureSentinels[idx] = error
})
}
}
it("should immediately call the closures") {
expect(failureSentinels.filter({ $0 != nil }).count).to(equal(failureSentinels.count))
}
it("should pass the right error") {
expect(failureSentinels).to(allPass({ $0!!.code == error.code }))
}
}
context("when calling onCompletion") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onCompletion({ value, error in
successSentinels[idx] = value
failureSentinels[idx] = error
})
}
}
it("should immediately call the closures") {
expect(failureSentinels.filter({ $0 != nil }).count).to(equal(failureSentinels.count))
}
it("should pass the right error") {
expect(failureSentinels).to(allPass({ $0!!.code == error.code }))
}
it("should not pass a value") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
}
}
context("when the error is nil") {
var failureSentinels: [Bool?]!
beforeEach {
request = CacheRequest<String>(error: nil)
successSentinels = [nil, nil, nil]
failureSentinels = [nil, nil, nil]
}
context("when calling onSuccess") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onSuccess({ result in
successSentinels[idx] = result
})
}
}
it("should not call the closures") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
}
context("when calling onFailure") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onFailure({ error in
failureSentinels[idx] = true
})
}
}
it("should immediately call the closures") {
expect(failureSentinels.filter({ $0 != nil }).count).to(equal(failureSentinels.count))
}
}
context("when calling onCompletion") {
beforeEach {
for idx in 0..<successSentinels.count {
request.onCompletion({ value, error in
failureSentinels[idx] = true
successSentinels[idx] = value
})
}
}
it("should immediately call the closures") {
expect(failureSentinels.filter({ $0 != nil }).count).to(equal(failureSentinels.count))
}
it("should not pass a value") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
}
}
}
}
}
} | mit |
twtstudio/WePeiYang-iOS | WePeiYang/Bicycle/Model/NotificationList.swift | 1 | 1889 | //
// NotificationList.swift
// WePeiYang
//
// Created by JinHongxu on 16/8/10.
// Copyright © 2016年 Qin Yubo. All rights reserved.
//
import Foundation
class NotificationList: NSObject {
var list: Array<NotificationItem> = []
var newestTimeStamp: Int = 0
var didGetNewNotification: Bool = false
static let sharedInstance = NotificationList()
private override init() {}
func getList(doSomething: () -> ()) {
list.removeAll()
let manager = AFHTTPSessionManager()
manager.GET(BicycleAPIs.notificationURL, parameters: nil, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) in
let dic = responseObject as? NSDictionary
//log.obj(dic!)/
guard dic?.objectForKey("errno") as? NSNumber == 0 else {
MsgDisplay.showErrorMsg(dic?.objectForKey("errmsg") as? String)
return
}
guard let foo = dic?.objectForKey("data") as? NSArray else {
MsgDisplay.showErrorMsg("获取信息失败")
return
}
if foo.count > 0 {
let fooTimeStamp = Int(foo[0].objectForKey("timestamp") as! String)!
if fooTimeStamp > self.newestTimeStamp {
self.didGetNewNotification = true
self.newestTimeStamp = fooTimeStamp
}
}
for dict in foo {
self.list.append(NotificationItem(dict: dict as! NSDictionary))
}
doSomething()
}, failure: { (task: NSURLSessionDataTask?, error: NSError) in
MsgDisplay.showErrorMsg("网络错误,请稍后再试")
print("error: \(error)")
})
}
} | mit |
atl009/WordPress-iOS | WordPressKit/WordPressKitTests/WordPressOrgXMLRPCApiTests.swift | 2 | 1504 | import Foundation
import XCTest
import OHHTTPStubs
@testable import WordPressKit
class WordPressOrgXMLRPCApiTests: XCTestCase {
let xmlrpcEndpoint = "http://wordpress.org/xmlrpc.php"
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
OHHTTPStubs.removeAllStubs()
}
fileprivate func isXmlRpcAPIRequest() -> OHHTTPStubsTestBlock {
return { request in
return request.url?.absoluteString == self.xmlrpcEndpoint
}
}
func testSuccessfullCall() {
stub(condition: isXmlRpcAPIRequest()) { request in
let stubPath = OHPathForFile("xmlrpc-response-getpost.xml", type(of: self))
return fixture(filePath: stubPath!, headers: ["Content-Type" as NSObject: "application/xml" as AnyObject])
}
let expect = self.expectation(description: "One callback should be invoked")
let api = WordPressOrgXMLRPCApi(endpoint: URL(string: xmlrpcEndpoint)! as URL)
api.callMethod("wp.getPost", parameters: nil, success: { (responseObject: AnyObject, httpResponse: HTTPURLResponse?) in
expect.fulfill()
XCTAssert(responseObject is [String: AnyObject], "The response should be a dictionary")
}, failure: { (error, httpResponse) in
expect.fulfill()
XCTFail("This call should be successfull")
}
)
self.waitForExpectations(timeout: 2, handler: nil)
}
}
| gpl-2.0 |
pisarm/Gojira | GojiraTests/GojiraTests.swift | 1 | 975 | //
// GojiraTests.swift
// GojiraTests
//
// Created by Flemming Pedersen on 01/11/15.
// Copyright © 2015 pisarm.dk. All rights reserved.
//
import XCTest
@testable import Gojira
class GojiraTests: 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.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
bvic23/VinceRP | VinceRPTests/Common/Util/WeakReferenceTests.swift | 1 | 2136 | //
// Created by Viktor Belenyesi on 20/04/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
@testable import VinceRP
import Quick
import Nimble
let v = NSObject()
class WeakReferenceSpec: QuickSpec {
override func spec() {
context("value") {
it("does not hold it's value") {
// when
let wr = WeakReference(NSObject())
// then
expect(wr.value).to(beNil())
}
it("keeps it's value if it got hold outside") {
// when
let wr = WeakReference(v)
// then
expect(wr.value) == v
}
}
describe("hash") {
it("'s hash is not 0 if reference is valid") {
// when
let wr = WeakReference(v)
// then
expect(wr.hashValue) != 0
}
it("'s hash is 0 if reference is gone") {
// when
let wr = WeakReference(NSObject())
// then
expect(wr.hashValue) == 0
}
}
describe("equality") {
it("holds equality for same instances") {
// when
let w1 = WeakReference(v)
let w2 = WeakReference(v)
// then
expect(w1) == w2
}
it("holds equality for nil reference") {
// when
let w1 = WeakReference(NSObject())
let w2 = WeakReference(NSObject())
// then
expect(w1) == w2
expect(w1.hashValue) == 0
}
it("holds equality the same hasValue") {
// when
let w1 = WeakReference(Foo())
let w2 = WeakReference(Foo())
// then
expect(w1) == w2
}
}
}
}
| mit |
royhsu/RHGoogleMapsDirections | RHGoogleMapsDirections/RHLocation.swift | 1 | 361 | //
// RHLocation.swift
// RHGoogleMapsDirections
//
// Created by 許郁棋 on 2015/4/26.
// Copyright (c) 2015年 tinyworld. All rights reserved.
//
import Foundation
class RHLocation {
let latitude: Double
let longitude: Double
init(latitude lat: Double, longitude long: Double) {
latitude = lat
longitude = long
}
} | mit |
tinrobots/Mechanica | Sources/StandardLibrary/String+Utils.swift | 1 | 15851 | extension String {
/// Creates a string containing the given 'StaticString'.
///
/// - Parameter staticString: The 'StaticString' to convert to a string.
public init(staticString: StaticString) {
self = staticString.withUTF8Buffer {
String(decoding: $0, as: UTF8.self)
}
}
/// **Mechanica**
///
/// Returns a `new` string containing the first character of the `String`.
public var first: String {
let first = self[..<index(after: startIndex)]
return String(first)
}
/// **Mechanica**
///
/// Checks if all of the characters in a string are all the same.
public var isHomogeneous: Bool {
for char in dropFirst() where char != first {
return false
}
return true
}
/// **Mechanica**
///
/// Returns true if all the characters are lowercased.
public var isLowercase: Bool {
return self == lowercased()
}
/// **Mechanica**
///
/// Returns true, if all characters are uppercased. Otherwise, false.
public var isUppercase: Bool {
return self == uppercased()
}
/// **Mechanica**
///
/// Returns a `new` string containing the last character of the `String`.
public var last: String {
let last = self[index(before: endIndex)...]
return String(last)
}
/// **Mechanica**
///
/// Returns the length of the `String`.
public var length: Int {
return count
}
/// **Mechanica**
///
/// Returns a `new` String with the center-padded version of `self` if it's shorter than `length` using a `token`. Padding characters are truncated if they can't be evenly divided by length.
///
/// Example 1:
///
/// let string = "Hello World"
/// string.padding(length: 15) -> " Hello World "
///
/// Example 2:
///
/// let string = "Hello World"
/// string.padding(length: 15, withToken: "*") -> "**Hello World**"
///
/// - Parameters:
/// - length: The final length of your string. If the provided length is less than or equal to the original string, the original string is returned.
/// - token: The string used to pad the String (defaults to a white space).
/// - Returns: The padded copy of the string.
/// - Note: If the the sum-total of characters added is odd, the left side of the string will have one less instance of the token.
public func padding(length: Int, with token: String = " ") -> String {
guard count < length else { return self }
let padLength = length - count
let halfPadLength = Double(padLength) / 2
let roundedStartingPadLength = Int(halfPadLength.rounded(.toNearestOrAwayFromZero))
return paddingStart(length: length - roundedStartingPadLength, with: token).paddingEnd(length: length, with: token)
}
/// **Mechanica**
///
/// Pads `self on the left and right sides if it's shorter than `length` using a `token`. Padding characters are truncated if they can't be evenly divided by length.
///
/// Example 1:
///
/// let string = "Hello World"
/// string.pad(length: 15) -> " Hello World "
///
/// Example 2:
///
/// let string = "Hello World"
/// string.pad(length: 15, withToken: "*") -> "**Hello World**"
///
/// - Parameters:
/// - length: The final length of your string. If the provided length is less than or equal to the original string, the original string is returned.
/// If the the sum-total of characters added is odd, the left side of the string will have one less instance of the token.
/// - token: The string used to pad the String (defaults to a white space).
/// - Note: If the the sum-total of characters added is odd, the left side of the string will have one less instance of the token.
public mutating func pad(length: Int, with token: String = " ") {
self = padding(length: length, with: token)
}
/// **Mechanica**
///
/// Returns a `new` String with the left-padded version of `self` if it's shorter than `length` using a `token`. Padding characters are truncated if they can't be evenly divided by length.
///
/// Example 1:
///
/// let string = "Hello World"
/// string.paddingStart(length: 15) -> " Hello World"
///
/// Example 2:
///
/// let string = "Hello World"
/// string.paddingStart(length: 15, withToken: "*") -> "****Hello World"
///
/// - Parameters:
/// - length: The final length of your string.
/// - token: The string used to pad the String (defaults to a white space).
/// - Returns: The left-padded copy of the string.
public func paddingStart(length: Int, with token: String = " ") -> String {
guard count < length else { return self }
let padLength = length - count
if padLength < token.count {
return token[token.startIndex..<token.index(token.startIndex, offsetBy: padLength)] + self
} else {
var padding = token
while padding.count < padLength {
padding.append(token)
}
return padding[padding.startIndex..<padding.index(padding.startIndex, offsetBy: padLength)] + self
}
}
/// **Mechanica**
///
/// Pads `self` on the left side if it's shorter than `length` using a `token`. Padding characters are truncated if they exceed length.
///
/// Example 1:
///
/// let string = "Hello World"
/// string.padStart(length: 15) -> " Hello World"
///
/// Example 2:
///
/// let string = "Hello World"
/// string.padStart(length: 15, withToken: "*") -> "****Hello World"
///
/// - Parameters:
/// - length: The final length of your string.
/// - token: The string used to pad the String (defaults to a white space).
public mutating func padStart(length: Int, with token: String = " ") {
self = paddingStart(length: length, with: token)
}
/// **Mechanica**
///
/// Returns a `new` String with the right-padded version of `self` if it's shorter than `length` using a `token`. Padding characters are truncated if they can't be evenly divided by length.
///
/// Example 1:
///
/// let string = "Hello World"
/// string.paddingEnd(length: 15) -> "Hello World "
///
/// Example 2:
///
/// let string = "Hello World"
/// string.paddingEnd(length: 15, withToken: "*", ) -> "Hello World****"
///
/// - Parameters:
/// - length: The final length of your string.
/// - token: The string used to pad the String (defaults to a white space).
/// - Returns: The right-padded copy of the string.
public func paddingEnd(length: Int, with token: String = " ") -> String {
guard count < length else { return self }
let padLength = length - count
if padLength < token.count {
return self + token[token.startIndex..<token.index(token.startIndex, offsetBy: padLength)]
} else {
var padding = token
while padding.count < padLength {
padding.append(token)
}
return self + padding[padding.startIndex..<padding.index(padding.startIndex, offsetBy: padLength)]
}
}
/// **Mechanica**
///
/// Pads `self` on the right side if it's shorter than `length` using a `token`. Padding characters are truncated if they exceed length.
///
/// Example 1:
///
/// let string = "Hello World"
/// string.padEnd(length: 15) -> "Hello World "
///
/// Example 2:
///
/// let string = "Hello World"
/// string.padEnd(length: 15, withToken: "*", ) -> "Hello World****"
///
/// - Parameters:
/// - length: The final length of your string.
/// - token: The string used to pad the String (defaults to a white space).
public mutating func padEnd(length: Int, with token: String = " ") {
self = paddingEnd(length: length, with: token)
}
/// **Mechanica**
///
/// Returns a substring, up to maxLength in length, containing the initial elements of the `String`.
///
/// - Warning: If maxLength exceeds self.count, the result contains all the elements of self.
/// - parameter maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero.
///
public func prefix(maxLength: Int) -> String {
return String(prefix(maxLength))
}
/// **Mechanica**
///
/// Returns a new `String` containing the characters of the String from the one at a given position to the end.
///
/// Example:
///
/// "hello".droppingPrefix(upToPosition: 1) -> "ello"
/// "hello".droppingPrefix(upToPosition: 1) -> ""
///
/// - parameter upToPosition: position (included) up to which remove the prefix.
public func droppingPrefix(upToPosition: Int = 1) -> String {
guard upToPosition >= 0 && upToPosition <= length else { return "" }
return String(dropFirst(upToPosition))
}
/// **Mechanica**
///
/// Returns a new `String` removing the spcified prefix (if the string has it).
///
/// Example:
///
/// "hello".droppingPrefix("hel") -> "lo"
///
/// - parameter prefix: prefix to be removed.
public func droppingPrefix(_ prefix: String) -> String {
guard hasPrefix(prefix) else { return self }
return droppingPrefix(upToPosition: prefix.length)
}
/// **Mechanica**
///
/// Returns a new `String` containing the characters of the String up to, but not including, the one at a given position.
/// - parameter fromPosition: position (included) from which remove the suffix
///
/// Example:
///
/// "hello".droppingSuffix(fromPosition: 1) -> "hell"
/// "hello".droppingSuffix(fromPosition: 10) -> ""
///
public func droppingSuffix(fromPosition: Int = 1) -> String {
guard fromPosition >= 0 && fromPosition <= length else { return "" }
return String(dropLast(fromPosition))
}
/// **Mechanica**
///
/// Returns a new `String` removing the spcified suffix (if the string has it).
///
/// Example:
///
/// "hello".droppingSuffix("0") -> "hell"
///
/// - parameter prefix: prefix to be removed.
public func droppingSuffix(_ suffix: String) -> String {
guard hasSuffix(suffix) else { return self }
return droppingSuffix(fromPosition: suffix.length)
}
/// **Mechanica**
///
/// Reverse `self`.
public mutating func reverse() {
self = String(reversed())
}
/// **Mechanica**
///
/// Returns a slice, up to maxLength in length, containing the final elements of `String`.
///
/// - Warning: If maxLength exceeds `String` character count, the result contains all the elements of `String`.
/// - parameter maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero.
public func suffix(maxLength: Int) -> String {
return String(suffix(maxLength))
}
/// **Mechanica**
///
/// Truncates the `String` to the given length (number of characters) and appends optional trailing string if longer.
/// The default trailing is the ellipsis (…).
/// - parameter length: number of characters after which the `String` is truncated
/// - parameter trailing: optional trailing string
///
public func truncate(at length: Int, withTrailing trailing: String? = "…") -> String {
var truncated = self.prefix(maxLength: length)
if 0..<self.length ~= length {
if let trailing = trailing {
truncated.append(trailing)
}
}
return truncated
}
// MARK: - Subscript Methods
/// **Mechanica**
///
/// Gets the character at the specified index as String.
///
/// - parameter index: index Position of the character to get
///
/// - Returns: Character as String or nil if the index is out of bounds
///
/// Example:
///
/// let myString = "Hello world"
/// myString[0] -> "H"
/// myString[3] -> "l"
/// myString[10] -> "d"
/// myString[11] -> nil
/// myString[-1] -> nil
///
public subscript (index: Int) -> Character? {
guard 0..<count ~= index else { return nil }
return Array(self)[index]
}
/// **Mechanica**
///
/// Returns a substring for the given range.
///
/// - Parameter range: a `CountableRange` range.
///
/// Example:
///
/// let myString = "Hello world"
/// myString[0..<0] -> ""
/// myString[0..<1] -> "Hello worl"
/// myString[0..<10] -> "Hello world"
/// myString[0..<11] -> nil
/// myString[11..<14] -> nil
/// myString[-1..<11] -> nil
///
public subscript (range: CountableRange<Int>) -> Substring? {
guard 0...count ~= range.lowerBound else { return nil }
guard 0...count ~= range.upperBound else { return nil }
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(startIndex, offsetBy: range.upperBound)
return self[start..<end]
}
/// **Mechanica**
///
/// Returns a substring for the given range.
/// - Parameter range: a `CountableClosedRange` range.
///
/// Example:
///
/// let myString = "Hello world"
/// myString[0...0]
/// myString[0...1]
/// myString[0...10]
/// myString[0...11]
/// myString[11...14]
/// myString[-1...11]
///
public subscript (range: CountableClosedRange<Int>) -> Substring? {
guard 0..<count ~= range.lowerBound else { return nil }
guard 0..<count ~= range.upperBound else { return nil }
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(startIndex, offsetBy: range.upperBound)
return self[start...end]
}
/// **Mechanica**
///
/// Returns a substring for the given range.
/// - Parameter range: a `PartialRangeUpTo` range.
///
/// Example:
///
/// let myString = "Hello world"
/// myString[0...0] -> "H"
/// myString[0...1] -> "He"
/// myString[0...10] -> "Hello world"
/// myString[0...11] -> nil
/// myString[11...14] -> nil
/// myString[-1...11] -> nil
///
public subscript (range: PartialRangeUpTo<Int>) -> Substring? {
guard 0...count ~= range.upperBound else { return nil }
let end = index(startIndex, offsetBy: range.upperBound)
return self[..<end]
}
/// **Mechanica**
///
/// - Parameter range: a `PartialRangeThrough` range.
/// Example:
///
/// let myString = "Hello world"
/// myString[..<0] -> ""
/// myString[..<1] -> "H"
/// myString[..<10] -> "Hello worl"
/// myString[..<11] -> "Hello world"
/// myString[..<14] -> nil
/// myString[..<(-1)] -> nil
///
public subscript(range: PartialRangeThrough<Int>) -> Substring? {
guard 0..<count ~= range.upperBound else { return nil }
let end = index(startIndex, offsetBy: range.upperBound)
return self[...end]
}
/// **Mechanica**
///
/// Returns a substring for the given range.
/// - Parameter range: a `CountablePartialRangeFrom` range.
/// Example:
///
/// let myString = "Hello world"
/// myString[0...] -> "Hello world"
/// myString[1...] -> "ello world"
/// myString[10...] -> "d"
/// myString[11...] -> nil
/// myString[14...] -> nil
/// myString[(-1)...] -> nil
///
public subscript (range: CountablePartialRangeFrom<Int>) -> Substring? {
guard 0..<count ~= range.lowerBound else { return nil }
let start = index(startIndex, offsetBy: range.lowerBound)
return self[start...]
}
// MARK: - Operators
/// **Mechanica**
///
/// Returns a substring for the given range.
/// Creates a `new` string representing the given string repeated the specified number of times.
public static func * (lhs: String, rhs: Int) -> String {
return String(repeating: lhs, count: rhs)
}
/// **Mechanica**
///
/// Returns a substring for the given range.
/// Creates a `new` string representing the given string repeated the specified number of times.
public static func * (lhs: Int, rhs: String) -> String {
return String(repeating: rhs, count: lhs)
}
}
| mit |
bigL055/Routable | Sources/Routable+Configs.swift | 1 | 3084 | //
// Routable
//
// Copyright (c) 2017 linhay - https://github.com/linhay
//
// 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
import Foundation
// MARK: - configs apis
@objc(Routable_Configs)
public class Routable_Configs: NSObject {
var cache = ["*":Config.default]
/// 获取配置列表
///
/// - Returns: 配置列表
@objc public func list() -> [String: [String: String]] {
return cache.mapValues { (item) -> [String: String] in
return item.desc()
}
}
/// 获取配置列表
///
/// - Parameter scheme: url scheme
/// - Returns: 配置
@objc public func value(for scheme: String) -> [String: String]? {
return cache[scheme]?.desc()
}
/// 添加/替换 配置
///
/// - Parameters:
/// - scheme: url scheme
/// - classPrefix: 类名前缀
/// - funcPrefix: 函数名前缀
/// - paramName: 参数名
/// - remark: 备注
@objc public func set(scheme: String,
classPrefix: String,
funcPrefix: String,
remark:String) {
cache[scheme] = Config(scheme: scheme, classPrefix: classPrefix, funcPrefix: funcPrefix, remark: remark)
}
/// 移除多条指定配置
///
/// - Parameter schemes: url scheme
@objc public func remove(for schemes: [String]) -> [String: [String: String]] {
var dict = [String: [String: String]]()
schemes.forEach { (item) in
dict[item] = cache.removeValue(forKey: item)?.desc()
}
return dict
}
/// 重置为默认配置
///
/// - Returns: 默认配置
@objc public func reset() -> [String: [String: String]] {
cache = ["*": Config.default]
return ["*": Config.default.desc()]
}
}
extension Routable_Configs {
func value(url: URL) -> Config? {
guard let scheme = url.scheme else { return nil }
if let value = cache[scheme] {
return value
}else if let value = cache["*"] {
return value
}
return nil
}
func value(scheme: String) -> Config? {
return cache[scheme]
}
}
| mit |
benlangmuir/swift | test/decl/protocol/special/coding/struct_codable_member_name_confusion.swift | 4 | 619 | // RUN: %target-typecheck-verify-swift
// https://github.com/apple/swift/issues/52448
// Tests that, when synthesizing init(from:), we don't accidentally confuse
// static and instance properties with the same name.
// The test fails if this file produces errors.
struct X: Codable {
// The static property is a let with an initial value; Codable synthesis skips
// instance properties that look like this.
static let a: String = "a"
// The instance property has no initial value, so the definite initialization
// checker will reject an init(from:) that doesn't decode a value for it.
let a: String
}
| apache-2.0 |
semiroot/SwiftyConstraints | Tests/SC203BottomTests.swift | 1 | 4849 | //
// SC201Top.swift
// SwiftyConstraints
//
// Created by Hansmartin Geiser on 15/04/17.
// Copyright © 2017 Hansmartin Geiser. All rights reserved.
//
import XCTest
import Foundation
@testable import SwiftyConstraints
class SC203BottomTests: SCTest {
var subview1 = SCView()
var subview2 = SCView()
var superview: SCView?
var swiftyConstraints: SwiftyConstraints?
override func setUp() {
super.setUp()
superview = SCView()
swiftyConstraints = SwiftyConstraints(superview!)
}
override func tearDown() {
super.tearDown()
swiftyConstraints = nil
superview = nil
}
func test00Bottom() {
guard let swiftyConstraints = swiftyConstraints, let superview = superview else { XCTFail("Test setup failure"); return }
swiftyConstraints.attach(subview1)
swiftyConstraints.bottom()
guard let constraint1 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint1, produceConstraint(subview1, superview, .bottom, .bottom, .equal, 1, 0))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint1, .bottom)
swiftyConstraints.bottom(33.5)
guard let constraint2 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint2, produceConstraint(subview1, superview, .bottom, .bottom, .equal, 1, -33.5))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint2, .bottom)
}
func test01Above() {
guard let swiftyConstraints = swiftyConstraints, let superview = superview else { XCTFail("Test setup failure"); return }
swiftyConstraints
.attach(subview1)
.attach(subview2)
swiftyConstraints.above(subview1)
guard let constraint1 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint1, produceConstraint(subview2, subview1, .bottom, .top, .equal, 1, 0))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint1, .bottom)
swiftyConstraints.above(subview1, 15.5)
guard let constraint2 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint2, produceConstraint(subview2, subview1, .bottom, .top, .equal, 1, -15.5))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint2, .bottom)
// invalid reference
let view = SCView()
swiftyConstraints.above(view)
XCTAssertTrue(
superview.constraints.count == 0,
"Constraint should not have been created for inexistent reference"
)
XCTAssertEqual(
swiftyConstraints.previousErrors.last,
SCError.emptyReferenceView,
"Empty reference view did not cause error"
)
}
func test02Stacking() {
guard let swiftyConstraints = swiftyConstraints, let superview = superview else { XCTFail("Test setup failure"); return }
swiftyConstraints.attach(subview1).stackBottom()
XCTAssertTrue(
(try? swiftyConstraints.getCurrentContainer()) === swiftyConstraints.previousBottom,
"Stacking container did not get set"
)
swiftyConstraints.attach(subview2)
swiftyConstraints.bottom()
guard let constraint1 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint1, produceConstraint(subview2, subview1, .bottom, .top, .equal, 1, 0))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint1, .bottom)
swiftyConstraints.bottom(15.5)
guard let constraint2 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint2, produceConstraint(subview2, subview1, .bottom, .top, .equal, 1, -15.5))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint2, .bottom)
swiftyConstraints.resetStackBottom()
XCTAssertNil(
swiftyConstraints.previousBottom,
"Stacking container did not get reset"
)
swiftyConstraints.bottom()
guard let constraint3 = SCTAssertConstraintCreated(swiftyConstraints, .bottom) else { return }
SCTAssertConstraintMatching(constraint3, produceConstraint(subview2, superview, .bottom, .bottom, .equal, 1, 0))
swiftyConstraints.removeBottom()
SCTAssertConstraintRemoved(swiftyConstraints, constraint3, .bottom)
swiftyConstraints.removeBottom()
XCTAssertEqual(
swiftyConstraints.previousErrors.last,
SCError.emptyRemoveConstraint,
"Removing empty constraint did not cause error"
)
}
}
| mit |
jkereako/MassStateKeno | Sources/Views/DrawingTableViewController.swift | 1 | 2324 | //
// DrawingTableViewController.swift
// MassLotteryKeno
//
// Created by Jeff Kereakoglow on 5/19/19.
// Copyright © 2019 Alexis Digital. All rights reserved.
//
import UIKit
protocol DrawingTableViewControllerDelegate: class {
func didPullToRefresh(tableViewController: DrawingTableViewController, refreshControl: UIRefreshControl)
}
final class DrawingTableViewController: UITableViewController {
weak var delegate: DrawingTableViewControllerDelegate?
var viewModel: DrawingTableViewModel? {
didSet {
title = viewModel?.title
tableView?.refreshControl?.endRefreshing()
tableView.dataSource = viewModel
tableView.delegate = viewModel
tableView.reloadData()
}
}
init() {
super.init(style: .grouped)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(
nibName: cellReuseIdentifier, bundle: Bundle(for: DrawingTableViewCell.self)
)
refreshControl = UIRefreshControl()
refreshControl?.addTarget(
viewModel,
action: #selector(refreshAction),
for: .valueChanged
)
tableView.register(nib, forCellReuseIdentifier: cellReuseIdentifier)
tableView.backgroundColor = UIColor(named: "DarkBlue")
tableView.separatorStyle = .none
}
}
// MARK: - DrawingTableViewModelDataSource
extension DrawingTableViewController: DrawingTableViewModelDataSource {
var cellReuseIdentifier: String {
return "DrawingTableViewCell"
}
func configure(_ cell: UITableViewCell, with drawingViewModel: DrawingViewModel) -> UITableViewCell {
guard let drawingTableViewCell = cell as? DrawingTableViewCell else {
assertionFailure("Expected a DrawingTableViewCell")
return UITableViewCell()
}
drawingTableViewCell.viewModel = drawingViewModel
return drawingTableViewCell
}
}
// MARK: - Target-actions
extension DrawingTableViewController {
@objc func refreshAction(sender: Any) {
delegate?.didPullToRefresh(
tableViewController: self, refreshControl: tableView.refreshControl!
)
}
}
| mit |
onmyway133/Github.swift | GithubSwiftTests/Classes/FormatterSpec.swift | 1 | 1751 | //
// FormatterSpec.swift
// GithubSwift
//
// Created by Khoa Pham on 03/04/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
import GithubSwift
import Quick
import Nimble
import Mockingjay
import RxSwift
import Sugar
class FormatterSpec: QuickSpec {
override func spec() {
describe("formatter") {
var calendar: NSCalendar!
beforeEach {
calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
calendar.locale = NSLocale(localeIdentifier: "en_US_POSIX")
calendar.timeZone = NSTimeZone(abbreviation: "UTC")!
}
it("should parse an ISO 8601 string into a date and back") {
let string = "2011-01-26T19:06:43Z"
let components = NSDateComponents().then {
$0.day = 26;
$0.month = 1;
$0.year = 2011;
$0.hour = 19;
$0.minute = 6;
$0.second = 43;
}
let date = Formatter.date(string: string)
expect(date).toNot(beNil())
expect(date).to(equal(calendar.dateFromComponents(components)))
expect(Formatter.string(date: date!)).to(equal(string))
}
it("shouldn't use ISO week-numbering year") {
let string = "2012-01-01T00:00:00Z"
let components = NSDateComponents().then {
$0.day = 1;
$0.month = 1;
$0.year = 2012;
$0.hour = 0;
$0.minute = 0;
$0.second = 0;
}
let date = Formatter.date(string: string)
expect(date).toNot(beNil())
expect(date).to(equal(calendar.dateFromComponents(components)))
expect(Formatter.string(date: date!)).to(equal(string))
}
}
}
}
| mit |
y-hryk/Architectures-iOS | ArchitecturesDemo/AppDelegate.swift | 1 | 2693 | //
// AppDelegate.swift
// ArchitecturesDemo
//
// Created by h.yamaguchi on 2016/12/28.
// Copyright © 2016年 h.yamaguchi. 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.
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.black
UINavigationBar.appearance().barTintColor = UIColor.baseColor()
UIApplication.shared.setStatusBarStyle(.lightContent, animated: false)
let vc = SwitchVC.mainController()
let navi = UINavigationController(rootViewController: vc)
self.window?.rootViewController = navi
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
Zewo/Log | Source/Appender.swift | 1 | 1313 | // Appender.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
public protocol Appender {
var name: String { get }
var closed: Bool { get }
var level: Log.Level { get }
func append (_ event: LoggingEvent)
}
| mit |
genadyo/Lyft | Lyft/Classes/LyftOAuth.swift | 1 | 2669 | //
// LyftOAuth.swift
// SFParties
//
// Created by Genady Okrain on 5/11/16.
// Copyright © 2016 Okrain. All rights reserved.
//
import Foundation
public extension Lyft {
// Initialize clientId & clientSecret
static func set(clientId: String, clientSecret: String, sandbox: Bool? = nil) {
sharedInstance.clientId = clientId
sharedInstance.clientSecret = clientSecret
sharedInstance.sandbox = sandbox ?? false
}
// 3-Legged flow for accessing user-specific endpoints
static func userLogin(scope: String, state: String = "", completionHandler: ((_ success: Bool, _ error: NSError?) -> ())?) {
guard let clientId = sharedInstance.clientId, let _ = sharedInstance.clientSecret else { return }
let string = "\(lyftAPIOAuthURL)/authorize?client_id=\(clientId)&response_type=code&scope=\(scope)&state=\(state)"
sharedInstance.completionHandler = completionHandler
if let url = URL(string: string.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!) {
UIApplication.shared.openURL(url)
}
}
// Client Credentials (2-legged) flow for public endpoints
static func publicLogin(_ completionHandler: ((_ success: Bool, _ error: NSError?) -> ())?) {
guard let _ = sharedInstance.clientId, let _ = sharedInstance.clientSecret else { return }
sharedInstance.completionHandler = completionHandler
fetchAccessToken(nil)
}
// Refreshing the access token
static func refreshToken(_ completionHandler: ((_ success: Bool, _ error: NSError?) -> ())?) {
guard let _ = sharedInstance.clientId, let _ = sharedInstance.clientSecret else { return }
sharedInstance.completionHandler = completionHandler
fetchAccessToken(nil, refresh: true)
}
// Revoking the access token
static func revokeToken(_ completionHandler: ((_ success: Bool, _ error: NSError?) -> ())?) {
guard let _ = sharedInstance.clientId, let _ = sharedInstance.clientSecret else { return }
sharedInstance.completionHandler = completionHandler
fetchAccessToken(nil, refresh: false, revoke: true)
}
// func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool
static func openURL(_ url: URL) -> Bool {
guard let _ = sharedInstance.clientId, let _ = sharedInstance.clientSecret else { return false }
guard let code = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.filter({ $0.name == "code" }).first?.value else { return false }
fetchAccessToken(code)
return true
}
}
| mit |
slavapestov/swift | validation-test/compiler_crashers_fixed/28149-addcurriedselftype.swift | 4 | 291 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<I{let a=Void{struct A:OptionSetType{
let rawValue=0
let rawValue=0
| apache-2.0 |
andrebocchini/SwiftChattyOSX | Pods/SwiftChatty/SwiftChatty/Requests/Notifications/DetachAccountRequest.swift | 1 | 629 | //
// DetachAccountRequest.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/28/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.
//
import Alamofire
/// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451708
public struct DetachAccountRequest: Request {
public let endpoint: ApiEndpoint = .DetachAccount
public let httpMethod: Alamofire.Method = .POST
public let account: Account
public var parameters: [String : AnyObject] = [:]
public init(withClientId clientId: String, account: Account) {
self.account = account
self.parameters["clientId"] = clientId
}
}
| mit |
nathan-hekman/Chill | Chill/Chill WatchKit Extension/InterfaceController.swift | 1 | 17218 | //
// InterfaceController.swift
// Chill WatchKit Extension
//
// Created by Nathan Hekman on 12/7/15.
// Copyright © 2015 NTH. All rights reserved.
//
import Foundation
import HealthKit
import WatchKit
import WatchConnectivity
class InterfaceController: WKInterfaceController {
@IBOutlet var resultGroup: WKInterfaceGroup!
@IBOutlet var chillResultLabel: WKInterfaceLabel!
@IBOutlet private weak var label: WKInterfaceLabel!
@IBOutlet private weak var heart: WKInterfaceImage!
@IBOutlet private weak var startStopButton : WKInterfaceButton!
@IBOutlet var pleaseWaitLabel: WKInterfaceLabel!
//State of the app - is the workout activated
var workoutActive = false
// define the activity type and location
var workoutSession : HKWorkoutSession?
let heartRateUnit = HKUnit(fromString: "count/min")
var anchor = HKQueryAnchor(fromValue: Int(HKAnchoredObjectQueryNoAnchor))
var hasShownAlert = false
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
tellPhoneWatchIsAwake()
//setupTargetLabel()
}
override func willActivate() {
super.willActivate()
setupWCSession()
setupHeartRateData()
tellPhoneWatchIsAwake()
//setupTargetLabel()
}
override func willDisappear() {
}
override func didAppear() {
tellPhoneWatchIsAwake()
//setupHeartRateData()
//showPopup()
//setupTargetLabel()
}
func setupHeartRateData() {
guard HKHealthStore.isHealthDataAvailable() == true else {
self.displayNotAllowed()
return
}
if let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) {
let dataTypes = Set(arrayLiteral: quantityType)
let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
if let healthStore = HealthKitManager.sharedInstance.healthStore {
let status = healthStore.authorizationStatusForType(quantityType!)
switch status {
case .SharingAuthorized:
Utils.updateUserDefaultsHasRespondedToHealthKit(1) //update has responded now at this point
dispatch_async(dispatch_get_main_queue()) {
self.startStopButton.setEnabled(true)
self.pleaseWaitLabel.setText("Measuring...")
self.pleaseWaitLabel.setHidden(true)
//self.chillResultLabel.setText("---")
}
case .SharingDenied:
Utils.updateUserDefaultsHasRespondedToHealthKit(0) //update has responded now at this point
dispatch_async(dispatch_get_main_queue()) {
self.startStopButton.setEnabled(false)
self.pleaseWaitLabel.setText("Open Health app to accept access")
self.pleaseWaitLabel.setHidden(false)
if (self.hasShownAlert == false) {
self.tryToShowPopup("\"Chill\" needs permission to access heart rate data and save heart rate data to the Health app in order to check your heart rate and Chill status. Check the Health app to accept. See the iPhone app for privacy information.")
} else { //if true, then set to false so it shows next time
self.hasShownAlert = false
}
}
//}
case .NotDetermined:
dispatch_async(dispatch_get_main_queue()) {
self.startStopButton.setEnabled(false)
//self.chillResultLabel.setText("Open on iPhone or Health app to accept access")
self.pleaseWaitLabel.setText("Open Health app to accept access")
self.pleaseWaitLabel.setHidden(false)
}
if (self.hasShownAlert == false) {
healthStore.requestAuthorizationToShareTypes(dataTypes, readTypes: dataTypes) { (success, error) -> Void in
if success == false {
self.displayNotAllowed()
Utils.updateUserDefaultsHasRespondedToHealthKit(0)
}
else if success == true {
self.setupHeartRateData()
Utils.updateUserDefaultsHasRespondedToHealthKit(1) //update has responded now at this point
}
}
}
else { //if true, then set to false so it shows next time
self.hasShownAlert = false
}
}
}
} else {
self.displayNotAllowed()
return
}
}
func tryToShowPopup(text: String!){
//if (Utils.retrieveHasRespondedToHealthKitFromUserDefaults() == nil) { //show alert if hasn't seen before or failed
let h0 = {
print("OK tapped")
//finish the current workout
// self.stopLoadingAnimation()
// self.resetScreen()
}
let action1 = WKAlertAction(title: "Got it", style: .Default, handler:h0)
dispatch_async(dispatch_get_main_queue()) {
self.presentAlertControllerWithTitle("Health Access", message: text, preferredStyle: .Alert, actions: [action1])
self.hasShownAlert = true
}
//}
}
func setupWCSession() {
WatchSessionManager.sharedInstance.startSession()
WatchSessionManager.sharedInstance.interfaceController = self //save copy of self in session manager
}
func displayNotAllowed() {
dispatch_async(dispatch_get_main_queue()) {
self.label.setText("use actual device")
}
}
func workoutDidStart(date : NSDate) {
dispatch_async(dispatch_get_main_queue()) {
if let query = self.createHeartRateStreamingQuery(date) {
if let healthStore = HealthKitManager.sharedInstance.healthStore {
healthStore.executeQuery(query)
}
} else {
self.label.setText("cannot start")
}
}
}
func workoutDidEnd(date : NSDate) {
dispatch_async(dispatch_get_main_queue()) {
if let query = self.createHeartRateStreamingQuery(date) {
if let healthStore = HealthKitManager.sharedInstance.healthStore {
healthStore.stopQuery(query)
self.stopLoadingAnimation()
self.stopWorkout()
self.resetScreen()
}
} else {
self.label.setText("cannot stop")
}
}
}
// MARK: - Actions
@IBAction func startBtnTapped() {
dispatch_async(dispatch_get_main_queue()) {
self.setupHeartRateData()
if (self.workoutActive) {
//finish the current workout
self.stopLoadingAnimation()
self.stopWorkout()
self.resetScreen()
} else {
//start a new workout
dispatch_async(dispatch_get_main_queue()) {
//self.setupTargetLabel()
self.startLoadingAnimation()
self.workoutActive = true
self.startStopButton.setTitle("Cancel")
self.label.setText("--")
self.chillResultLabel.setText("---")
self.startWorkout()
}
}
}
}
func startLoadingAnimation() {
// 1
let duration = 1.0
// 2
resultGroup.setBackgroundImageNamed("Loader")
// 3
dispatch_async(dispatch_get_main_queue()) {
self.pleaseWaitLabel.setText("Measuring...")
self.pleaseWaitLabel.setHidden(false)
self.chillResultLabel.setHidden(true)
self.resultGroup.startAnimatingWithImagesInRange(NSRange(location: 0, length: 97), duration: duration, repeatCount: 0)
}
}
func stopLoadingAnimation() {
//stop loading animation
dispatch_async(dispatch_get_main_queue()) {
self.pleaseWaitLabel.setText("Measuring...")
self.pleaseWaitLabel.setHidden(true)
self.chillResultLabel.setHidden(false)
self.resultGroup.setBackgroundImage(nil)
self.resultGroup.stopAnimating()
}
}
func tellPhoneWatchIsAwake() {
//if let _ = WatchSessionManager.sharedInstance.validReachableSession {
let messageToSend = ["Awake":"I'm awake, iPhone!"]
WatchSessionManager.sharedInstance.sendMessage(messageToSend, replyHandler: { replyMessage in
//handle and present the message on screen
if let value = replyMessage["Awake"] as? String {
print("Message received back from iPhone: \(value)")
}
else {
print("No message received back from iPhone!")
}
}, errorHandler: {error in
// catch any errors here
print(error)
})
//}
}
func stopWorkout() {
if let workout = self.workoutSession {
if let healthStore = HealthKitManager.sharedInstance.healthStore {
healthStore.endWorkoutSession(workout)
}
self.workoutSession = nil
}
}
func startWorkout() {
self.workoutSession = HKWorkoutSession(activityType: HKWorkoutActivityType.CrossTraining, locationType: HKWorkoutSessionLocationType.Indoor)
self.workoutSession?.delegate = self
if let healthStore = HealthKitManager.sharedInstance.healthStore {
healthStore.startWorkoutSession(self.workoutSession!)
}
}
func createHeartRateStreamingQuery(workoutStartDate: NSDate) -> HKQuery? {
// adding predicate will not work
// let predicate = HKQuery.predicateForSamplesWithStartDate(workoutStartDate, endDate: nil, options: HKQueryOptions.None)
guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return nil }
let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
guard let newAnchor = newAnchor else {
return
}
self.anchor = newAnchor
self.updateHeartRate(sampleObjects)
}
heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in
if (self.workoutActive == true) { //check if stop button has been pressed
self.anchor = newAnchor! //these two lines will continue measuring if uncommented
self.updateHeartRate(samples)
}
else {
}
}
return heartRateQuery
}
func sendHeartRateValueToPhone(heartRate: String!, isChill: String!) { //heart rate as a string, is chill boolean as "T" or "F" string for true or false
WatchSessionManager.sharedInstance.lastHeartRateString = heartRate
let messageToSend = ["HR":"\(isChill):\(heartRate)"]
//if let _ = WatchSessionManager.sharedInstance.validReachableSession {
do {
try WatchSessionManager.sharedInstance.updateApplicationContext(messageToSend)
}
catch {
print("couldn't update application context!!")
}
//}
}
func updateHeartRate(samples: [HKSample]?) {
guard let heartRateSamples = samples as? [HKQuantitySample] else {return}
guard let sample = heartRateSamples.first else{return}
let value = sample.quantity.doubleValueForUnit(self.heartRateUnit)
let heartRateInt = UInt16(value)
let heartRateString = String(heartRateInt)
let chill = userIsChill(heartRateInt)
if (self.workoutActive == true) {
//finish the current workout after 1 measurement
self.workoutActive = false
self.stopLoadingAnimation()
//show result on UI
dispatch_async(dispatch_get_main_queue()) {
//vibrate watch too
WKInterfaceDevice().playHaptic(.Notification)
self.animateHeart()
self.label.setText(heartRateString)
if (chill == true) { //user is chill
self.chillResultLabel.setText("You're Chill.")
self.chillResultLabel.setVerticalAlignment(WKInterfaceObjectVerticalAlignment.Center)
self.chillResultLabel.setHorizontalAlignment(WKInterfaceObjectHorizontalAlignment.Center)
//send latest HR value to phone
self.sendHeartRateValueToPhone(heartRateString, isChill:"T")
}
else { //user is not chill
self.chillResultLabel.setText("You should Chill.")
self.chillResultLabel.setVerticalAlignment(WKInterfaceObjectVerticalAlignment.Center)
self.chillResultLabel.setHorizontalAlignment(WKInterfaceObjectHorizontalAlignment.Center)
//send latest HR value to phone
self.sendHeartRateValueToPhone(heartRateString, isChill:"F")
}
self.stopWorkout()
self.resetScreen()
//var _ = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "resetScreen", userInfo: nil, repeats: false)
}
}
}
func resetScreen() {
dispatch_async(dispatch_get_main_queue()) {
self.workoutActive = false
self.startStopButton.setTitle("Measure")
// self.label.setText("--")
// self.chillResultLabel.setText("---")
}
}
func userIsChill(heartRate: UInt16!) -> Bool! {
//user is not "Chill" if heartrate is above 76 bpm. According to: http://www.webmd.com/heart-disease/features/5-heart-rate-myths-debunked
//"Recent studies suggest a heart rate higher than 76 beats per minute when you're resting may be linked to a higher risk of heart attack."
let heartRateTarget = UInt16(WatchSessionManager.sharedInstance.targetHeartRateString)
if (heartRate > heartRateTarget) {
return false
}
else {
return true
}
}
func animateHeart() {
self.animateWithDuration(0.5) {
self.heart.setWidth(30)
self.heart.setHeight(30)
}
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * double_t(NSEC_PER_SEC)))
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_after(when, queue) {
dispatch_async(dispatch_get_main_queue(), {
self.animateWithDuration(0.5, animations: {
self.heart.setWidth(23)
self.heart.setHeight(23)
})
})
}
}
}
extension InterfaceController: HKWorkoutSessionDelegate {
func workoutSession(workoutSession: HKWorkoutSession, didChangeToState toState: HKWorkoutSessionState, fromState: HKWorkoutSessionState, date: NSDate) {
switch toState {
case .Running:
workoutDidStart(date)
case .Ended:
workoutDidEnd(date)
default:
//workoutDidEnd(date)
print("Unexpected state \(toState)")
}
}
func workoutSession(workoutSession: HKWorkoutSession, didFailWithError error: NSError) {
// Do nothing for now
NSLog("Workout error: \(error.userInfo)")
stopLoadingAnimation()
self.stopWorkout()
resetScreen()
}
}
extension InterfaceController: WCSessionDelegate {
} | mit |
vsqweHCL/DouYuZB | DouYuZB/DouYuZB/Classs/Room/Controller/RoomNormalViewController.swift | 1 | 979 | //
// RoomNormalViewController.swift
// DouYuZB
//
// Created by HCL黄 on 2016/12/25.
// Copyright © 2016年 HCL黄. All rights reserved.
//
import UIKit
class RoomNormalViewController: UIViewController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.orange
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 隐藏导航栏
navigationController?.setNavigationBarHidden(true, animated: true)
//
// // 依然保持手势
// navigationController?.interactivePopGestureRecognizer?.delegate = self
// navigationController?.interactivePopGestureRecognizer?.isEnabled = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
}
| mit |
trvslhlt/CalcLater | CalcLater/AppDelegate.swift | 1 | 640 | //
// AppDelegate.swift
// CalcLater
//
// Created by trvslhlt on 10/26/15.
// Copyright © 2015 travis holt. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.makeKeyAndVisible()
window?.rootViewController = CalcLaterViewController()
window?.backgroundColor = UIColor.whiteColor()
return true
}
}
| mit |
michael-lehew/swift-corelibs-foundation | Foundation/NSURLSession/NSURLSessionTask.swift | 1 | 52949 | // Foundation/NSURLSession/NSURLSessionTask.swift - NSURLSession API
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// URLSession API code.
/// - SeeAlso: NSURLSession.swift
///
// -----------------------------------------------------------------------------
import CoreFoundation
import Dispatch
/// A cancelable object that refers to the lifetime
/// of processing a given request.
open class URLSessionTask : NSObject, NSCopying {
/// How many times the task has been suspended, 0 indicating a running task.
fileprivate var suspendCount = 1
fileprivate var easyHandle: _EasyHandle!
fileprivate var totalDownloaded = 0
fileprivate var session: URLSessionProtocol! //change to nil when task completes
fileprivate let body: _Body
fileprivate let tempFileURL: URL
/// The internal state that the task is in.
///
/// Setting this value will also add / remove the easy handle.
/// It is independt of the `state: URLSessionTask.State`. The
/// `internalState` tracks the state of transfers / waiting for callbacks.
/// The `state` tracks the overall state of the task (running vs.
/// completed).
/// - SeeAlso: URLSessionTask._InternalState
fileprivate var internalState = _InternalState.initial {
// We manage adding / removing the easy handle and pausing / unpausing
// here at a centralized place to make sure the internal state always
// matches up with the state of the easy handle being added and paused.
willSet {
if !internalState.isEasyHandlePaused && newValue.isEasyHandlePaused {
fatalError("Need to solve pausing receive.")
}
if internalState.isEasyHandleAddedToMultiHandle && !newValue.isEasyHandleAddedToMultiHandle {
session.remove(handle: easyHandle)
}
}
didSet {
if !oldValue.isEasyHandleAddedToMultiHandle && internalState.isEasyHandleAddedToMultiHandle {
session.add(handle: easyHandle)
}
if oldValue.isEasyHandlePaused && !internalState.isEasyHandlePaused {
fatalError("Need to solve pausing receive.")
}
if case .taskCompleted = internalState {
updateTaskState()
guard let s = session as? URLSession else { fatalError() }
s.workQueue.async {
s.taskRegistry.remove(self)
}
}
}
}
/// All operations must run on this queue.
fileprivate let workQueue: DispatchQueue
/// This queue is used to make public attributes thread safe. It's a
/// **concurrent** queue and must be used with a barries when writing. This
/// allows multiple concurrent readers or a single writer.
fileprivate let taskAttributesIsolation: DispatchQueue
public override init() {
// Darwin Foundation oddly allows calling this initializer, even though
// such a task is quite broken -- it doesn't have a session. And calling
// e.g. `taskIdentifier` will crash.
//
// We set up the bare minimum for init to work, but don't care too much
// about things crashing later.
session = _MissingURLSession()
taskIdentifier = 0
originalRequest = nil
body = .none
workQueue = DispatchQueue(label: "URLSessionTask.notused.0")
taskAttributesIsolation = DispatchQueue(label: "URLSessionTask.notused.1")
let fileName = NSTemporaryDirectory() + NSUUID().uuidString + ".tmp"
_ = FileManager.default.createFile(atPath: fileName, contents: nil)
self.tempFileURL = URL(fileURLWithPath: fileName)
super.init()
}
/// Create a data task. If there is a httpBody in the URLRequest, use that as a parameter
internal convenience init(session: URLSession, request: URLRequest, taskIdentifier: Int) {
if let bodyData = request.httpBody {
self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: _Body.data(createDispatchData(bodyData)))
} else {
self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: .none)
}
}
internal init(session: URLSession, request: URLRequest, taskIdentifier: Int, body: _Body) {
self.session = session
self.workQueue = session.workQueue
self.taskAttributesIsolation = session.taskAttributesIsolation
self.taskIdentifier = taskIdentifier
self.originalRequest = request
self.body = body
let fileName = NSTemporaryDirectory() + NSUUID().uuidString + ".tmp"
_ = FileManager.default.createFile(atPath: fileName, contents: nil)
self.tempFileURL = URL(fileURLWithPath: fileName)
super.init()
self.easyHandle = _EasyHandle(delegate: self)
}
deinit {
//TODO: Can we ensure this somewhere else? This might run on the wrong
// thread / queue.
//if internalState.isEasyHandleAddedToMultiHandle {
// session.removeHandle(easyHandle)
//}
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone?) -> Any {
NSUnimplemented()
}
/// An identifier for this task, assigned by and unique to the owning session
open let taskIdentifier: Int
/// May be nil if this is a stream task
/*@NSCopying*/ open let originalRequest: URLRequest?
/// May differ from originalRequest due to http server redirection
/*@NSCopying*/ open fileprivate(set) var currentRequest: URLRequest? {
get {
var r: URLRequest? = nil
taskAttributesIsolation.sync { r = self._currentRequest }
return r
}
//TODO: dispatch_barrier_async
set { taskAttributesIsolation.async { self._currentRequest = newValue } }
}
fileprivate var _currentRequest: URLRequest? = nil
/*@NSCopying*/ open fileprivate(set) var response: URLResponse? {
get {
var r: URLResponse? = nil
taskAttributesIsolation.sync { r = self._response }
return r
}
set { taskAttributesIsolation.async { self._response = newValue } }
}
fileprivate var _response: URLResponse? = nil
/* Byte count properties may be zero if no body is expected,
* or URLSessionTransferSizeUnknown if it is not possible
* to know how many bytes will be transferred.
*/
/// Number of body bytes already received
open fileprivate(set) var countOfBytesReceived: Int64 {
get {
var r: Int64 = 0
taskAttributesIsolation.sync { r = self._countOfBytesReceived }
return r
}
set { taskAttributesIsolation.async { self._countOfBytesReceived = newValue } }
}
fileprivate var _countOfBytesReceived: Int64 = 0
/// Number of body bytes already sent */
open fileprivate(set) var countOfBytesSent: Int64 {
get {
var r: Int64 = 0
taskAttributesIsolation.sync { r = self._countOfBytesSent }
return r
}
set { taskAttributesIsolation.async { self._countOfBytesSent = newValue } }
}
fileprivate var _countOfBytesSent: Int64 = 0
/// Number of body bytes we expect to send, derived from the Content-Length of the HTTP request */
open fileprivate(set) var countOfBytesExpectedToSend: Int64 = 0
/// Number of byte bytes we expect to receive, usually derived from the Content-Length header of an HTTP response. */
open fileprivate(set) var countOfBytesExpectedToReceive: Int64 = 0
/// The taskDescription property is available for the developer to
/// provide a descriptive label for the task.
open var taskDescription: String?
/* -cancel returns immediately, but marks a task as being canceled.
* The task will signal -URLSession:task:didCompleteWithError: with an
* error value of { NSURLErrorDomain, NSURLErrorCancelled }. In some
* cases, the task may signal other work before it acknowledges the
* cancelation. -cancel may be sent to a task that has been suspended.
*/
open func cancel() { NSUnimplemented() }
/*
* The current state of the task within the session.
*/
open var state: URLSessionTask.State {
get {
var r: URLSessionTask.State = .suspended
taskAttributesIsolation.sync { r = self._state }
return r
}
set { taskAttributesIsolation.async { self._state = newValue } }
}
fileprivate var _state: URLSessionTask.State = .suspended
/*
* The error, if any, delivered via -URLSession:task:didCompleteWithError:
* This property will be nil in the event that no error occured.
*/
/*@NSCopying*/ open var error: NSError? { NSUnimplemented() }
/// Suspend the task.
///
/// Suspending a task will prevent the URLSession from continuing to
/// load data. There may still be delegate calls made on behalf of
/// this task (for instance, to report data received while suspending)
/// but no further transmissions will be made on behalf of the task
/// until -resume is sent. The timeout timer associated with the task
/// will be disabled while a task is suspended. -suspend and -resume are
/// nestable.
open func suspend() {
// suspend / resume is implemented simply by adding / removing the task's
// easy handle fromt he session's multi-handle.
//
// This might result in slightly different behaviour than the Darwin Foundation
// implementation, but it'll be difficult to get complete parity anyhow.
// Too many things depend on timeout on the wire etc.
//
// TODO: It may be worth looking into starting over a task that gets
// resumed. The Darwin Foundation documentation states that that's what
// it does for anything but download tasks.
// We perform the increment and call to `updateTaskState()`
// synchronous, to make sure the `state` is updated when this method
// returns, but the actual suspend will be done asynchronous to avoid
// dead-locks.
workQueue.sync {
self.suspendCount += 1
guard self.suspendCount < Int.max else { fatalError("Task suspended too many times \(Int.max).") }
self.updateTaskState()
if self.suspendCount == 1 {
self.workQueue.async {
self.performSuspend()
}
}
}
}
/// Resume the task.
///
/// - SeeAlso: `suspend()`
open func resume() {
workQueue.sync {
self.suspendCount -= 1
guard 0 <= self.suspendCount else { fatalError("Resuming a task that's not suspended. Calls to resume() / suspend() need to be matched.") }
self.updateTaskState()
if self.suspendCount == 0 {
self.workQueue.async {
self.performResume()
}
}
}
}
/// The priority of the task.
///
/// Sets a scaling factor for the priority of the task. The scaling factor is a
/// value between 0.0 and 1.0 (inclusive), where 0.0 is considered the lowest
/// priority and 1.0 is considered the highest.
///
/// The priority is a hint and not a hard requirement of task performance. The
/// priority of a task may be changed using this API at any time, but not all
/// protocols support this; in these cases, the last priority that took effect
/// will be used.
///
/// If no priority is specified, the task will operate with the default priority
/// as defined by the constant URLSessionTaskPriorityDefault. Two additional
/// priority levels are provided: URLSessionTaskPriorityLow and
/// URLSessionTaskPriorityHigh, but use is not restricted to these.
open var priority: Float {
get {
var r: Float = 0
taskAttributesIsolation.sync { r = self._priority }
return r
}
set {
taskAttributesIsolation.async { self._priority = newValue }
}
}
fileprivate var _priority: Float = URLSessionTaskPriorityDefault
}
extension URLSessionTask {
public enum State : Int {
/// The task is currently being serviced by the session
case running
case suspended
/// The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError: message.
case canceling
/// The task has completed and the session will receive no more delegate notifications
case completed
}
}
fileprivate extension URLSessionTask {
/// The calls to `suspend` can be nested. This one is only called when the
/// task is not suspended and needs to go into suspended state.
func performSuspend() {
if case .transferInProgress(let transferState) = internalState {
internalState = .transferReady(transferState)
}
}
/// The calls to `resume` can be nested. This one is only called when the
/// task is suspended and needs to go out of suspended state.
func performResume() {
if case .initial = internalState {
guard let r = originalRequest else { fatalError("Task has no original request.") }
startNewTransfer(with: r)
}
if case .transferReady(let transferState) = internalState {
internalState = .transferInProgress(transferState)
}
}
}
internal extension URLSessionTask {
/// The is independent of the public `state: URLSessionTask.State`.
enum _InternalState {
/// Task has been created, but nothing has been done, yet
case initial
/// The easy handle has been fully configured. But it is not added to
/// the multi handle.
case transferReady(_TransferState)
/// The easy handle is currently added to the multi handle
case transferInProgress(_TransferState)
/// The transfer completed.
///
/// The easy handle has been removed from the multi handle. This does
/// not (necessarily mean the task completed. A task that gets
/// redirected will do multiple transfers.
case transferCompleted(response: HTTPURLResponse, bodyDataDrain: _TransferState._DataDrain)
/// The transfer failed.
///
/// Same as `.transferCompleted`, but without response / body data
case transferFailed
/// Waiting for the completion handler of the HTTP redirect callback.
///
/// When we tell the delegate that we're about to perform an HTTP
/// redirect, we need to wait for the delegate to let us know what
/// action to take.
case waitingForRedirectCompletionHandler(response: HTTPURLResponse, bodyDataDrain: _TransferState._DataDrain)
/// Waiting for the completion handler of the 'did receive response' callback.
///
/// When we tell the delegate that we received a response (i.e. when
/// we received a complete header), we need to wait for the delegate to
/// let us know what action to take. In this state the easy handle is
/// paused in order to suspend delegate callbacks.
case waitingForResponseCompletionHandler(_TransferState)
/// The task is completed
///
/// Contrast this with `.transferCompleted`.
case taskCompleted
}
}
fileprivate extension URLSessionTask._InternalState {
var isEasyHandleAddedToMultiHandle: Bool {
switch self {
case .initial: return false
case .transferReady: return false
case .transferInProgress: return true
case .transferCompleted: return false
case .transferFailed: return false
case .waitingForRedirectCompletionHandler: return false
case .waitingForResponseCompletionHandler: return true
case .taskCompleted: return false
}
}
var isEasyHandlePaused: Bool {
switch self {
case .initial: return false
case .transferReady: return false
case .transferInProgress: return false
case .transferCompleted: return false
case .transferFailed: return false
case .waitingForRedirectCompletionHandler: return false
case .waitingForResponseCompletionHandler: return true
case .taskCompleted: return false
}
}
}
internal extension URLSessionTask {
/// Updates the (public) state based on private / internal state.
///
/// - Note: This must be called on the `workQueue`.
fileprivate func updateTaskState() {
func calculateState() -> URLSessionTask.State {
if case .taskCompleted = internalState {
return .completed
}
if suspendCount == 0 {
return .running
} else {
return .suspended
}
}
state = calculateState()
}
}
internal extension URLSessionTask {
enum _Body {
case none
case data(DispatchData)
/// Body data is read from the given file URL
case file(URL)
case stream(InputStream)
}
}
fileprivate extension URLSessionTask._Body {
enum _Error : Error {
case fileForBodyDataNotFound
}
/// - Returns: The body length, or `nil` for no body (e.g. `GET` request).
func getBodyLength() throws -> UInt64? {
switch self {
case .none:
return 0
case .data(let d):
return UInt64(d.count)
/// Body data is read from the given file URL
case .file(let fileURL):
guard let s = try FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? NSNumber else {
throw _Error.fileForBodyDataNotFound
}
return s.uint64Value
case .stream:
return nil
}
}
}
/// Easy handle related
fileprivate extension URLSessionTask {
/// Start a new transfer
func startNewTransfer(with request: URLRequest) {
currentRequest = request
guard let url = request.url else { fatalError("No URL in request.") }
internalState = .transferReady(createTransferState(url: url))
configureEasyHandle(for: request)
if suspendCount < 1 {
performResume()
}
}
/// Creates a new transfer state with the given behaviour:
func createTransferState(url: URL) -> URLSessionTask._TransferState {
let drain = createTransferBodyDataDrain()
switch body {
case .none:
return URLSessionTask._TransferState(url: url, bodyDataDrain: drain)
case .data(let data):
let source = _HTTPBodyDataSource(data: data)
return URLSessionTask._TransferState(url: url, bodyDataDrain: drain, bodySource: source)
case .file(let fileURL):
let source = _HTTPBodyFileSource(fileURL: fileURL, workQueue: workQueue, dataAvailableHandler: { [weak self] in
// Unpause the easy handle
self?.easyHandle.unpauseSend()
})
return URLSessionTask._TransferState(url: url, bodyDataDrain: drain, bodySource: source)
case .stream:
NSUnimplemented()
}
}
/// The data drain.
///
/// This depends on what the delegate / completion handler need.
fileprivate func createTransferBodyDataDrain() -> URLSessionTask._TransferState._DataDrain {
switch session.behaviour(for: self) {
case .noDelegate:
return .ignore
case .taskDelegate:
// Data will be forwarded to the delegate as we receive it, we don't
// need to do anything about it.
return .ignore
case .dataCompletionHandler:
// Data needs to be concatenated in-memory such that we can pass it
// to the completion handler upon completion.
return .inMemory(nil)
case .downloadCompletionHandler:
// Data needs to be written to a file (i.e. a download task).
let fileHandle = try! FileHandle(forWritingTo: tempFileURL)
return .toFile(tempFileURL, fileHandle)
}
}
/// Set options on the easy handle to match the given request.
///
/// This performs a series of `curl_easy_setopt()` calls.
fileprivate func configureEasyHandle(for request: URLRequest) {
// At this point we will call the equivalent of curl_easy_setopt()
// to configure everything on the handle. Since we might be re-using
// a handle, we must be sure to set everything and not rely on defaul
// values.
//TODO: We could add a strong reference from the easy handle back to
// its URLSessionTask by means of CURLOPT_PRIVATE -- that would ensure
// that the task is always around while the handle is running.
// We would have to break that retain cycle once the handle completes
// its transfer.
// Behavior Options
easyHandle.set(verboseModeOn: enableLibcurlDebugOutput)
easyHandle.set(debugOutputOn: enableLibcurlDebugOutput, task: self)
easyHandle.set(passHeadersToDataStream: false)
easyHandle.set(progressMeterOff: true)
easyHandle.set(skipAllSignalHandling: true)
// Error Options:
easyHandle.set(errorBuffer: nil)
easyHandle.set(failOnHTTPErrorCode: false)
// Network Options:
guard let url = request.url else { fatalError("No URL in request.") }
easyHandle.set(url: url)
easyHandle.setAllowedProtocolsToHTTPAndHTTPS()
easyHandle.set(preferredReceiveBufferSize: Int.max)
do {
switch (body, try body.getBodyLength()) {
case (.none, _):
set(requestBodyLength: .noBody)
case (_, .some(let length)):
set(requestBodyLength: .length(length))
case (_, .none):
set(requestBodyLength: .unknown)
}
} catch let e {
// Fail the request here.
// TODO: We have multiple options:
// NSURLErrorNoPermissionsToReadFile
// NSURLErrorFileDoesNotExist
internalState = .transferFailed
failWith(errorCode: errorCode(fileSystemError: e), request: request)
return
}
// HTTP Options:
easyHandle.set(followLocation: false)
easyHandle.set(customHeaders: curlHeaders(for: request))
//Options unavailable on Ubuntu 14.04 (libcurl 7.36)
//TODO: Introduce something like an #if
//easyHandle.set(waitForPipeliningAndMultiplexing: true)
//easyHandle.set(streamWeight: priority)
//set the request timeout
//TODO: the timeout value needs to be reset on every data transfer
let s = session as! URLSession
easyHandle.set(timeout: Int(s.configuration.timeoutIntervalForRequest))
easyHandle.set(automaticBodyDecompression: true)
easyHandle.set(requestMethod: request.httpMethod ?? "GET")
if request.httpMethod == "HEAD" {
easyHandle.set(noBody: true)
} else if ((request.httpMethod == "POST") && (request.value(forHTTPHeaderField: "Content-Type") == nil)) {
easyHandle.set(customHeaders: ["Content-Type:application/x-www-form-urlencoded"])
}
}
}
fileprivate extension URLSessionTask {
/// These are a list of headers that should be passed to libcurl.
///
/// Headers will be returned as `Accept: text/html` strings for
/// setting fields, `Accept:` for disabling the libcurl default header, or
/// `Accept;` for a header with no content. This is the format that libcurl
/// expects.
///
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html
func curlHeaders(for request: URLRequest) -> [String] {
var result: [String] = []
var names = Set<String>()
if let hh = currentRequest?.allHTTPHeaderFields {
hh.forEach {
let name = $0.0.lowercased()
guard !names.contains(name) else { return }
names.insert(name)
if $0.1.isEmpty {
result.append($0.0 + ";")
} else {
result.append($0.0 + ": " + $0.1)
}
}
}
curlHeadersToSet.forEach {
let name = $0.0.lowercased()
guard !names.contains(name) else { return }
names.insert(name)
if $0.1.isEmpty {
result.append($0.0 + ";")
} else {
result.append($0.0 + ": " + $0.1)
}
}
curlHeadersToRemove.forEach {
let name = $0.lowercased()
guard !names.contains(name) else { return }
names.insert(name)
result.append($0 + ":")
}
return result
}
/// Any header values that should be passed to libcurl
///
/// These will only be set if not already part of the request.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html
var curlHeadersToSet: [(String,String)] {
var result = [("Connection", "keep-alive"),
("User-Agent", userAgentString),
]
if let language = NSLocale.current.languageCode {
result.append(("Accept-Language", language))
}
return result
}
/// Any header values that should be removed from the ones set by libcurl
/// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html
var curlHeadersToRemove: [String] {
if case .none = body {
return []
} else {
return ["Expect"]
}
}
}
fileprivate var userAgentString: String = {
// Darwin uses something like this: "xctest (unknown version) CFNetwork/760.4.2 Darwin/15.4.0 (x86_64)"
let info = ProcessInfo.processInfo
let name = info.processName
let curlVersion = CFURLSessionCurlVersionInfo()
//TODO: Should probably use sysctl(3) to get these:
// kern.ostype: Darwin
// kern.osrelease: 15.4.0
//TODO: Use NSBundle to get the version number?
return "\(name) (unknown version) curl/\(curlVersion.major).\(curlVersion.minor).\(curlVersion.patch)"
}()
fileprivate func errorCode(fileSystemError error: Error) -> Int {
func fromCocoaErrorCode(_ code: Int) -> Int {
switch code {
case CocoaError.fileReadNoSuchFile.rawValue:
return NSURLErrorFileDoesNotExist
case CocoaError.fileReadNoPermission.rawValue:
return NSURLErrorNoPermissionsToReadFile
default:
return NSURLErrorUnknown
}
}
switch error {
case let e as NSError where e.domain == NSCocoaErrorDomain:
return fromCocoaErrorCode(e.code)
default:
return NSURLErrorUnknown
}
}
fileprivate extension URLSessionTask {
/// Set request body length.
///
/// An unknown length
func set(requestBodyLength length: URLSessionTask._RequestBodyLength) {
switch length {
case .noBody:
easyHandle.set(upload: false)
easyHandle.set(requestBodyLength: 0)
case .length(let length):
easyHandle.set(upload: true)
easyHandle.set(requestBodyLength: Int64(length))
case .unknown:
easyHandle.set(upload: true)
easyHandle.set(requestBodyLength: -1)
}
}
enum _RequestBodyLength {
case noBody
///
case length(UInt64)
/// Will result in a chunked upload
case unknown
}
}
extension URLSessionTask: _EasyHandleDelegate {
func didReceive(data: Data) -> _EasyHandle._Action {
guard case .transferInProgress(let ts) = internalState else { fatalError("Received body data, but no transfer in progress.") }
guard ts.isHeaderComplete else { fatalError("Received body data, but the header is not complete, yet.") }
notifyDelegate(aboutReceivedData: data)
internalState = .transferInProgress(ts.byAppending(bodyData: data))
return .proceed
}
fileprivate func notifyDelegate(aboutReceivedData data: Data) {
if case .taskDelegate(let delegate) = session.behaviour(for: self),
let dataDelegate = delegate as? URLSessionDataDelegate,
let task = self as? URLSessionDataTask {
// Forward to the delegate:
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
dataDelegate.urlSession(s, dataTask: task, didReceive: data)
}
} else if case .taskDelegate(let delegate) = session.behaviour(for: self),
let downloadDelegate = delegate as? URLSessionDownloadDelegate,
let task = self as? URLSessionDownloadTask {
guard let s = session as? URLSession else { fatalError() }
let fileHandle = try! FileHandle(forWritingTo: tempFileURL)
_ = fileHandle.seekToEndOfFile()
fileHandle.write(data)
self.totalDownloaded += data.count
s.delegateQueue.addOperation {
downloadDelegate.urlSession(s, downloadTask: task, didWriteData: Int64(data.count), totalBytesWritten: Int64(self.totalDownloaded),
totalBytesExpectedToWrite: Int64(self.easyHandle.fileLength))
}
if Int(self.easyHandle.fileLength) == totalDownloaded {
fileHandle.closeFile()
s.delegateQueue.addOperation {
downloadDelegate.urlSession(s, downloadTask: task, didFinishDownloadingTo: self.tempFileURL)
}
}
}
}
func didReceive(headerData data: Data) -> _EasyHandle._Action {
guard case .transferInProgress(let ts) = internalState else { fatalError("Received body data, but no transfer in progress.") }
do {
let newTS = try ts.byAppending(headerLine: data)
internalState = .transferInProgress(newTS)
let didCompleteHeader = !ts.isHeaderComplete && newTS.isHeaderComplete
if didCompleteHeader {
// The header is now complete, but wasn't before.
didReceiveResponse()
}
return .proceed
} catch {
return .abort
}
}
func fill(writeBuffer buffer: UnsafeMutableBufferPointer<Int8>) -> _EasyHandle._WriteBufferResult {
guard case .transferInProgress(let ts) = internalState else { fatalError("Requested to fill write buffer, but transfer isn't in progress.") }
guard let source = ts.requestBodySource else { fatalError("Requested to fill write buffer, but transfer state has no body source.") }
switch source.getNextChunk(withLength: buffer.count) {
case .data(let data):
copyDispatchData(data, infoBuffer: buffer)
let count = data.count
assert(count > 0)
return .bytes(count)
case .done:
return .bytes(0)
case .retryLater:
// At this point we'll try to pause the easy handle. The body source
// is responsible for un-pausing the handle once data becomes
// available.
return .pause
case .error:
return .abort
}
}
func transferCompleted(withErrorCode errorCode: Int?) {
// At this point the transfer is complete and we can decide what to do.
// If everything went well, we will simply forward the resulting data
// to the delegate. But in case of redirects etc. we might send another
// request.
guard case .transferInProgress(let ts) = internalState else { fatalError("Transfer completed, but it wasn't in progress.") }
guard let request = currentRequest else { fatalError("Transfer completed, but there's no currect request.") }
guard errorCode == nil else {
internalState = .transferFailed
failWith(errorCode: errorCode!, request: request)
return
}
guard let response = ts.response else { fatalError("Transfer completed, but there's no response.") }
internalState = .transferCompleted(response: response, bodyDataDrain: ts.bodyDataDrain)
let action = completionAction(forCompletedRequest: request, response: response)
switch action {
case .completeTask:
completeTask()
case .failWithError(let errorCode):
internalState = .transferFailed
failWith(errorCode: errorCode, request: request)
case .redirectWithRequest(let newRequest):
redirectFor(request: newRequest)
}
}
func seekInputStream(to position: UInt64) throws {
// We will reset the body sourse and seek forward.
NSUnimplemented()
}
func updateProgressMeter(with propgress: _EasyHandle._Progress) {
//TODO: Update progress. Note that a single URLSessionTask might
// perform multiple transfers. The values in `progress` are only for
// the current transfer.
}
}
/// State Transfers
extension URLSessionTask {
func completeTask() {
guard case .transferCompleted(response: let response, bodyDataDrain: let bodyDataDrain) = internalState else {
fatalError("Trying to complete the task, but its transfer isn't complete.")
}
self.response = response
//because we deregister the task with the session on internalState being set to taskCompleted
//we need to do the latter after the delegate/handler was notified/invoked
switch session.behaviour(for: self) {
case .taskDelegate(let delegate):
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
delegate.urlSession(s, task: self, didCompleteWithError: nil)
self.internalState = .taskCompleted
}
case .noDelegate:
internalState = .taskCompleted
case .dataCompletionHandler(let completion):
guard case .inMemory(let bodyData) = bodyDataDrain else {
fatalError("Task has data completion handler, but data drain is not in-memory.")
}
guard let s = session as? URLSession else { fatalError() }
var data = Data()
if let body = bodyData {
data = Data(bytes: body.bytes, count: body.length)
}
s.delegateQueue.addOperation {
completion(data, response, nil)
self.internalState = .taskCompleted
self.session = nil
}
case .downloadCompletionHandler(let completion):
guard case .toFile(let url, let fileHandle?) = bodyDataDrain else {
fatalError("Task has data completion handler, but data drain is not a file handle.")
}
guard let s = session as? URLSession else { fatalError() }
//The contents are already written, just close the file handle and call the handler
fileHandle.closeFile()
s.delegateQueue.addOperation {
completion(url, response, nil)
self.internalState = .taskCompleted
self.session = nil
}
}
}
func completeTask(withError error: NSError) {
guard case .transferFailed = internalState else {
fatalError("Trying to complete the task, but its transfer isn't complete / failed.")
}
switch session.behaviour(for: self) {
case .taskDelegate(let delegate):
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
delegate.urlSession(s, task: self, didCompleteWithError: error as Error)
self.internalState = .taskCompleted
}
case .noDelegate:
internalState = .taskCompleted
case .dataCompletionHandler(let completion):
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
completion(nil, nil, error)
self.internalState = .taskCompleted
}
case .downloadCompletionHandler(let completion):
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
completion(nil, nil, error)
self.internalState = .taskCompleted
}
}
}
func failWith(errorCode: Int, request: URLRequest) {
//TODO: Error handling
let userInfo: [String : Any]? = request.url.map {
[
NSURLErrorFailingURLErrorKey: $0,
NSURLErrorFailingURLStringErrorKey: $0.absoluteString,
]
}
let error = NSError(domain: NSURLErrorDomain, code: errorCode, userInfo: userInfo)
completeTask(withError: error)
}
func redirectFor(request: URLRequest) {
//TODO: Should keep track of the number of redirects that this
// request has gone through and err out once it's too large, i.e.
// call into `failWith(errorCode: )` with NSURLErrorHTTPTooManyRedirects
guard case .transferCompleted(response: let response, bodyDataDrain: let bodyDataDrain) = internalState else {
fatalError("Trying to redirect, but the transfer is not complete.")
}
switch session.behaviour(for: self) {
case .taskDelegate(let delegate):
// At this point we need to change the internal state to note
// that we're waiting for the delegate to call the completion
// handler. Then we'll call the delegate callback
// (willPerformHTTPRedirection). The task will then switch out of
// its internal state once the delegate calls the completion
// handler.
//TODO: Should the `public response: URLResponse` property be updated
// before we call delegate API
// `func urlSession(session: session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void)`
// ?
internalState = .waitingForRedirectCompletionHandler(response: response, bodyDataDrain: bodyDataDrain)
// We need this ugly cast in order to be able to support `URLSessionTask.init()`
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
delegate.urlSession(s, task: self, willPerformHTTPRedirection: response, newRequest: request) { [weak self] (request: URLRequest?) in
guard let task = self else { return }
task.workQueue.async {
task.didCompleteRedirectCallback(request)
}
}
}
case .noDelegate, .dataCompletionHandler, .downloadCompletionHandler:
// Follow the redirect.
startNewTransfer(with: request)
}
}
fileprivate func didCompleteRedirectCallback(_ request: URLRequest?) {
guard case .waitingForRedirectCompletionHandler(response: let response, bodyDataDrain: let bodyDataDrain) = internalState else {
fatalError("Received callback for HTTP redirection, but we're not waiting for it. Was it called multiple times?")
}
// If the request is `nil`, we're supposed to treat the current response
// as the final response, i.e. not do any redirection.
// Otherwise, we'll start a new transfer with the passed in request.
if let r = request {
startNewTransfer(with: r)
} else {
internalState = .transferCompleted(response: response, bodyDataDrain: bodyDataDrain)
completeTask()
}
}
}
/// Response processing
fileprivate extension URLSessionTask {
/// Whenever we receive a response (i.e. a complete header) from libcurl,
/// this method gets called.
func didReceiveResponse() {
guard let dt = self as? URLSessionDataTask else { return }
guard case .transferInProgress(let ts) = internalState else { fatalError("Transfer not in progress.") }
guard let response = ts.response else { fatalError("Header complete, but not URL response.") }
switch session.behaviour(for: self) {
case .noDelegate:
break
case .taskDelegate(let delegate as URLSessionDataDelegate):
//TODO: There's a problem with libcurl / with how we're using it.
// We're currently unable to pause the transfer / the easy handle:
// https://curl.haxx.se/mail/lib-2016-03/0222.html
//
// For now, we'll notify the delegate, but won't pause the transfer,
// and we'll disregard the completion handler:
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
delegate.urlSession(s, dataTask: dt, didReceive: response, completionHandler: { _ in
print("warning: Ignoring dispotion from completion handler.")
})
}
case .taskDelegate:
break
case .dataCompletionHandler:
break
case .downloadCompletionHandler:
break
}
}
/// Give the delegate a chance to tell us how to proceed once we have a
/// response / complete header.
///
/// This will pause the transfer.
func askDelegateHowToProceedAfterCompleteResponse(_ response: HTTPURLResponse, delegate: URLSessionDataDelegate) {
// Ask the delegate how to proceed.
// This will pause the easy handle. We need to wait for the
// delegate before processing any more data.
guard case .transferInProgress(let ts) = internalState else { fatalError("Transfer not in progress.") }
internalState = .waitingForResponseCompletionHandler(ts)
let dt = self as! URLSessionDataTask
// We need this ugly cast in order to be able to support `URLSessionTask.init()`
guard let s = session as? URLSession else { fatalError() }
s.delegateQueue.addOperation {
delegate.urlSession(s, dataTask: dt, didReceive: response, completionHandler: { [weak self] disposition in
guard let task = self else { return }
task.workQueue.async {
task.didCompleteResponseCallback(disposition: disposition)
}
})
}
}
/// This gets called (indirectly) when the data task delegates lets us know
/// how we should proceed after receiving a response (i.e. complete header).
func didCompleteResponseCallback(disposition: URLSession.ResponseDisposition) {
guard case .waitingForResponseCompletionHandler(let ts) = internalState else { fatalError("Received response disposition, but we're not waiting for it.") }
switch disposition {
case .cancel:
//TODO: Fail the task with NSURLErrorCancelled
NSUnimplemented()
case .allow:
// Continue the transfer. This will unpause the easy handle.
internalState = .transferInProgress(ts)
case .becomeDownload:
/* Turn this request into a download */
NSUnimplemented()
case .becomeStream:
/* Turn this task into a stream task */
NSUnimplemented()
}
}
/// Action to be taken after a transfer completes
enum _CompletionAction {
case completeTask
case failWithError(Int)
case redirectWithRequest(URLRequest)
}
/// What action to take
func completionAction(forCompletedRequest request: URLRequest, response: HTTPURLResponse) -> _CompletionAction {
// Redirect:
if let request = redirectRequest(for: response, fromRequest: request) {
return .redirectWithRequest(request)
}
return .completeTask
}
/// If the response is a redirect, return the new request
///
/// RFC 7231 section 6.4 defines redirection behavior for HTTP/1.1
///
/// - SeeAlso: <https://tools.ietf.org/html/rfc7231#section-6.4>
func redirectRequest(for response: HTTPURLResponse, fromRequest: URLRequest) -> URLRequest? {
//TODO: Do we ever want to redirect for HEAD requests?
func methodAndURL() -> (String, URL)? {
guard
let location = response.value(forHeaderField: .location),
let targetURL = URL(string: location)
else {
// Can't redirect when there's no location to redirect to.
return nil
}
// Check for a redirect:
switch response.statusCode {
//TODO: Should we do this for 300 "Multiple Choices", too?
case 301, 302, 303:
// Change into "GET":
return ("GET", targetURL)
case 307:
// Re-use existing method:
return (fromRequest.httpMethod ?? "GET", targetURL)
default:
return nil
}
}
guard let (method, targetURL) = methodAndURL() else { return nil }
var request = fromRequest
request.httpMethod = method
request.url = targetURL
return request
}
}
fileprivate extension HTTPURLResponse {
/// Type safe HTTP header field name(s)
enum _Field: String {
/// `Location`
/// - SeeAlso: RFC 2616 section 14.30 <https://tools.ietf.org/html/rfc2616#section-14.30>
case location = "Location"
}
func value(forHeaderField field: _Field) -> String? {
return field.rawValue
}
}
public let URLSessionTaskPriorityDefault: Float = 0.5
public let URLSessionTaskPriorityLow: Float = 0.25
public let URLSessionTaskPriorityHigh: Float = 0.75
/*
* An URLSessionDataTask does not provide any additional
* functionality over an URLSessionTask and its presence is merely
* to provide lexical differentiation from download and upload tasks.
*/
open class URLSessionDataTask : URLSessionTask {
}
/*
* An URLSessionUploadTask does not currently provide any additional
* functionality over an URLSessionDataTask. All delegate messages
* that may be sent referencing an URLSessionDataTask equally apply
* to URLSessionUploadTasks.
*/
open class URLSessionUploadTask : URLSessionDataTask {
}
/*
* URLSessionDownloadTask is a task that represents a download to
* local storage.
*/
open class URLSessionDownloadTask : URLSessionTask {
internal var fileLength = -1.0
/* Cancel the download (and calls the superclass -cancel). If
* conditions will allow for resuming the download in the future, the
* callback will be called with an opaque data blob, which may be used
* with -downloadTaskWithResumeData: to attempt to resume the download.
* If resume data cannot be created, the completion handler will be
* called with nil resumeData.
*/
open func cancel(byProducingResumeData completionHandler: (NSData?) -> Void) { NSUnimplemented() }
}
/*
* An URLSessionStreamTask provides an interface to perform reads
* and writes to a TCP/IP stream created via URLSession. This task
* may be explicitly created from an URLSession, or created as a
* result of the appropriate disposition response to a
* -URLSession:dataTask:didReceiveResponse: delegate message.
*
* URLSessionStreamTask can be used to perform asynchronous reads
* and writes. Reads and writes are enquened and executed serially,
* with the completion handler being invoked on the sessions delegate
* queuee. If an error occurs, or the task is canceled, all
* outstanding read and write calls will have their completion
* handlers invoked with an appropriate error.
*
* It is also possible to create InputStream and OutputStream
* instances from an URLSessionTask by sending
* -captureStreams to the task. All outstanding read and writess are
* completed before the streams are created. Once the streams are
* delivered to the session delegate, the task is considered complete
* and will receive no more messsages. These streams are
* disassociated from the underlying session.
*/
open class URLSessionStreamTask : URLSessionTask {
/* Read minBytes, or at most maxBytes bytes and invoke the completion
* handler on the sessions delegate queue with the data or an error.
* If an error occurs, any outstanding reads will also fail, and new
* read requests will error out immediately.
*/
open func readData(ofMinLength minBytes: Int, maxLength maxBytes: Int, timeout: TimeInterval, completionHandler: (NSData?, Bool, NSError?) -> Void) { NSUnimplemented() }
/* Write the data completely to the underlying socket. If all the
* bytes have not been written by the timeout, a timeout error will
* occur. Note that invocation of the completion handler does not
* guarantee that the remote side has received all the bytes, only
* that they have been written to the kernel. */
open func write(data: NSData, timeout: TimeInterval, completionHandler: (NSError?) -> Void) { NSUnimplemented() }
/* -captureStreams completes any already enqueued reads
* and writes, and then invokes the
* URLSession:streamTask:didBecomeInputStream:outputStream: delegate
* message. When that message is received, the task object is
* considered completed and will not receive any more delegate
* messages. */
open func captureStreams() { NSUnimplemented() }
/* Enqueue a request to close the write end of the underlying socket.
* All outstanding IO will complete before the write side of the
* socket is closed. The server, however, may continue to write bytes
* back to the client, so best practice is to continue reading from
* the server until you receive EOF.
*/
open func closeWrite() { NSUnimplemented() }
/* Enqueue a request to close the read side of the underlying socket.
* All outstanding IO will complete before the read side is closed.
* You may continue writing to the server.
*/
open func closeRead() { NSUnimplemented() }
/*
* Begin encrypted handshake. The hanshake begins after all pending
* IO has completed. TLS authentication callbacks are sent to the
* session's -URLSession:task:didReceiveChallenge:completionHandler:
*/
open func startSecureConnection() { NSUnimplemented() }
/*
* Cleanly close a secure connection after all pending secure IO has
* completed.
*/
open func stopSecureConnection() { NSUnimplemented() }
}
/* Key in the userInfo dictionary of an NSError received during a failed download. */
public let URLSessionDownloadTaskResumeData: String = "" // NSUnimplemented
extension URLSession {
static func printDebug(_ text: @autoclosure () -> String) {
guard enableDebugOutput else { return }
debugPrint(text())
}
}
fileprivate let enableLibcurlDebugOutput: Bool = {
return (ProcessInfo.processInfo.environment["URLSessionDebugLibcurl"] != nil)
}()
fileprivate let enableDebugOutput: Bool = {
return (ProcessInfo.processInfo.environment["URLSessionDebug"] != nil)
}()
| apache-2.0 |
KeithPiTsui/Pavers | Pavers/Sources/CryptoSwift/Array+Extension.swift | 2 | 2913 | //
// ArrayExtension.swift
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
extension Array {
init(reserveCapacity: Int) {
self = Array<Element>()
self.reserveCapacity(reserveCapacity)
}
var slice: ArraySlice<Element> {
return self[self.startIndex..<self.endIndex]
}
}
extension Array {
/// split in chunks with given chunk size
@available(*, deprecated: 0.8.0, message: "")
public func chunks(size chunksize: Int) -> Array<Array<Element>> {
var words = Array<Array<Element>>()
words.reserveCapacity(count / chunksize)
for idx in stride(from: chunksize, through: count, by: chunksize) {
words.append(Array(self[idx - chunksize..<idx])) // slow for large table
}
let remainder = suffix(count % chunksize)
if !remainder.isEmpty {
words.append(Array(remainder))
}
return words
}
}
extension Array where Element == UInt8 {
public init(hex: String) {
self.init(reserveCapacity: hex.unicodeScalars.lazy.underestimatedCount)
var buffer: UInt8?
var skip = hex.hasPrefix("0x") ? 2 : 0
for char in hex.unicodeScalars.lazy {
guard skip == 0 else {
skip -= 1
continue
}
guard char.value >= 48 && char.value <= 102 else {
removeAll()
return
}
let v: UInt8
let c: UInt8 = UInt8(char.value)
switch c {
case let c where c <= 57:
v = c - 48
case let c where c >= 65 && c <= 70:
v = c - 55
case let c where c >= 97:
v = c - 87
default:
removeAll()
return
}
if let b = buffer {
append(b << 4 | v)
buffer = nil
} else {
buffer = v
}
}
if let b = buffer {
append(b)
}
}
}
| mit |
ahoppen/swift | test/SourceKit/CursorInfo/rdar_64230277.swift | 13 | 220 | // RUN: %sourcekitd-test -req=cursor -pos=5:16 %s -- %s | %FileCheck %s
protocol View {}
struct MyView: View {}
func indicator<T>(_ a: T) -> some View {
MyView()
}
// CHECK: source.lang.swift.decl.generic_type_param
| apache-2.0 |
brentsimmons/Evergreen | Account/Tests/AccountTests/Feedly/FeedlyTextSanitizationTests.swift | 1 | 1291 | //
// FeedlyTextSanitizationTests.swift
// AccountTests
//
// Created by Kiel Gillard on 29/1/20.
// Copyright © 2020 Ranchero Software, LLC. All rights reserved.
//
import XCTest
@testable import Account
class FeedlyTextSanitizationTests: XCTestCase {
func testRTLSanitization() {
let targetsAndExpectations: [(target: String?, expectation: String?)] = [
(nil, nil),
("", ""),
(" ", " "),
("text", "text"),
("<div style=\"direction:rtl;text-align:right\">", "<div style=\"direction:rtl;text-align:right\">"),
("</div>", "</div>"),
("<div style=\"direction:rtl;text-align:right\">text", "<div style=\"direction:rtl;text-align:right\">text"),
("text</div>", "text</div>"),
("<div style=\"direction:rtl;text-align:right\"></div>", ""),
("<DIV style=\"direction:rtl;text-align:right\"></div>", "<DIV style=\"direction:rtl;text-align:right\"></div>"),
("<div style=\"direction:rtl;text-align:right\"></DIV>", "<div style=\"direction:rtl;text-align:right\"></DIV>"),
("<div style=\"direction:rtl;text-align:right\">text</div>", "text"),
]
let sanitizer = FeedlyRTLTextSanitizer()
for (target, expectation) in targetsAndExpectations {
let calculated = sanitizer.sanitize(target)
XCTAssertEqual(expectation, calculated)
}
}
}
| mit |
cuappdev/tcat-ios | TCAT/Utilities/Phrases.swift | 1 | 8497 | //
// Personality.swift
//
// Created by Matthew Barker on 04/15/18
// Copyright © 2018 cuappdev. All rights reserved.
//
import Foundation
struct Messages {
static let walkingPhrases: [String] = [
"A little exercise never hurt anyone!",
"I hope it's a nice day!",
"Get yourself some Itha-calves"
]
static let shoppingPhrases: [String] = [
"Stock up on some Ramen noodles!",
"Paper or plastic?",
"Pro Tip: Never grocery shop on an empty stomach"
]
// MARK: - Cornell
static let rpcc: [String] = [
"In the kitchen, wrist twistin' like it's Mongo 🎵",
"The best place for 1 AM calzones 😋",
"Hear someone passionately scream out your name 😉"
]
static let bakerFlagpole: [String] = [
"You should try the food on East Campus some time!",
"Grab a snack at Jansen's 🍪",
"Admire how slope-y the slope is."
]
static let statler: [String] = [
"You can check out any time you like, but you can never leave 🎵",
"The Terrace has the best burritos on campus 🌯",
"You think dorms are expensive, try staying a night here!"
]
static let rockefeller: [String] = [
"Voted #3 Best Bus Stop Shelter in Tompkins County",
"Why is it called East Ave.? It doesn't even go east!",
"I bet there's a Rockefeller building on every old campus"
]
static let balch: [String] = [
"Home of the Balch Arch, aka the Barch!",
"Treat yourself with a Louie's milkshake 😋",
"Dorm sweet dorm!"
]
static let schwartz: [String] = [
"Try something new at CTB!",
"I wonder if eHub is crowded... probably",
"Welcome to the hustle and bustle of Collegetown"
]
// MARK: - Ithaca
static let regalCinema: [String] = [
"The trailers always take a half hour anyway...",
"Grab some popcorn! 🍿",
"Don't track your bus while the movie is playing 🙂"
]
static let target: [String] = [
"Do they even sell targets?",
"Can you get tar at target?"
] + Messages.shoppingPhrases
static let mall: [String] = [
"Let's go to the mall... today! 🎵",
"You should play some lazer tag!"
]
static let wegmans: [String] = [
"Make sure you grab a liter of Dr. W!",
"Weg it up."
] + Messages.shoppingPhrases
static let walmart: [String] = [
"But they don't sell any walls...",
"A small mom & pop shop owned by Wally and Marty"
] + Messages.shoppingPhrases
static let chipotle: [String] = [
"Honestly, the new queso is a bit underwhelming...",
"Get there early before they run out of guac!",
"Try getting a quesarito, a secret menu item!"
]
}
class Phrases {
/// Select random string from array
static func selectMessage(from messages: [String]) -> String {
let rand = Int(arc4random_uniform(UInt32(messages.count)))
return messages[rand]
}
}
class LocationPhrases: Phrases {
/// For new places, use: https://boundingbox.klokantech.com set to CSV.
/// For overlapping places, put the smaller one first
static let places: [CustomLocation] = [
CustomLocation(
messages: Messages.rpcc,
minimumLongitude: -76.4780073578,
minimumLatitude: 42.4555571687,
maximumLongitude: -76.4770239162,
maximumLatitude: 42.4562933289
),
CustomLocation(
messages: Messages.bakerFlagpole,
minimumLongitude: -76.4882680195,
minimumLatitude: 42.447154511,
maximumLongitude: -76.4869808879,
maximumLatitude: 42.4482142506
),
CustomLocation(
messages: Messages.statler,
minimumLongitude: -76.4826804461,
minimumLatitude: 42.445607399,
maximumLongitude: -76.4816523295,
maximumLatitude: 42.4467569576
),
CustomLocation(
messages: Messages.rockefeller,
minimumLongitude: -76.4828309704,
minimumLatitude: 42.4493108267,
maximumLongitude: -76.4824479047,
maximumLatitude: 42.44969019
),
CustomLocation(
messages: Messages.balch,
minimumLongitude: -76.4811291114,
minimumLatitude: 42.4526837484,
maximumLongitude: -76.4789034578,
maximumLatitude: 42.4536103104
),
CustomLocation(
messages: Messages.schwartz,
minimumLongitude: -76.4855623082,
minimumLatitude: 42.4424106249,
maximumLongitude: -76.4849883155,
maximumLatitude: 42.4428654009
),
CustomLocation(
messages: Messages.target,
minimumLongitude: -76.4927489222,
minimumLatitude: 42.4847167857,
maximumLongitude: -76.4889960764,
maximumLatitude: 42.4858172457
),
CustomLocation(
messages: Messages.regalCinema,
minimumLongitude: -76.493338437,
minimumLatitude: 42.4838963076,
maximumLongitude: -76.4914179754,
maximumLatitude: 42.4846716949
),
CustomLocation(
messages: Messages.mall,
minimumLongitude: -76.493291,
minimumLatitude: 42.480977,
maximumLongitude: -76.488651,
maximumLatitude: 42.48597
),
CustomLocation(
messages: Messages.wegmans,
minimumLongitude: -76.5114533069,
minimumLatitude: 42.4336357432,
maximumLongitude: -76.5093075397,
maximumLatitude: 42.4362012905
),
CustomLocation(
messages: Messages.walmart,
minimumLongitude: -76.5148997155,
minimumLatitude: 42.4265752766,
maximumLongitude: -76.511709343,
maximumLatitude: 42.4284506244
),
CustomLocation(
messages: Messages.chipotle,
minimumLongitude: -76.5082565033,
minimumLatitude: 42.4297004932,
maximumLongitude: -76.5080904931,
maximumLatitude: 42.4302749214
)
]
/// Return a string from the first location within the range of coordinates. Otherwise, return nil.
static func generateMessage(latitude: Double, longitude: Double) -> String? {
for place in places {
if place.isWithinRange(latitude: latitude, longitude: longitude) {
return selectMessage(from: place.messages)
}
}
return nil
}
}
class WalkingPhrases: Phrases {
/// If route is solely a walking direction, return message. Otherwise, return nil.
static func generateMessage(route: Route) -> String? {
let messages = Messages.walkingPhrases
return route.isRawWalkingRoute() ? selectMessage(from: messages) : nil
}
}
// MARK: - Utility Classes & Functions
/// A custom location the a user searches for. Coordinates used for matching.
struct CustomLocation: Equatable {
/// Messages related to location
var messages: [String]
// MARK: - Bounding Box Variables
/// The bottom left corner longitude value for the location's bounding box
var maximumLongitude: Double
/// The bottom right corner latitude value for the location's bounding box
var minimumLatitude: Double
/// The top right corner longitude value for the location's bounding box
var minimumLongitude: Double
/// The top left corner latitude value for the location's bounding box
var maximumLatitude: Double
init(messages: [String], minimumLongitude: Double, minimumLatitude: Double, maximumLongitude: Double, maximumLatitude: Double) {
self.messages = messages
self.minimumLongitude = minimumLongitude
self.minimumLatitude = minimumLatitude
self.maximumLongitude = maximumLongitude
self.maximumLatitude = maximumLatitude
}
/// Returns true is passed in coordinates are within the range of the location
func isWithinRange(latitude: Double, longitude: Double) -> Bool {
let isLatInRange = minimumLatitude <= latitude && latitude <= maximumLatitude
let isLongInRange = minimumLongitude <= longitude && longitude <= maximumLongitude
return isLatInRange && isLongInRange
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/11513-swift-type-walk.swift | 11 | 242 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A : g
protocol g {
func f<S : a
{
}
protocol a {
typealias e : A.a
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/14385-swift-sourcemanager-getmessage.swift | 11 | 216 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum A {
let a {
deinit {
{
}
{
}
class
case ,
| mit |
uShip/iOSIdeaFlow | IdeaFlow/IdeaFlowEvent+AssociatedValues.swift | 1 | 2434 | //
// IdeaFlowEvent+Stuff.swift
// IdeaFlow
//
// Created by Matt Hayes on 8/14/15.
// Copyright (c) 2015 uShip. All rights reserved.
//
import Foundation
import UIKit
import CoreData
extension IdeaFlowEvent
{
enum EventType: String
{
case Productivity = "Productivity"
case Troubleshooting = "Troubleshooting"
case Learning = "Learning"
case Rework = "Rework"
case Pause = "Pause"
case Unknown = "Unknown"
init(int: Int32)
{
switch int
{
case 1:
self = .Productivity
case 2:
self = .Troubleshooting
case 3:
self = .Learning
case 4:
self = .Rework
case 5:
self = .Pause
default:
self = .Unknown
}
}
func intValue() -> Int32
{
switch (self)
{
case .Unknown:
return 0
case .Productivity:
return 1
case .Troubleshooting:
return 2
case .Learning:
return 3
case .Rework:
return 4
case .Pause:
return 5
}
}
}
func eventTypeName() -> String
{
return EventType(int: eventType.intValue).rawValue
}
func eventTypeColor() -> UIColor
{
switch EventType(int: eventType.intValue)
{
case .Productivity:
return UIColor.lightGrayColor()
case .Troubleshooting:
return UIColor.redColor()
case .Learning:
return UIColor.blueColor()
case .Rework:
return UIColor.orangeColor()
case .Pause:
return UIColor.blackColor()
default:
return UIColor.magentaColor()
}
}
class func csvColumnNames() -> String
{
return "startTimeStamp, eventType, identifier"
}
func asCSV() -> String
{
let eventTypeString = EventType(int: eventType.intValue).rawValue
let startTimeStampString = "\(startTimeStamp)"
//TODO: include notes
// for note in notes
// {
//
// }
return "\(startTimeStampString),\(eventTypeString),\(identifier)"
}
} | gpl-3.0 |
avito-tech/Marshroute | Marshroute/Sources/Utilities/AssertionUtiliites/MarshrouteAssertionPlugin.swift | 1 | 943 | public protocol MarshrouteAssertionPlugin: AnyObject {
func assert(
_ condition: @autoclosure () -> Bool,
_ message: @autoclosure () -> String,
file: StaticString,
line: UInt)
func assertionFailure(
_ message: @autoclosure () -> String,
file: StaticString,
line: UInt)
}
public final class DefaultMarshrouteAssertionPlugin: MarshrouteAssertionPlugin {
public init() {}
public func assert(
_ condition: @autoclosure () -> Bool,
_ message: @autoclosure () -> String,
file: StaticString,
line: UInt)
{
if !condition() {
Swift.print("\(message()), file: \(file), line: \(line)")
}
}
public func assertionFailure(
_ message: @autoclosure () -> String,
file: StaticString,
line: UInt)
{
Swift.print("\(message()), file: \(file), line: \(line)")
}
}
| mit |
ccrama/Slide-iOS | Slide for Reddit/NSDate+Extensions.swift | 1 | 678 | //
// NSDate+Extensions.swift
// Slide for Reddit
//
// Created by Jonathan Cole on 11/14/18.
// Copyright © 2018 Haptic Apps. All rights reserved.
//
import Foundation
extension Date {
var timeAgoString: String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.maximumUnitCount = 1
formatter.allowedUnits = [.year, .month, .day, .hour, .minute, .second]
guard let timeString = formatter.string(from: self, to: Date()) else {
return nil
}
let formatString = NSLocalizedString("%@ ago", comment: "")
return String(format: formatString, timeString)
}
}
| apache-2.0 |
pollarm/MondoKit | MondoKitTestApp/Accounts/AccountDetailsViewController.swift | 1 | 9320 | //
// AccountDetailsViewController.swift
// MondoKit
//
// Created by Mike Pollard on 24/01/2016.
// Copyright © 2016 Mike Pollard. All rights reserved.
//
import UIKit
import MondoKit
class AccountDetailsViewController: UIViewController {
@IBOutlet private var balanceLabel : UILabel!
@IBOutlet private var spentLabel : UILabel!
private var transactionsController : AccountTransactionsViewController!
var account : MondoAccount?
private var balance : MondoAccountBalance? {
didSet {
if let balance = balance {
let currencyFormatter = NSNumberFormatter()
currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyAccountingStyle
let locale = NSLocale.currentLocale()
let symbol = locale.displayNameForKey(NSLocaleCurrencySymbol, value: balance.currency)
currencyFormatter.currencySymbol = symbol
let currency = CurrencyFormatter(isoCode: balance.currency)
balanceLabel?.text = currency.stringFromMinorUnitsValue(balance.balance)
spentLabel?.text = currency.stringFromMinorUnitsValue(balance.spendToday)
}
else {
balanceLabel?.text = ""
spentLabel?.text = ""
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let account = account {
title = account.description
MondoAPI.instance.getBalanceForAccount(account) { [weak self] (balance, error) in
self?.balance = balance
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let transactionsController = segue.destinationViewController as? AccountTransactionsViewController {
transactionsController.account = account
self.transactionsController = transactionsController
transactionsController.selectionHandler = { _ in
self.performSegueWithIdentifier("showDetails", sender: nil)
}
}
if let detailsController = segue.destinationViewController as? TransactionDetailController,
transaction = transactionsController.selectedTransaction {
detailsController.transaction = transaction
}
}
}
class TransactionCell : UITableViewCell {
@IBOutlet private var descriptionLabel : UILabel!
@IBOutlet private var categoryLabel : UILabel!
@IBOutlet private var amountLabel : UILabel!
override func awakeFromNib() {
super.awakeFromNib()
amountLabel.font = UIFont.monospacedDigitSystemFontOfSize(amountLabel.font.pointSize, weight: UIFontWeightRegular)
}
}
class AccountTransactionsViewController : UIViewController {
@IBOutlet private var tableView : UITableView!
var account : MondoAccount!
var selectionHandler : ((selected: MondoTransaction) -> Void)?
var selectedTransaction : MondoTransaction? {
if let dataSourceWithTransactions = tableView.dataSource as? DataSourceWithTransactions,
indexPath = tableView.indexPathForSelectedRow,
transaction = dataSourceWithTransactions.transactionAtIndexPath(indexPath) {
return transaction
}
else {
return nil
}
}
private let transactionsDataSource = TransactionsDataSource()
private let feedDataSource = FeedDataSource()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = transactionsDataSource
tableView.delegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
transactionsDataSource.loadTransactionsForAccount(account) { [weak self] _ in
self?.tableView.reloadData()
}
}
@IBAction func segmentedValueChanged(segmentedControl: UISegmentedControl) {
if segmentedControl.selectedSegmentIndex == 0 {
tableView.dataSource = transactionsDataSource
transactionsDataSource.loadTransactionsForAccount(account) { [weak self] _ in
self?.tableView.reloadData()
}
}
else {
tableView.dataSource = feedDataSource
feedDataSource.loadFeedForAccount(account) { [weak self] _ in
self?.tableView.reloadData()
}
}
}
}
protocol DataSourceWithTransactions {
func transactionAtIndexPath(indexPath : NSIndexPath) -> MondoTransaction?
}
private class FeedDataSource : NSObject, UITableViewDataSource, DataSourceWithTransactions {
private static let FeedCellIdentifier = "TransactionCell2"
private var feedItems : [MondoFeedItem]?
private func loadFeedForAccount(account: MondoAccount, completion: ()->Void) {
MondoAPI.instance.listFeedForAccount(account) { [weak self] (items, error) in
if let items = items {
self?.feedItems = items
}
completion()
}
}
private func transactionAtIndexPath(indexPath : NSIndexPath) -> MondoTransaction? {
return feedItems?[indexPath.row].transaction
}
@objc func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return feedItems?.count ?? 0
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(FeedDataSource.FeedCellIdentifier, forIndexPath: indexPath) as! TransactionCell
if let feedItem = feedItems?[indexPath.row] {
if let transaction = feedItem.transaction {
if let m = transaction.merchant, case .Expanded(let merchant) = m {
cell.descriptionLabel.text = merchant.name
}
else {
cell.descriptionLabel.text = transaction.description
}
cell.categoryLabel.text = transaction.category.rawValue
let currency = CurrencyFormatter(isoCode: transaction.currency)
cell.amountLabel.text = currency.stringFromMinorUnitsValue(transaction.amount)
}
else {
cell.descriptionLabel.text = ""
cell.categoryLabel.text = feedItem.type.rawValue
cell.amountLabel.text = ""
}
}
return cell
}
}
private class TransactionsDataSource : NSObject, UITableViewDataSource, DataSourceWithTransactions {
private static let TransactionCellIdentifier = "TransactionCell2"
private var transactions : [MondoTransaction]?
private func loadTransactionsForAccount(account: MondoAccount, completion: ()->Void) {
MondoAPI.instance.listTransactionsForAccount(account, expand: "merchant") { [weak self] (transactions, error) in
if let transactions = transactions {
self?.transactions = transactions
}
completion()
}
}
private func transactionAtIndexPath(indexPath : NSIndexPath) -> MondoTransaction? {
return transactions?[indexPath.row]
}
@objc func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return transactions?.count ?? 0
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(TransactionsDataSource.TransactionCellIdentifier, forIndexPath: indexPath) as! TransactionCell
if let transaction = transactions?[indexPath.row] {
if let m = transaction.merchant, case .Expanded(let merchant) = m {
cell.descriptionLabel.text = merchant.name
}
else {
cell.descriptionLabel.text = transaction.description
}
cell.categoryLabel.text = transaction.category.rawValue
let currency = CurrencyFormatter(isoCode: transaction.currency)
cell.amountLabel.text = currency.stringFromMinorUnitsValue(transaction.amount)
}
return cell
}
}
extension AccountTransactionsViewController : UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let dataSourceWithTransactions = tableView.dataSource as? DataSourceWithTransactions,
transaction = dataSourceWithTransactions.transactionAtIndexPath(indexPath) {
selectionHandler?(selected: transaction)
}
}
}
| mit |
Stitch7/Instapod | Instapod/Podcast/PodcastsViewController.swift | 1 | 15727 | //
// PodcastsViewController.swift
// Instapod
//
// Created by Christopher Reitz on 03.09.16.
// Copyright © 2016 Christopher Reitz. All rights reserved.
//
import UIKit
import CoreData
class PodcastsViewController: UIViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource, PodcastListDelegate, FeedUpdaterDelegate, FeedImporterDelegate, CoreDataContextInjectable {
// MARK: - Properties
var podcasts = [Podcast]()
var pageViewController: UIPageViewController?
var editingMode: PodcastListEditingMode = .off
var viewMode: PodcastListViewMode = .tableView
var tableViewController: PodcastsTableViewController?
var collectionViewController: PodcastsCollectionViewController?
var toolbarLabel: UILabel?
var updater: FeedUpdater?
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
podcasts = loadData(context: coreDataContext)
configureAppNavigationBar()
configureNavigationBar()
configureToolbar()
configureTableViewController()
configureCollectionViewController()
configurePageViewController()
updater = initFeedupdater(podcasts: podcasts)
}
override func viewWillAppear(_ animated: Bool) {
guard
let playerVC: PlayerViewController = UIStoryboard(name: "Main", bundle: nil).instantiate(),
let navVC = self.navigationController,
navVC.popupContent == nil
else { return }
navVC.presentPopupBar(withContentViewController: playerVC, openPopup: false, animated: false) {
navVC.dismissPopupBar(animated: false)
}
}
func initFeedupdater(podcasts: [Podcast]) -> FeedUpdater {
let updater = FeedUpdater(podcasts: podcasts)
updater.delegates.addDelegate(self)
if let tableVC = tableViewController {
updater.delegates.addDelegate(tableVC)
}
if let collectionVC = collectionViewController {
updater.delegates.addDelegate(collectionVC)
}
return updater
}
func configureNavigationBar() {
title = "Podcasts" // TODO: i18n
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Edit", // TODO: i18n
style: .plain,
target: self,
action: #selector(editButtonPressed))
let switchViewButton = UIButton(type: .custom)
let sortButtonImage = PodcastListViewMode.collectionView.image
switchViewButton.setImage(sortButtonImage, for: UIControlState())
switchViewButton.addTarget(self,
action: #selector(switchViewButtonPressed),
for: .touchUpInside)
switchViewButton.frame = CGRect(x: 0, y: 0, width: 22, height: 22)
let switchViewBarButton = UIBarButtonItem(customView: switchViewButton)
navigationItem.rightBarButtonItem = switchViewBarButton
}
func configureToolbar() {
configureToolbarItems()
configureToolbarApperance()
}
func configureToolbarItems() {
let spacer: () -> UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
target: self,
action: nil)
}
let addButton = UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(addFeedButtonPressed))
let labelView = UILabel(frame: CGRect(x: 0, y: 0, width: 220, height: 22))
labelView.font = UIFont.systemFont(ofSize: 12)
labelView.textAlignment = .center
let label = UIBarButtonItem(customView: labelView)
self.toolbarLabel = labelView
updateToolbarLabel()
let sortButtonView = UIButton(type: .custom)
let sortButtonImage = UIImage(named: "sortButtonDesc")?.withRenderingMode(.alwaysTemplate)
sortButtonView.setImage(sortButtonImage, for: UIControlState())
sortButtonView.addTarget(self,
action: #selector(sortButtonPressed),
for: .touchUpInside)
sortButtonView.frame = CGRect(x: 0, y: 0, width: 22, height: 22)
let sortButton = UIBarButtonItem(customView: sortButtonView)
toolbarItems = [addButton, spacer(), label, spacer(), sortButton]
}
func updateToolbarLabel() {
toolbarLabel?.text = "\(podcasts.count) Subscriptions" // TODO: i18n
}
func configureToolbarApperance() {
guard let navController = navigationController else { return }
let screenWidth = UIScreen.main.bounds.size.width
let toolbarBarColor = ColorPalette.Background.withAlphaComponent(0.9)
let toolbar = navController.toolbar
toolbar?.setBackgroundImage(UIImage(), forToolbarPosition: .bottom, barMetrics: .default)
toolbar?.backgroundColor = toolbarBarColor
toolbar?.clipsToBounds = true
let toolbarView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 20.0))
toolbarView.backgroundColor = toolbarBarColor
navController.view.addSubview(toolbarView)
navController.isToolbarHidden = false
}
func configureTableViewController() {
tableViewController = storyboard?.instantiate()
tableViewController?.podcasts = podcasts
tableViewController?.delegate = self
}
func configureCollectionViewController() {
collectionViewController = storyboard?.instantiate()
collectionViewController?.podcasts = podcasts
collectionViewController?.delegate = self
}
func configurePageViewController() {
guard let
tableVC = self.tableViewController,
let pageVC: UIPageViewController = storyboard?.instantiate()
else { return }
pageVC.delegate = self
pageVC.dataSource = self
pageVC.view.backgroundColor = UIColor.groupTableViewBackground
pageVC.setViewControllers([tableVC], direction: .forward, animated: false, completion: nil)
addChildViewController(pageVC)
view.addSubview(pageVC.view)
view.sendSubview(toBack: pageVC.view)
pageVC.didMove(toParentViewController: self)
pageViewController = pageVC
}
// MARK: - Database
func reload() {
podcasts = loadData(context: coreDataContext)
tableViewController?.podcasts = podcasts
tableViewController?.tableView.reloadData()
updateToolbarLabel()
}
func loadData(context: NSManagedObjectContext) -> [Podcast] {
var podcasts = [Podcast]()
do {
let fetchRequest: NSFetchRequest<NSManagedObject> = NSFetchRequest(entityName: "Podcast")
fetchRequest.sortDescriptors = [
NSSortDescriptor(key: "sortIndex", ascending: true)
]
let managedPodcasts = try context.fetch(fetchRequest) as! [PodcastManagedObject]
for managedPodcast in managedPodcasts {
podcasts.append(Podcast(managedObject: managedPodcast))
}
context.reset()
}
catch {
print("Error: Could not load podcasts from db: \(error)")
}
return podcasts
}
// MARK: - PodcastListDelegate
func updateFeeds() {
updater?.update()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func podcastSelected(_ podcast: Podcast) {
performSegue(withIdentifier: "ShowEpisodes", sender: podcast)
}
// MARK: - FeedUpdaterDelegate
func feedUpdater(_ feedupdater: FeedUpdater, didFinishWithEpisode foundEpisode: Episode, ofPodcast podcast: Podcast) {
var affected: Podcast?
let newPodcast = podcast
for oldPodcast in podcasts {
if oldPodcast.uuid == newPodcast.uuid {
affected = oldPodcast
break
}
}
guard let affectedPodcast = affected else { return }
do {
guard let
coordinator = coreDataContext.persistentStoreCoordinator,
let id = affectedPodcast.id,
let objectID = coordinator.managedObjectID(forURIRepresentation: id as URL),
let managedPodcast = try coreDataContext.existingObject(with: objectID) as? PodcastManagedObject
else { return }
let newEpisode = foundEpisode.createEpisode(fromContext: coreDataContext)
managedPodcast.addObject(newEpisode, forKey: "episodes")
try coreDataContext.save()
reload()
} catch {
print("Could bot save new episode \(error)")
}
}
func feedUpdater(_ feedupdater: FeedUpdater, didFinishWithNumberOfEpisodes numberOfEpisodes: Int) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
var hearts = ""; for _ in 0..<numberOfEpisodes { hearts += "♥️" }; print(hearts)
}
// MARK: - FeedImporterDelegate
func feedImporter(_ feedImporter: FeedImporter, didFinishWithFeed feed: Podcast) {
do {
let _ = feed.createPodcast(fromContext: coreDataContext)
try coreDataContext.save()
coreDataContext.reset()
} catch {
print("Error: Could not save podcasts to db: \(error)")
}
reload()
}
func feedImporterDidFinishWithAllFeeds(_ feedImporter: FeedImporter) {
loadingHUD(show: false)
}
// MARK: - Actions
func editButtonPressed(_ sender: UIBarButtonItem) {
guard let
tableVC = tableViewController,
let collectionVC = collectionViewController
else { return }
editingMode.nextValue()
switch editingMode {
case .on:
let attrs = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)]
sender.setTitleTextAttributes(attrs, for: UIControlState())
sender.title = "Done" // TODO: i18n
case .off:
let attrs = [NSFontAttributeName: UIFont.systemFont(ofSize: 18)]
sender.setTitleTextAttributes(attrs, for: UIControlState())
sender.title = "Edit" // TODO: i18n
}
switch viewMode {
case .tableView:
tableVC.setEditing(editingMode.boolValue, animated: true)
case .collectionView:
collectionVC.setEditing(editingMode.boolValue, animated: true)
}
}
func switchViewButtonPressed(_ sender: UIButton) {
guard let
pageVC = pageViewController,
let tableVC = tableViewController,
let collectionVC = collectionViewController
else { return }
var vc: UIViewController
var direction: UIPageViewControllerNavigationDirection
switch viewMode {
case .tableView:
vc = collectionVC
direction = .forward
case .collectionView:
vc = tableVC
direction = .reverse
}
pageVC.setViewControllers([vc], direction: direction, animated: true) { completed in
if completed {
self.switchViewButtonImage()
self.viewMode.nextValue()
}
}
}
func switchViewButtonImage() {
guard let
switchViewBarButton = self.navigationItem.rightBarButtonItem,
let switchViewButton = switchViewBarButton.customView as? UIButton
else { return }
switchViewButton.setImage(self.viewMode.image, for: UIControlState())
self.navigationItem.rightBarButtonItem = switchViewBarButton
}
func addFeedButtonPressed(_ sender: UIBarButtonItem) {
let alertController = UIAlertController(
title: "Add new Podcast", // TODO: i18n
message: nil,
preferredStyle: .alert
)
var feedUrlTextField: UITextField?
alertController.addTextField { (textField) in
textField.placeholder = "Feed URL" // TODO: i18n
feedUrlTextField = textField
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in // TODO: i18n
guard
let path = Bundle.main.path(forResource: "subscriptions", ofType: "opml"),
let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
else {
print("Failed loading subscriptions.opml")
return
}
self.loadingHUD(show: true, dimsBackground: true)
let datasource = FeedImporterDatasourceAEXML(data: data)
let feedImporter = FeedImporter(datasource: datasource)
feedImporter.delegates.addDelegate(self)
feedImporter.start()
}
let okAction = UIAlertAction(title: "Add", style: .default) { (action) in // TODO: i18n
guard let _ = feedUrlTextField?.text else { return }
// self.tableView.reloadData()
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
// alertController.view.tintColor = ColorPalette.
}
func sortButtonPressed(_ sender: UIBarButtonItem) {
let alertController = UIAlertController(title: nil,
message: "Sort by", // TODO: i18n
preferredStyle: .actionSheet)
let titleAction = UIAlertAction(title: "Title", style: .default) { (action) in // TODO: i18n
print("Sort by last abc")
}
alertController.addAction(titleAction)
let unplayedAction = UIAlertAction(title: "Unplayed", style: .default) { (action) in // TODO: i18n
print("Sort by last unplayed")
}
alertController.addAction(unplayedAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) // TODO: i18n
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
// MARK: - UIPageViewControllerDelegate
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
switchViewButtonImage()
viewMode.nextValue()
}
}
// MARK: - UIPageViewControllerDataSource
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if viewController.isKind(of: PodcastsTableViewController.self) { return nil }
return tableViewController
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if viewController.isKind(of: PodcastsCollectionViewController.self) { return nil }
return collectionViewController
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let podcast = sender as? Podcast else { return }
guard let episodesVC = segue.destination as? EpisodesViewController else { return }
// episodesVC.hidesBottomBarWhenPushed = true
episodesVC.podcast = podcast
}
}
| mit |
iSapozhnik/FamilyPocket | FamilyPocket/Extensions/AppHelpers.swift | 1 | 325 | //
// AppHelpers.swift
// FamilyPocket
//
// Created by Ivan Sapozhnik on 5/24/17.
// Copyright © 2017 Ivan Sapozhnik. All rights reserved.
//
import Foundation
extension UserDefaults {
class func groupUserDefaults() -> UserDefaults {
return UserDefaults(suiteName: "group.\(Constants.bundle())")!
}
}
| mit |
google-research/swift-tfp | Sources/LibTFP/ConstraintTransforms.swift | 1 | 12810 | // Copyright 2019 Google LLC
//
// 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
//
// https://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.
////////////////////////////////////////////////////////////////////////////////
// MARK: Simple transforms
// Normalizes names of variables
func alphaNormalize(_ constraints: [Constraint]) -> [Constraint] {
var rename = DefaultDict<Var, Var>(withDefault: makeVariableGenerator())
return constraints.map{ substitute($0, using: { rename[$0].expr }) }
}
// Returns a list of constraints in the same order, but with no single
// constraint appearing twice (only the first occurence is retained.
public func deduplicate(_ constraints: [Constraint]) -> [Constraint] {
struct BoolExprPair: Hashable { let expr: BoolExpr; let assumption: BoolExpr }
var seen = Set<BoolExprPair>()
// TODO: prefer asserted constraints to implicit constraints
return constraints.compactMap {
let key = BoolExprPair(expr: $0.expr, assumption: $0.assumption)
guard !seen.contains(key) else { return nil }
seen.insert(key)
return $0
}
}
// Preprocess constraints to find the weakest assumption under which a
// variable is used. This is useful, because it allows us to e.g. inline
// equalities when we have a guarantee that all users of a variable have
// to satisfy the same assumption that the equality does.
func computeWeakestAssumptions(_ constraints: [Constraint]) -> [Var: BoolExpr] {
var userAssumptions = DefaultDict<Var, Set<BoolExpr>>{ _ in [] }
for constraint in constraints {
switch constraint {
case let .expr(expr, assuming: cond, _, _):
let _ = substitute(expr, using: {
userAssumptions[$0].insert(cond)
return nil
})
}
}
var weakestAssumption: [Var: BoolExpr] = [:]
for entry in userAssumptions.dictionary {
let assumptions = entry.value.sorted(by: { $0.description < $1.description })
var currentWeakest = assumptions[0]
for assumption in assumptions.suffix(from: 1) {
if assumption =>? currentWeakest {
continue
} else if currentWeakest =>? assumption {
currentWeakest = assumption
} else {
currentWeakest = .true
}
}
weakestAssumption[entry.key] = currentWeakest
}
return weakestAssumption
}
// Tries to iteratively go over expressions, simplify them, and in case they
// equate a variable with an expression, inline the definition of this variable
// into all following constraints.
func inline(_ originalConstraints: [Constraint],
canInline: (Constraint) -> Bool = { $0.complexity <= 20 },
simplifying shouldSimplify: Bool = true) -> [Constraint] {
// NB: It is safe to reuse this accross iterations.
let weakestAssumption = computeWeakestAssumptions(originalConstraints)
let simplifyExpr: (Expr) -> Expr = shouldSimplify ? simplify : { $0 }
let simplifyConstraint: (Constraint) -> Constraint = shouldSimplify ? simplify : { $0 }
var constraints = originalConstraints
while true {
var inlined: [Var: Expr] = [:]
var inlineForbidden = Set<Var>()
func subst(_ v: Var) -> Expr? {
if let replacement = inlined[v] {
return replacement
}
inlineForbidden.insert(v)
return nil
}
func tryInline(_ v: Var, _ originalExpr: Expr, assuming cond: BoolExpr) -> Bool {
guard !inlined.keys.contains(v),
weakestAssumption[v]! =>? cond else { return false }
let expr = simplifyExpr(substitute(originalExpr, using: subst))
// NB: The substitution above might have added the variable to inlineForbidden
guard !inlineForbidden.contains(v) else { return false }
inlined[v] = expr
return true
}
constraints = constraints.compactMap { constraint in
if canInline(constraint) {
let cond = constraint.assumption
switch constraint.expr {
case let .listEq(.var(v), expr),
let .listEq(expr, .var(v)):
if tryInline(.list(v), .list(expr), assuming: cond) { return nil }
case let .intEq(.var(v), expr),
let .intEq(expr, .var(v)):
if tryInline(.int(v), .int(expr), assuming: cond) { return nil }
case let .boolEq(.var(v), expr),
let .boolEq(expr, .var(v)):
if tryInline(.bool(v), .bool(expr), assuming: cond) { return nil }
default: break
}
}
return simplifyConstraint(substitute(constraint, using: subst))
}
if inlined.isEmpty { break }
}
return constraints
}
// Assertion instantiations produce patterns of the form:
// b4 = <cond>, b4
// This function tries to find those and inline the conditions.
public func inlineBoolVars(_ constraints: [Constraint]) -> [Constraint] {
return inline(constraints, canInline: {
switch $0 {
case .expr(.boolEq(.var(_), _), assuming: _, _, _): return true
case .expr(.boolEq(_, .var(_)), assuming: _, _, _): return true
default: return false
}
}, simplifying: false)
}
////////////////////////////////////////////////////////////////////////////////
// MARK: - Simplification
// Simplifies the constraint without any additional context. For example
// a subexpression [1, 2, 3][1] will get replaced by 2.
public func simplify(_ constraint: Constraint) -> Constraint {
switch constraint {
case let .expr(expr, assuming: cond, origin, stack):
return .expr(simplify(expr), assuming: simplify(cond), origin, stack)
}
}
public func simplify(_ genericExpr: Expr) -> Expr {
switch genericExpr {
case let .int(expr): return .int(simplify(expr))
case let .list(expr): return .list(simplify(expr))
case let .bool(expr): return .bool(simplify(expr))
case let .compound(expr): return .compound(simplify(expr))
}
}
public func simplify(_ expr: IntExpr) -> IntExpr {
func binaryOp(_ clhs: IntExpr, _ crhs: IntExpr,
_ f: (Int, Int) -> Int,
_ constructor: (IntExpr, IntExpr) -> IntExpr,
leftIdentity: Int? = nil,
rightIdentity: Int? = nil) -> IntExpr {
let (lhs, rhs) = (simplify(clhs), simplify(crhs))
if case let .literal(lhsValue) = lhs,
case let .literal(rhsValue) = rhs {
return .literal(f(lhsValue, rhsValue))
}
if let id = leftIdentity, case .literal(id) = lhs {
return rhs
}
if let id = rightIdentity, case .literal(id) = rhs {
return lhs
}
return constructor(lhs, rhs)
}
switch expr {
case .hole(_): return expr
case .var(_): return expr
case .literal(_): return expr
case let .length(of: clist):
let list = simplify(clist)
if case let .literal(elems) = list {
return .literal(elems.count)
}
return .length(of: list)
case let .element(offset, of: clist):
let list = simplify(clist)
if case let .literal(elems) = list {
let normalOffset = offset < 0 ? offset + elems.count : offset
if 0 <= normalOffset, normalOffset < elems.count,
let elem = elems[normalOffset] {
return elem
}
}
return .element(offset, of: list)
case let .add(clhs, crhs):
return binaryOp(clhs, crhs, +, IntExpr.add, leftIdentity: 0, rightIdentity: 0)
case let .sub(clhs, crhs):
return binaryOp(clhs, crhs, -, IntExpr.sub, rightIdentity: 0)
case let .mul(clhs, crhs):
return binaryOp(clhs, crhs, *, IntExpr.mul, leftIdentity: 1, rightIdentity: 1)
case let .div(clhs, crhs):
return binaryOp(clhs, crhs, /, IntExpr.div, rightIdentity: 1)
}
}
public func simplify(_ expr: ListExpr) -> ListExpr {
struct Break: Error {}
func tryBroadcast(_ lhs: [IntExpr?], _ rhs: [IntExpr?]) throws -> [IntExpr?] {
let paddedLhs = Array(repeating: 1, count: max(rhs.count - lhs.count, 0)) + lhs
let paddedRhs = Array(repeating: 1, count: max(lhs.count - rhs.count, 0)) + rhs
return try zip(paddedLhs, paddedRhs).map{ (l, r) in
if (l == nil || l == 1) { return r }
if (r == nil || r == 1) { return l }
if (r == l) { return l }
throw Break()
}
}
switch expr {
case .var(_): return expr
case let .literal(subexprs): return .literal(subexprs.map{ $0.map(simplify) })
case let .broadcast(clhs, crhs):
let (lhs, rhs) = (simplify(clhs), simplify(crhs))
if case let .literal(lhsElems) = lhs,
case let .literal(rhsElems) = rhs {
if let resultElems = try? tryBroadcast(lhsElems, rhsElems) {
return .literal(resultElems)
}
}
return .broadcast(lhs, rhs)
}
}
public func simplify(_ expr: BoolExpr) -> BoolExpr {
switch expr {
case .true: return expr
case .false: return expr
case .var(_): return expr
case let .not(.not(subexpr)): return simplify(subexpr)
case let .not(subexpr): return .not(simplify(subexpr))
// TODO(#20): Collapse and/or trees and filter out true/false
case let .and(subexprs): return .and(subexprs.map(simplify))
case let .or(subexprs): return .or(subexprs.map(simplify))
case let .intEq(lhs, rhs): return .intEq(simplify(lhs), simplify(rhs))
case let .intGt(lhs, rhs): return .intGt(simplify(lhs), simplify(rhs))
case let .intGe(lhs, rhs): return .intGe(simplify(lhs), simplify(rhs))
case let .intLt(lhs, rhs): return .intLt(simplify(lhs), simplify(rhs))
case let .intLe(lhs, rhs): return .intLe(simplify(lhs), simplify(rhs))
case let .listEq(lhs, rhs): return .listEq(simplify(lhs), simplify(rhs))
case let .boolEq(lhs, rhs): return .boolEq(simplify(lhs), simplify(rhs))
}
}
public func simplify(_ expr: CompoundExpr) -> CompoundExpr {
switch expr {
case let .tuple(subexprs): return .tuple(subexprs.map{ $0.map(simplify) })
}
}
////////////////////////////////////////////////////////////////////////////////
// MARK: - Complexity measure
// Returns an approximate measure of how hard to read the constraint will be when
// printed. In most cases it's equivalent to simply computing the number of nodes in
// the expression tree, but some rules don't conform to this specification.
extension Constraint {
var complexity: Int {
switch self {
case let .expr(expr, assuming: _, _, _): return expr.complexity
}
}
}
extension BoolExpr {
var complexity: Int {
switch self {
case .true: return 1
case .false: return 1
case .var(_): return 1
case let .not(subexpr): return 1 + subexpr.complexity
case let .and(subexprs): fallthrough
case let .or(subexprs): return 1 + subexprs.reduce(0, { $0 + $1.complexity })
case let .intEq(lhs, rhs): fallthrough
case let .intGt(lhs, rhs): fallthrough
case let .intGe(lhs, rhs): fallthrough
case let .intLt(lhs, rhs): fallthrough
case let .intLe(lhs, rhs):
return 1 + lhs.complexity + rhs.complexity
case let .listEq(lhs, rhs):
return 1 + lhs.complexity + rhs.complexity
case let .boolEq(lhs, rhs):
return 1 + lhs.complexity + rhs.complexity
}
}
}
extension IntExpr {
var complexity: Int {
switch self {
case .hole(_): return 1
case .var(_): return 1
case .literal(_): return 1
// NB: We don't add one, because both .rank and indexing does not increase
// the subjective complexity of the expression significantly
case let .length(of: list): return list.complexity
case let .element(_, of: list): return list.complexity
case let .add(lhs, rhs): fallthrough
case let .sub(lhs, rhs): fallthrough
case let .mul(lhs, rhs): fallthrough
case let .div(lhs, rhs):
return 1 + lhs.complexity + rhs.complexity
}
}
}
extension ListExpr {
var complexity: Int {
switch self {
case .var(_): return 1
// FIXME: If we changed the way we print list literals to e.g. explode one
// element per line then we could take a max instead of a sum here.
case let .literal(subexprs): return 1 + subexprs.reduce(0, { $0 + ($1?.complexity ?? 1) })
case let .broadcast(lhs, rhs): return 1 + lhs.complexity + rhs.complexity
}
}
}
extension CompoundExpr {
var complexity: Int {
switch self {
case let .tuple(elements): return 1 + elements.reduce(0, { $0 + ($1?.complexity ?? 1) })
}
}
}
extension Expr {
var complexity: Int {
switch self {
case let .int(expr): return expr.complexity
case let .bool(expr): return expr.complexity
case let .list(expr): return expr.complexity
case let .compound(expr): return expr.complexity
}
}
}
| apache-2.0 |
blockchain/My-Wallet-V3-iOS | Modules/FeatureForm/Sources/FeatureFormDomain/FormValidation.swift | 1 | 1379 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import ToolKit
extension FormQuestion {
var isValid: Bool {
let isValid: Bool
switch type {
case .singleSelection:
let selections = children.filter { $0.checked == true }
isValid = selections.count == 1 && selections.hasAllValidAnswers
case .multipleSelection:
let selections = children.filter { $0.checked == true }
isValid = selections.count >= 1 && selections.hasAllValidAnswers
case .openEnded:
if let regex = regex {
isValid = input.emptyIfNil ~= regex
} else {
isValid = input.isNilOrEmpty
}
}
return isValid
}
}
extension FormAnswer {
var isValid: Bool {
var isValid = checked == true || input.isNotNilOrEmpty
if let children = children {
isValid = isValid && children.hasAllValidAnswers
}
if let regex = regex {
isValid = isValid && input.emptyIfNil ~= regex
}
return isValid
}
}
extension Array where Element == FormAnswer {
var hasAllValidAnswers: Bool {
allSatisfy(\.isValid)
}
}
extension Array where Element == FormQuestion {
public var isValidForm: Bool {
allSatisfy(\.isValid)
}
}
| lgpl-3.0 |
proxpero/Placeholder | Placeholder/FileStorage.swift | 1 | 1256 | //
// FileStorage.swift
// Placeholder
//
// Created by Todd Olsen on 4/8/17.
// Copyright © 2017 proxpero. All rights reserved.
//
import Foundation
/// A class to manage storing and retrieving data from disk.
public struct FileStorage {
// The base URL.
private let baseURL: URL
/// Initialize with a baseURL, which has a default value of the document
/// directory in the user domain mask.
init(baseURL: URL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)) {
self.baseURL = baseURL
}
/// A subscript for reading and writing data at the address represented
/// by `key`. Setting a value of `nil` clears the cache for that `key`.
subscript(key: String) -> Data? {
get {
let url = baseURL.appendingPathComponent(key)
return try? Data(contentsOf: url)
}
set {
let url = baseURL.appendingPathComponent(key)
if let newValue = newValue {
_ = try? newValue.write(to: url)
} else {
// If `newValue` is `nil` then clear the cache.
_ = try? FileManager.default.removeItem(at: url)
}
}
}
}
| mit |
brentsimmons/Evergreen | Account/Sources/Account/FeedWrangler/FeedWranglerSubscription.swift | 1 | 505 | //
// FeedWranglerSubscription.swift
// Account
//
// Created by Jonathan Bennett on 2019-10-16.
// Copyright © 2019 Ranchero Software, LLC. All rights reserved.
//
import Foundation
import RSCore
import RSParser
struct FeedWranglerSubscription: Hashable, Codable {
let title: String
let feedID: Int
let feedURL: String
let siteURL: String?
enum CodingKeys: String, CodingKey {
case title = "title"
case feedID = "feed_id"
case feedURL = "feed_url"
case siteURL = "site_url"
}
}
| mit |
cubixlabs/GIST-Framework | GISTFramework/Classes/BaseClasses/BaseUIStackView.swift | 1 | 2855 | //
// BaseUIStackView.swift
// GISTFramework
//
// Created by Shoaib Abdul on 13/02/2017.
// Copyright © 2017 Social Cubix. All rights reserved.
//
import UIKit
/// BaseUIStackView is a subclass of UIStackView and implements BaseView. It has some extra proporties and support for SyncEngine.
@available(iOS 9.0, *)
open class BaseUIStackView: UIStackView, BaseView {
//MARK: - Properties
/// Overriden property to update spacing with ratio.
open override var spacing:CGFloat {
get {
return super.spacing;
}
set {
super.spacing = GISTUtility.convertToRatio(newValue, sizedForIPad: sizeForIPad);
}
}
/// Flag for whether to resize the values for iPad.
@IBInspectable open var sizeForIPad:Bool = GIST_CONFIG.sizeForIPad;
/// Background color key from Sync Engine.
@IBInspectable open var bgColorStyle:String? = nil {
didSet {
self.backgroundColor = SyncedColors.color(forKey: bgColorStyle);
}
}
/// Width of View Border.
@IBInspectable open var border:Int = 0 {
didSet {
if let borderCStyle:String = borderColorStyle {
self.addBorder(SyncedColors.color(forKey: borderCStyle), width: border)
}
}
}
/// Border color key from Sync Engine.
@IBInspectable open var borderColorStyle:String? = nil {
didSet {
if let borderCStyle:String = borderColorStyle {
self.addBorder(SyncedColors.color(forKey: borderCStyle), width: border)
}
}
}
/// Corner Radius for View.
@IBInspectable open var cornerRadius:Int = 0 {
didSet {
self.addRoundedCorners(GISTUtility.convertToRatio(CGFloat(cornerRadius), sizedForIPad: sizeForIPad));
}
}
/// Flag for making circle/rounded view.
@IBInspectable open var rounded:Bool = false {
didSet {
if rounded {
self.addRoundedCorners();
}
}
}
/// Flag for Drop Shadow.
@IBInspectable open var hasDropShadow:Bool = false {
didSet {
if (hasDropShadow) {
self.addDropShadow();
} else {
// TO HANDLER
}
}
}
//MARK: - Overridden Methods
/// Overridden method to setup/ initialize components.
override open func awakeFromNib() {
super.awakeFromNib();
} //F.E.
/// Overridden methed to update layout.
override open func layoutSubviews() {
super.layoutSubviews();
if rounded {
self.addRoundedCorners();
}
if (hasDropShadow) {
self.addDropShadow();
}
} //F.E.
} //CLS END
| agpl-3.0 |
oceanfive/swift | swift_two/swift_two/Classes/Model/HYStatusToolBarFrame.swift | 1 | 207 | //
// HYStatusToolBarFrame.swift
// swift_two
//
// Created by ocean on 16/6/21.
// Copyright © 2016年 ocean. All rights reserved.
//
import UIKit
class HYStatusToolBarFrame: NSObject {
}
| mit |
sora0077/RelayoutKit | RelayoutKit/TableView/TableController+Cell.swift | 1 | 9025 | //
// TableController+Cell.swift
// RelayoutKit
//
// Created by 林達也 on 2015/09/10.
// Copyright © 2015年 jp.sora0077. All rights reserved.
//
import Foundation
//MARK: Cell
extension TableController {
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let row = sections[indexPath.section].internalRows[indexPath.row]
row.setIndexPath(indexPath)
row.setSuperview(tableView)
return row.estimatedSize.height
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.size.height
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = sections[indexPath.section].internalRows[indexPath.row]
let clazz = row.dynamicType
let identifier = clazz.identifier
if !registeredCells.contains(identifier) {
clazz.register(tableView)
registeredCells.insert(identifier)
}
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
updateCell(cell, indexPath: indexPath, row: row)
return cell
}
private func updateCell(cell: UITableViewCell, indexPath: NSIndexPath, row: TableRowProtocolInternal) {
cell.indentationLevel = row.indentationLevel
cell.indentationWidth = row.indentationWidth
cell.accessoryType = row.accessoryType
cell.selectionStyle = row.selectionStyle
cell.selected = row.selected
cell.relayoutKit_row = Wrapper(row)
row.setRenderer(cell)
row.setSuperview(tableView)
row.setIndexPath(indexPath)
row.componentUpdate()
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.relayoutKit_defaultSeparatorInset == nil {
cell.relayoutKit_defaultSeparatorInset = Wrapper(cell.separatorInset)
}
if let row = cell.relayoutKit_row?.value {
func applySeparatorStyle(style: UITableViewCellSeparatorStyle) {
switch style {
case .None:
cell.separatorInset.right = tableView.frame.width - cell.separatorInset.left
default:
if let inset = row.separatorInset {
cell.separatorInset = inset
} else if let inset = cell.relayoutKit_defaultSeparatorInset?.value {
cell.separatorInset = inset
}
}
}
let prev = sections[indexPath.section].internalRows[safe: indexPath.row - 1]
let next = sections[indexPath.section].internalRows[safe: indexPath.row + 1]
if let style = prev?.nextSeparatorStyle {
applySeparatorStyle(style)
} else if let style = next?.previousSeparatorStyle {
applySeparatorStyle(style)
} else {
applySeparatorStyle(row.separatorStyle)
}
row.willDisplayCell()
}
}
func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let row = cell.relayoutKit_row?.value {
row.didEndDisplayingCell()
row.setRenderer(nil)
cell.relayoutKit_row = nil
}
}
func tableView(tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.indentationLevel
}
}
extension TableController {
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.willSelect(indexPath)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let row = sections[indexPath.section].internalRows[indexPath.row]
row.didSelect(indexPath)
if !row.selected {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
func tableView(tableView: UITableView, willDeselectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.willDeselect(indexPath)
}
func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
let row = sections[indexPath.section].internalRows[indexPath.row]
row.accessoryButtonTapped(indexPath)
}
}
//MARK: - Editing Table Rows
extension TableController {
func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.shouldIndentWhileEditing()
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.editingStyle
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.editActions()
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let row = sections[indexPath.section].internalRows[indexPath.row]
row.commit(editingStyle: editingStyle)
}
func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.titleForDeleteConfirmationButton
}
func tableView(tableView: UITableView, willBeginEditingRowAtIndexPath indexPath: NSIndexPath) {
let row = sections[indexPath.section].internalRows[indexPath.row]
row.willBeginEditingRow()
}
}
private extension TableController {
func row(indexPath: NSIndexPath) -> TableRowProtocolInternal {
return sections[indexPath.section].internalRows[indexPath.row]
}
func row(safe indexPath: NSIndexPath) -> TableRowProtocolInternal? {
return sections[safe: indexPath.section]?.internalRows[safe: indexPath.row]
}
}
extension TableController {
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let row = sections[indexPath.section].internalRows[indexPath.row]
return row.canMove
}
func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath {
let source = row(sourceIndexPath)
if let destination = row(safe: proposedDestinationIndexPath) {
if source.canMove && destination.canMove {
if source.willMove(to: destination) && destination.willMove(from: source) {
return proposedDestinationIndexPath
}
}
} else {
if source.canMove {
return proposedDestinationIndexPath
}
}
return sourceIndexPath
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let source = row(sourceIndexPath)
sections[sourceIndexPath.section].removeAtIndex(sourceIndexPath.row)
sections[destinationIndexPath.section].insert(source, atIndex: destinationIndexPath.row)
for (idx, row) in sections[sourceIndexPath.section].internalRows.enumerate() {
let indexPath = NSIndexPath(forRow: idx, inSection: sourceIndexPath.section)
row.setIndexPath(indexPath)
}
for (idx, row) in sections[destinationIndexPath.section].internalRows.enumerate() {
let indexPath = NSIndexPath(forRow: idx, inSection: destinationIndexPath.section)
row.setIndexPath(indexPath)
}
}
}
private func pindexPath(indexPath: NSIndexPath) -> String {
return "indexPath(row: \(indexPath.row), section: \(indexPath.section))"
}
| mit |
uasys/swift | validation-test/Sema/type_checker_crashers_fixed/rdar27017206.swift | 14 | 159 | // RUN: not %target-swift-frontend %s -typecheck
var str = "Hello"
String(str.characters.subscript(
str.characters.startIndex..<str.characters.endIndex))
| apache-2.0 |
Limon-O-O/Lego | Modules/Door/Door/WelcomeViewController.swift | 1 | 6715 | //
// WelcomeViewController.swift
// Door
//
// Created by Limon.F on 19/2/2017.
// Copyright © 2017 Limon.F. All rights reserved.
//
import UIKit
import EggKit
import RxSwift
import MonkeyKing
class WelcomeViewController: UIViewController {
var innateParams: [String: Any] = [:]
@IBOutlet private weak var loginButton: UIButton!
@IBOutlet private weak var registerButton: UIButton!
@IBOutlet private weak var weiboButton: UIButton!
@IBOutlet private weak var qqButton: UIButton!
@IBOutlet private weak var wechatButton: UIButton!
@IBOutlet private weak var phoneButton: UIButton!
@IBOutlet private weak var loginWayLabel: UILabel!
fileprivate var showStatusBar = false
fileprivate let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
title = "Welcome"
loginWayLabel.text = "select_login_way".egg.localized
weiboButton.setTitle("button.weibo_login".egg.localized, for: .normal)
qqButton.setTitle("button.qq_login".egg.localized, for: .normal)
wechatButton.setTitle("button.wechat_login".egg.localized, for: .normal)
phoneButton.setTitle("button.phone_login".egg.localized, for: .normal)
registerButton.setTitle("button.register_by_phone".egg.localized, for: .normal)
loginButton.rx.tap
.throttle(0.3, scheduler: MainScheduler.instance)
.subscribe(onNext: { [weak self] in
let accessToken = "002dS5ZGOoM5BCd78614ac1dJnIUWD"
let userID: Int = 007
DoorUserDefaults.accessToken = accessToken
DoorUserDefaults.userID = userID
let alertController = UIAlertController(title: nil, message: "登录成功", preferredStyle: .alert)
let action: UIAlertAction = UIAlertAction(title: "确定", style: .default) { _ in
let deliverParams: [String: Any] = [
"accessToken": accessToken,
"userID": userID
]
// 通过闭包回调出去,这样不用依赖 Main Project
(self?.innateParams["callbackAction"] as? ([String: Any]) -> Void)?(deliverParams)
}
alertController.addAction(action)
self?.present(alertController, animated: true, completion: nil)
})
.addDisposableTo(disposeBag)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let navigationBarHidden = (innateParams["navigationBarHidden"] as? Bool) ?? true
showStatusBar = !navigationBarHidden
navigationController?.setNavigationBarHidden(navigationBarHidden, animated: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 0.2) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
override var prefersStatusBarHidden : Bool {
return !showStatusBar
}
deinit {
print("WelcomeViewController Deinit")
}
}
// MARK: - Segue
extension WelcomeViewController: SegueHandlerType {
enum SegueIdentifier: String {
case showLogin
case showPhoneNumberPicker
}
@IBAction private func register(_ sender: UIButton) {
performSegue(withIdentifier: .showPhoneNumberPicker, sender: nil)
}
@IBAction private func login(_ sender: UIButton) {
performSegue(withIdentifier: .showLogin, sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
showStatusBar = true
setNeedsStatusBarAppearanceUpdate()
switch segueIdentifier(for: segue) {
case .showLogin:
let vc = segue.destination as? LoginViewController
vc?.innateParams = innateParams
case .showPhoneNumberPicker:
let vc = segue.destination as? PhoneNumberPickerViewController
vc?.innateParams = innateParams
}
}
}
// MARK: - Actions
extension WelcomeViewController {
private func login(platform: LoginPlatform, token: String, openID: String) {
UserProvider.request(.login(["": ""]))
.mapObject(type: LoginUser.self)
.observeOn(MainScheduler.asyncInstance)
.subscribe(onNext: { success in
}, onError: { error in
})
.addDisposableTo(disposeBag)
}
@IBAction private func qqLogin(_ sender: UIButton) {
let account = MonkeyKing.Account.qq(appID: Configure.Account.QQ.appID)
MonkeyKing.registerAccount(account)
MonkeyKing.oauth(for: .qq) { [weak self] info, response, error in
guard
let unwrappedInfo = info,
let token = unwrappedInfo["access_token"] as? String,
let openID = unwrappedInfo["openid"] as? String else {
return
}
self?.login(platform: .qq, token: token, openID: openID)
}
}
@IBAction private func weiboLogin(_ sender: UIButton) {
let account = MonkeyKing.Account.weibo(appID: Configure.Account.Weibo.appID, appKey: Configure.Account.Weibo.appKey, redirectURL: Configure.Account.Weibo.redirectURL)
MonkeyKing.registerAccount(account)
MonkeyKing.oauth(for: .weibo) { [weak self] info, response, error in
// App or Web: token & userID
guard
let unwrappedInfo = info,
let token = (unwrappedInfo["access_token"] as? String) ?? (unwrappedInfo["accessToken"] as? String),
let userID = (unwrappedInfo["uid"] as? String) ?? (unwrappedInfo["userID"] as? String) else {
return
}
self?.login(platform: .weibo, token: token, openID: userID)
}
}
@IBAction private func weChatLogin(_ sender: UIButton) {
let account = MonkeyKing.Account.weChat(appID: Configure.Account.Wechat.appID, appKey: Configure.Account.Wechat.appKey)
MonkeyKing.registerAccount(account)
MonkeyKing.oauth(for: .weChat) { [weak self] oauthInfo, response, error in
guard
let token = oauthInfo?["access_token"] as? String,
let userID = oauthInfo?["openid"] as? String else {
return
}
self?.login(platform: .weChat, token: token, openID: userID)
}
}
}
| mit |
cburrows/swift-protobuf | Sources/SwiftProtobuf/Message+JSONAdditions.swift | 1 | 5646 | // Sources/SwiftProtobuf/Message+JSONAdditions.swift - JSON format primitive types
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Extensions to `Message` to support JSON encoding/decoding.
///
// -----------------------------------------------------------------------------
import Foundation
/// JSON encoding and decoding methods for messages.
extension Message {
/// Returns a string containing the JSON serialization of the message.
///
/// Unlike binary encoding, presence of required fields is not enforced when
/// serializing to JSON.
///
/// - Returns: A string containing the JSON serialization of the message.
/// - Parameters:
/// - options: The JSONEncodingOptions to use.
/// - Throws: `JSONEncodingError` if encoding fails.
public func jsonString(
options: JSONEncodingOptions = JSONEncodingOptions()
) throws -> String {
if let m = self as? _CustomJSONCodable {
return try m.encodedJSONString(options: options)
}
let data = try jsonUTF8Data(options: options)
return String(data: data, encoding: String.Encoding.utf8)!
}
/// Returns a Data containing the UTF-8 JSON serialization of the message.
///
/// Unlike binary encoding, presence of required fields is not enforced when
/// serializing to JSON.
///
/// - Returns: A Data containing the JSON serialization of the message.
/// - Parameters:
/// - options: The JSONEncodingOptions to use.
/// - Throws: `JSONEncodingError` if encoding fails.
public func jsonUTF8Data(
options: JSONEncodingOptions = JSONEncodingOptions()
) throws -> Data {
if let m = self as? _CustomJSONCodable {
let string = try m.encodedJSONString(options: options)
let data = string.data(using: String.Encoding.utf8)! // Cannot fail!
return data
}
var visitor = try JSONEncodingVisitor(type: Self.self, options: options)
visitor.startObject(message: self)
try traverse(visitor: &visitor)
visitor.endObject()
return visitor.dataResult
}
/// Creates a new message by decoding the given string containing a
/// serialized message in JSON format.
///
/// - Parameter jsonString: The JSON-formatted string to decode.
/// - Parameter options: The JSONDecodingOptions to use.
/// - Throws: `JSONDecodingError` if decoding fails.
public init(
jsonString: String,
options: JSONDecodingOptions = JSONDecodingOptions()
) throws {
try self.init(jsonString: jsonString, extensions: nil, options: options)
}
/// Creates a new message by decoding the given string containing a
/// serialized message in JSON format.
///
/// - Parameter jsonString: The JSON-formatted string to decode.
/// - Parameter extensions: An ExtensionMap for looking up extensions by name
/// - Parameter options: The JSONDecodingOptions to use.
/// - Throws: `JSONDecodingError` if decoding fails.
public init(
jsonString: String,
extensions: ExtensionMap? = nil,
options: JSONDecodingOptions = JSONDecodingOptions()
) throws {
if jsonString.isEmpty {
throw JSONDecodingError.truncated
}
if let data = jsonString.data(using: String.Encoding.utf8) {
try self.init(jsonUTF8Data: data, extensions: extensions, options: options)
} else {
throw JSONDecodingError.truncated
}
}
/// Creates a new message by decoding the given `Data` containing a
/// serialized message in JSON format, interpreting the data as UTF-8 encoded
/// text.
///
/// - Parameter jsonUTF8Data: The JSON-formatted data to decode, represented
/// as UTF-8 encoded text.
/// - Parameter options: The JSONDecodingOptions to use.
/// - Throws: `JSONDecodingError` if decoding fails.
public init(
jsonUTF8Data: Data,
options: JSONDecodingOptions = JSONDecodingOptions()
) throws {
try self.init(jsonUTF8Data: jsonUTF8Data, extensions: nil, options: options)
}
/// Creates a new message by decoding the given `Data` containing a
/// serialized message in JSON format, interpreting the data as UTF-8 encoded
/// text.
///
/// - Parameter jsonUTF8Data: The JSON-formatted data to decode, represented
/// as UTF-8 encoded text.
/// - Parameter extensions: The extension map to use with this decode
/// - Parameter options: The JSONDecodingOptions to use.
/// - Throws: `JSONDecodingError` if decoding fails.
public init(
jsonUTF8Data: Data,
extensions: ExtensionMap? = nil,
options: JSONDecodingOptions = JSONDecodingOptions()
) throws {
self.init()
try jsonUTF8Data.withUnsafeBytes { (body: UnsafeRawBufferPointer) in
// Empty input is valid for binary, but not for JSON.
guard body.count > 0 else {
throw JSONDecodingError.truncated
}
var decoder = JSONDecoder(source: body, options: options,
messageType: Self.self, extensions: extensions)
if decoder.scanner.skipOptionalNull() {
if let customCodable = Self.self as? _CustomJSONCodable.Type,
let message = try customCodable.decodedFromJSONNull() {
self = message as! Self
} else {
throw JSONDecodingError.illegalNull
}
} else {
try decoder.decodeFullObject(message: &self)
}
if !decoder.scanner.complete {
throw JSONDecodingError.trailingGarbage
}
}
}
}
| apache-2.0 |
collegboi/DIT-Timetable-iOS | DIT-Timetable-today/TodayCellTableViewCell.swift | 1 | 616 | //
// TodayCellTableViewCell.swift
// DIT-Timetable-V2
//
// Created by Timothy Barnard on 14/09/2017.
// Copyright © 2017 Timothy Barnard. All rights reserved.
//
import UIKit
class TodayCellTableViewCell: UITableViewCell {
@IBOutlet weak var className: UILabel!
@IBOutlet weak var classStartTime: UILabel!
@IBOutlet weak var lectureName: UILabel!
func setupCell(timetable: Timetable) {
self.className.text = timetable.name
self.classStartTime.text = timetable.timeStart.convertToCurrentTimeFormat()
self.lectureName.text = timetable.room
}
}
| mit |
stowy/LayoutKit | Sources/Views/StackView.swift | 5 | 5831 | // Copyright 2016 LinkedIn Corp.
// 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.
import UIKit
/**
A view that stacks its subviews along a single axis.
It is similar to UIStackView except that it uses StackLayout instead of Auto Layout, which means layout is much faster.
Although StackView is faster than UIStackView, it still does layout on the main thread.
If you want to get the full benefit of LayoutKit, use StackLayout directly.
Unlike UIStackView, if you position StackView with Auto Layout, you must call invalidateIntrinsicContentSize on that StackView
whenever any of its subviews' intrinsic content sizes change (e.g. changing the text of a UILabel that is positioned by the StackView).
Otherwise, Auto Layout won't recompute the layout of the StackView.
Subviews MUST implement sizeThatFits so StackView can allocate space correctly.
If a subview uses Auto Layout, then the subview may implement sizeThatFits by calling systemLayoutSizeFittingSize.
*/
open class StackView: UIView {
/// The axis along which arranged views are stacked.
open let axis: Axis
/**
The distance in points between adjacent edges of sublayouts along the axis.
For Distribution.EqualSpacing, this is a minimum spacing. For all other distributions it is an exact spacing.
*/
open let spacing: CGFloat
/// The distribution of space along the stack's axis.
open let distribution: StackLayoutDistribution
/// The distance that the arranged views are inset from the stack view. Defaults to 0.
open let contentInsets: UIEdgeInsets
/// The stack's alignment inside its parent.
open let alignment: Alignment
/// The stack's flexibility.
open let flexibility: Flexibility?
private var arrangedSubviews: [UIView] = []
public init(axis: Axis,
spacing: CGFloat = 0,
distribution: StackLayoutDistribution = .leading,
contentInsets: UIEdgeInsets = .zero,
alignment: Alignment = .fill,
flexibility: Flexibility? = nil) {
self.axis = axis
self.spacing = spacing
self.distribution = distribution
self.contentInsets = contentInsets
self.alignment = alignment
self.flexibility = flexibility
super.init(frame: .zero)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
Adds a subview to the stack.
Subviews MUST implement sizeThatFits so StackView can allocate space correctly.
If a subview uses Auto Layout, then the subview can implement sizeThatFits by calling systemLayoutSizeFittingSize.
*/
open func addArrangedSubviews(_ subviews: [UIView]) {
arrangedSubviews.append(contentsOf: subviews)
for subview in subviews {
addSubview(subview)
}
invalidateIntrinsicContentSize()
setNeedsLayout()
}
/**
Deletes all subviews from the stack.
*/
open func removeArrangedSubviews() {
for subview in arrangedSubviews {
subview.removeFromSuperview()
}
arrangedSubviews.removeAll()
invalidateIntrinsicContentSize()
setNeedsLayout()
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
return stackLayout.measurement(within: size).size
}
open override var intrinsicContentSize: CGSize {
return sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
}
open override func layoutSubviews() {
stackLayout.measurement(within: bounds.size).arrangement(within: bounds).makeViews(in: self)
}
private var stackLayout: Layout {
let sublayouts = arrangedSubviews.map { view -> Layout in
return ViewLayout(view: view)
}
let stack = StackLayout(
axis: axis,
spacing: spacing,
distribution: distribution,
alignment: alignment,
flexibility: flexibility,
sublayouts: sublayouts,
config: nil)
return InsetLayout(insets: contentInsets, sublayout: stack)
}
}
/// Wraps a UIView so that it conforms to the Layout protocol.
private struct ViewLayout: ConfigurableLayout {
let needsView = true
let view: UIView
let viewReuseId: String? = nil
func measurement(within maxSize: CGSize) -> LayoutMeasurement {
let size = view.sizeThatFits(maxSize)
return LayoutMeasurement(layout: self, size: size, maxSize: maxSize, sublayouts: [])
}
func arrangement(within rect: CGRect, measurement: LayoutMeasurement) -> LayoutArrangement {
return LayoutArrangement(layout: self, frame: rect, sublayouts: [])
}
func makeView() -> UIView {
return view
}
func configure(view: UIView) {
// Nothing to configure.
}
var flexibility: Flexibility {
let horizontal = flexForAxis(.horizontal)
let vertical = flexForAxis(.vertical)
return Flexibility(horizontal: horizontal, vertical: vertical)
}
private func flexForAxis(_ axis: UILayoutConstraintAxis) -> Flexibility.Flex {
switch view.contentHuggingPriority(for: .horizontal) {
case UILayoutPriorityRequired:
return nil
case let priority:
return -Int32(priority)
}
}
}
| apache-2.0 |
linhaosunny/smallGifts | 小礼品/小礼品/Classes/Module/Me/Chat/ViewModels/VoiceChatCellViewModel.swift | 1 | 1324 | //
// VoiceChatCellViewModel.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/28.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
fileprivate let voiceCellWidth:CGFloat = 80.0
fileprivate let voiceCellHeight:CGFloat = 45.0
class VoiceChatCellViewModel: BaseChatCellViewModel {
var voiceStatus:RecordStatus?
var voicebackImage:UIImage?
var voicebackHightLightImage:UIImage?
var voiceTimeLabelFont:UIFont?
var voiceTimeLabelText:String?
init(withVoiceMessage msg: VoiceMessage) {
super.init(withMsgModel: msg as MessageModel)
if viewLocation == .right {
voicebackImage = #imageLiteral(resourceName: "SenderTextNodeBkg")
voicebackHightLightImage = #imageLiteral(resourceName: "SenderTextNodeBkgHL")
}
else{
voicebackImage = #imageLiteral(resourceName: "ReceiverTextNodeBkg")
voicebackHightLightImage = #imageLiteral(resourceName: "ReceiverTextNodeBkgHL")
}
voiceTimeLabelFont = fontSize14
voiceTimeLabelText = String(format: "%.0lf\"\n", msg.time)
voiceStatus = msg.status
viewFrame.contentSize = CGSize(width: voiceCellWidth, height: voiceCellHeight)
viewFrame.height += viewFrame.contentSize.height
}
}
| mit |
powerytg/Accented | Accented/UI/Home/Stream/Models/StreamState.swift | 1 | 428 | //
// StreamState.swift
// Accented
//
// Created by Tiangong You on 5/1/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
class StreamState: NSObject {
// Whether the stream is refreshing
var refreshing : Bool = false
// Whether the stream is scrolling
var scrolling : Bool = false
// Whether the stream is loading its content
var loading : Bool = false
}
| mit |
mnewmedia/cordova-plugin-file-sync | src/ios/FSOptions.swift | 1 | 499 | struct FSOptions {
let pathRelease: NSURL
let pathManifest: NSURL
let pathRemoteDir: NSURL
let pathLocalDir: NSURL
let pathUpload: NSURL
let errorCode: Int
// TODO
/*
init(jsOptions: Dictionary<String, String>?) {
guard jsOptions != nil else {
self.errorCode = 7
return
}
self.pathManifest = jsOptions["pathManifest"]
guard self.pathManifest = jsOptions["pathManifest"] else {
}
}
*/
}
| gpl-3.0 |
jay0420/jigsaw | JKPinTu-Swift/Util/Extension/UIKit/JKUIViewExtension.swift | 1 | 1405 | //
// JKUIViewExtension.swift
// JKPinTu-Swift
//
// Created by bingjie-macbookpro on 15/12/15.
// Copyright © 2015年 Bingjie. All rights reserved.
//
import Foundation
import UIKit
extension UIView
{
public func left()->CGFloat{
return self.frame.origin.x
}
public func right()->CGFloat{
return self.frame.origin.x + self.frame.size.width
}
public func top()->CGFloat{
return self.frame.origin.y
}
public func bottom()->CGFloat{
return self.frame.origin.y + self.frame.size.height
}
public func width()->CGFloat{
return self.frame.size.width
}
public func height()->CGFloat{
return self.frame.size.height
}
public func addTapGesturesTarget(_ target:AnyObject, action selector:Selector){
self.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer.init(target: target, action: selector)
tapGesture.numberOfTapsRequired = 1
self.addGestureRecognizer(tapGesture)
}
public func removeAllSubviews(){
while (self.subviews.count != 0)
{
let child = self.subviews.last
child!.removeFromSuperview()
}
}
public func makeSubviewRandomColor(){
for view in self.subviews{
view.backgroundColor = UIColor.randomColor()
}
}
}
| mit |
frederik-jacques/UIFont-Enumerate | Pod/Classes/UIFont_Enumerate.swift | 1 | 737 | //
// UIFont-Enumerate.swift
//
// Created by Frederik Jacques on 28/05/15.
// Copyright (c) 2015 the-nerd. All rights reserved.
//
import UIKit
public extension UIFont {
public class func enumerateFonts(){
println("[UIFont] Start enumerating \(UIFont.familyNames().count) font families")
for( i, fontFamily ) in enumerate(UIFont.familyNames()) {
println("\(i+1). Font family = \(fontFamily as! String)");
for( j, fontName ) in enumerate(UIFont.fontNamesForFamilyName( fontFamily as! String )) {
println("- \(j+1)) Font name = \(fontName as! String)");
}
println("\n");
}
println("[UIFont] End enumerating fonts")
}
}
| mit |
Narsail/relaykit | Tests/iOS/SampleMessageSpec.swift | 1 | 728 | //
// SampleMessageSpec.swift
// RelayKit
//
// Created by David Moeller on 17.09.17.
//Copyright © 2017 David Moeller. All rights reserved.
//
import Quick
import Nimble
class SampleMessageSpec: QuickSpec {
override func spec() {
describe("create a Sample Message") {
var message: SampleMessage!
beforeEach {
message = SampleMessage(description: "Test Message")
}
it("encode and decode it") {
let data = message.encode()
expect((try! SampleMessage.decode(data)).description).to(equal(message.description))
}
}
}
}
| mit |
symentis/Corridor | Sources/Resolver.swift | 1 | 5551 | //
// Resolver.swift
// Corridor
//
// Created by Elmar Kretzer on 06.08.17.
// Copyright © 2017 Elmar Kretzer. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// --------------------------------------------------------------------------------
// MARK: - Resolver
//
// TL;DR:
// The resolver resolves access to the context for a given Source and Context.
// --------------------------------------------------------------------------------
/// Will be created with
/// - a generic type `S` a.k.a the Source that resolves.
/// - a generic type `C` a.k.a the Context protocol that we are resolving from.
public struct Resolver<S, C>: CustomStringConvertible where S: HasContext {
/// The typealias for the Context Protocol in your app.
public typealias Context = C
/// The typeaias for the Source that holds the resolver.
public typealias Source = S
/// The stored context which is used to access the injected types.
public private(set) var context: C
/// Inititializer needs a actual implementation of the Context protocol.
/// example usage:
///
/// static var mock: Resolver<Self, AppContext> {
/// return Resolver(context: MockContext())
/// }
///
public init(context: C) {
self.context = context
}
/// A public function to swap the Context for e.g. mocks
public mutating func apply(_ context: C) {
self.context = context
}
// --------------------------------------------------------------------------------
// MARK: - Subscripting a.k.a Resolving
//
// TL:DR;
// Subscripts are used to provide a config-ish access to injected values
// on a protocol level.
//
// The examples will use HasInstanceAppContext
// which is a protocol to pin the Context typealias for convenience.
// protocol HasInstanceAppContext: HasInstanceContext where Self.Context == AppContext {}
// --------------------------------------------------------------------------------
/// Subscripting any regular Type from the Context.
/// This basic subscribt can be seen as an eqivalent to extract on a Coreader
/// Example usage:
///
/// extension HasInstanceAppContext {
///
/// var now: Date {
/// return resolve[\.now]
/// }
/// }
///
public subscript<D>(_ k: KeyPath<C, D>) -> D {
return context[keyPath: k]
}
/// Subscripting an Type that conforms to `HasInstanceContext` from the Context.
/// This subscript can be seen as an eqivalent to extend on a Coreader
/// This will be called when the Type D implements HasInstanceContext,
/// which will result in passing on the context.
/// Example usage:
///
/// extension HasInstanceAppContext {
///
/// /// Api itself implements HasInstanceAppContext
/// var api: Api {
/// return resolve[\.api]
/// }
/// }
///
public subscript<D>(_ k: KeyPath<C, D>) -> D where D: HasInstanceContext, D.Context == C {
var d = context[keyPath: k]
d.resolve.apply(context)
return d
}
/// Subscripting an Type that conforms to `HasStaticContext` from the Context.
/// This subscript can be seen as an eqivalent to extend on a Coreader
/// This will be called when the Type D implements HasStaticContext,
/// which will result in passing on the context.
public subscript<D>(_ k: KeyPath<C, D>) -> D where D: HasStaticContext, D.Context == C {
D.resolve.apply(context)
return context[keyPath: k]
}
/// Subscripting an Type that conforms to `HasInstanceContext` from the Context.
/// This is used to provide on-the-fly context passing to types that are not
/// defined in the context.
/// e.g. viewmodels in a controller
///
/// extension HasInstanceAppContext where Source == MyViewController {
/// var myModel: MyModel {
/// return resolve[MyModel()]
/// }
/// }
///
/// class MyViewController: HasInstanceAppContext {
/// var resolve = `default`
/// lazy var model: MyModel = { myModel }()
/// }
///
public subscript<D>(_ d: D) -> D where D: HasInstanceContext, D.Context == C {
var dx = d
dx.resolve.apply(context)
return dx
}
// --------------------------------------------------------------------------------
// MARK: - CustomStringConvertible
// --------------------------------------------------------------------------------
public var description: String {
return "Resolver with \(context)"
}
}
| mit |
letzgro/GooglePlacesPicker | Classes/GooglePlacesPresentationAnimationController.swift | 1 | 2998 | //
// GooglePlacesPresentationAnimationController.swift
//
// Created by Ihor Rapalyuk on 2/3/16.
// Copyright © 2016 Lezgro. All rights reserved.
//
import UIKit
open class GooglePlacesPresentationAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
let isPresenting: Bool
let duration: TimeInterval = 0.5
init(isPresenting: Bool) {
self.isPresenting = isPresenting
super.init()
}
//MARK UIViewControllerAnimatedTransitioning methods
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return self.duration
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if isPresenting {
self.animatePresentationWithTransitionContext(transitionContext)
} else {
self.animateDismissalWithTransitionContext(transitionContext)
}
}
//MARK Helper methods
fileprivate func animatePresentationWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
let presentedController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let presentedControllerView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
// Position the presented view off the top of the container view
presentedControllerView.frame = transitionContext.finalFrame(for: presentedController)
presentedControllerView.center.y -= transitionContext.containerView.bounds.size.height
transitionContext.containerView.addSubview(presentedControllerView)
self.animateWithPresentedControllerView(presentedControllerView, andContainerView: transitionContext.containerView
, andTransitionContext: transitionContext)
}
fileprivate func animateDismissalWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
guard let presentedControllerView = transitionContext.view(forKey: UITransitionContextViewKey.from) else {
return
}
self.animateWithPresentedControllerView(presentedControllerView, andContainerView: transitionContext.containerView
, andTransitionContext: transitionContext)
}
fileprivate func animateWithPresentedControllerView(_ presentedControllerView: UIView, andContainerView containerView: UIView, andTransitionContext transitionContext: UIViewControllerContextTransitioning) {
// Animate the presented view off the bottom of the view
UIView.animate(withDuration: self.duration, delay: 0.0, usingSpringWithDamping: 1.0,
initialSpringVelocity: 0.0, options: .allowUserInteraction, animations: {
presentedControllerView.center.y += containerView.bounds.size.height
}, completion: {(completed: Bool) -> Void in
transitionContext.completeTransition(completed)
})
}
}
| mit |
realDogbert/myScore | myScore/CourseManager.swift | 1 | 1228 | //
// CourseManager.swift
// myScore
//
// Created by Frank on 21.07.14.
// Copyright (c) 2014 Frank von Eitzen. All rights reserved.
//
import UIKit
import CoreData
var manager = CourseManager()
struct CourseManager {
var context:NSManagedObjectContext!
init() {
var appDel = (UIApplication.sharedApplication().delegate as! AppDelegate)
//self.context = appDel.managedObjectContext
}
func getCourseByName(name: String) -> Course {
// Ebersberg Sepp Maier
var holes = [
Hole(number: 1, par: 3, length: 128, average:4),
Hole(number: 2, par: 4, length: 237, average:5),
Hole(number: 3, par: 3, length: 152, average:4),
Hole(number: 4, par: 4, length: 329, average:8),
Hole(number: 5, par: 3, length: 104, average:3),
Hole(number: 6, par: 3, length: 165, average:4),
Hole(number: 7, par: 4, length: 280, average:5),
Hole(number: 8, par: 3, length: 113, average:4),
Hole(number: 9, par: 3, length: 91, average:4)
]
var current = Course(name: "Ebersberg Sepp Maier", holes: holes)
return current
}
}
| mit |
Bygo/BGChatBotMessaging-iOS | Example/Pods/BGMessaging/BGMessaging/Classes/Views/BGMessagingCollectionViewCellOutgoing.swift | 2 | 807 | //
// BGMessagingCollectionViewCellOutgoing.swift
// Pods
//
// Created by Nicholas Garfield on 13/6/16.
//
//
import UIKit
public class BGMessagingCollectionViewCellOutgoing: BGMessagingCollectionViewCell {
override func configure() {
super.configure()
// bubbleContainer.backgroundColor = UIColor.bg_outgoingMessageBubbleColor()
messageTextLabel.textColor = UIColor.bg_incomingMessageTextColor()
}
// public override func layoutSubviews() {
// super.layoutSubviews()
// let maskLayer = CAShapeLayer()
// maskLayer.path = UIBezierPath(roundedRect: bubbleContainer.bounds, byRoundingCorners: [.TopLeft, .TopRight, .BottomLeft], cornerRadii: CGSizeMake(16.0, 16.0)).CGPath
// bubbleContainer.layer.mask = maskLayer
// }
}
| mit |
BlurredSoftware/BSWInterfaceKit | Sources/BSWInterfaceKit/SwiftUI/AsyncStateView.swift | 1 | 2729 |
#if canImport(SwiftUI)
import SwiftUI
@available(iOS 14, *)
public protocol ViewDataInitiable {
associatedtype Data
init(data: Data)
}
/*
Use this view like this:
```
AsyncStateView<ProductDetailsView>(
model: AsyncStateModel(
generator: Current.productDetailFactory(productID)
)
)
```
*/
@available(iOS 14, *)
public struct AsyncStateView<HostedView: View & ViewDataInitiable>: View {
@StateObject public var model: AsyncStateModel<HostedView.Data>
public var body: some View {
switch model.state {
case .loading:
ProgressView()
case .loaded(let data):
HostedView(data: data)
case .error(let error):
ErrorView(error: error, onRetry: {
self.model.fetchData()
})
}
}
}
import Combine
@available(iOS 14, *)
private extension AsyncStateView {
struct ErrorView: View {
let error: Swift.Error
let onRetry: () -> ()
var body: some View {
VStack(spacing: 16) {
Text(error.localizedDescription)
.multilineTextAlignment(.center)
Button("Retry") {
self.onRetry()
}
}
.padding()
}
}
}
@available(iOS 14, *)
public class AsyncStateModel<T>: ObservableObject {
public typealias Generator = () -> Combine.AnyPublisher<T, Swift.Error>
@Published public var state: State<T>
public let generator: Generator
public init(generator: @escaping Generator) {
self.generator = generator
self.state = .loading
fetchData()
}
init(state: State<T>) {
self.state = state
self.generator = { Future.never().eraseToAnyPublisher() }
fetchData()
}
deinit {
cancellable?.cancel()
}
private var cancellable: AnyCancellable!
func fetchData() {
self.state = .loading
let fetch = self.generator()
cancellable = fetch.receive(on: DispatchQueue.main).sink(receiveCompletion: { (completion) in
switch completion {
case .failure(let error):
self.state = .error(error)
case .finished:
break
}
self.cancellable.cancel()
self.cancellable = nil
}, receiveValue: {
self.state = .loaded($0)
})
}
public enum State<T> {
case loading
case loaded(T)
case error(Swift.Error)
}
}
@available(iOS 14, *)
private extension Future {
static func never() -> Future<Output, Failure> {
return .init { (_) in }
}
}
#endif
| mit |
gaurav1981/SwiftStructures | Source/Factories/Trie.swift | 1 | 3345 | //
// Trie.swift
// SwiftStructures
//
// Created by Wayne Bishop on 10/14/14.
// Copyright (c) 2014 Arbutus Software Inc. All rights reserved.
//
import Foundation
public class Trie {
private var root: TrieNode!
init(){
root = TrieNode()
}
//builds a tree hierarchy of dictionary content
func append(word keyword: String) {
//trivial case
guard keyword.length > 0 else {
return
}
var current: TrieNode = root
while keyword.length != current.level {
var childToUse: TrieNode!
let searchKey = keyword.substring(to: current.level + 1)
//print("current has \(current.children.count) children..")
//iterate through child nodes
for child in current.children {
if (child.key == searchKey) {
childToUse = child
break
}
}
//new node
if childToUse == nil {
childToUse = TrieNode()
childToUse.key = searchKey
childToUse.level = current.level + 1
current.children.append(childToUse)
}
current = childToUse
} //end while
//final end of word check
if (keyword.length == current.level) {
current.isFinal = true
print("end of word reached!")
return
}
} //end function
//find words based on the prefix
func search(forWord keyword: String) -> Array<String>! {
//trivial case
guard keyword.length > 0 else {
return nil
}
var current: TrieNode = root
var wordList = Array<String>()
while keyword.length != current.level {
var childToUse: TrieNode!
let searchKey = keyword.substring(to: current.level + 1)
//print("looking for prefix: \(searchKey)..")
//iterate through any child nodes
for child in current.children {
if (child.key == searchKey) {
childToUse = child
current = childToUse
break
}
}
if childToUse == nil {
return nil
}
} //end while
//retrieve the keyword and any descendants
if ((current.key == keyword) && (current.isFinal)) {
wordList.append(current.key)
}
//include only children that are words
for child in current.children {
if (child.isFinal == true) {
wordList.append(child.key)
}
}
return wordList
} //end function
}
| mit |
ngageoint/mage-ios | Mage/Extensions/UIApplicationTopController.swift | 1 | 884 | //
// UIApplicationTopController.swift
// MAGE
//
// Created by Daniel Barela on 11/19/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
extension UIApplication {
@objc class func getTopViewController(base: UIViewController? = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return getTopViewController(base: nav.visibleViewController)
} else if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
return getTopViewController(base: selected)
} else if let presented = base?.presentedViewController {
return getTopViewController(base: presented)
}
return base
}
}
| apache-2.0 |
IngmarStein/swift | validation-test/compiler_crashers_fixed/26303-llvm-llvm-unreachable-internal.swift | 4 | 580 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: %target-swift-frontend %s -emit-silgen
// Test case submitted to project by https://github.com/airspeedswift (airspeedswift)
struct S<T> {
var a: [T] = []
}
extension S {
init(other: [T]) {
a = other
}
}
| apache-2.0 |
teambition/GrowingTextView | GrowingTextViewExample/MessageLabel.swift | 1 | 418 | //
// MessageLabel.swift
// GrowingTextViewExample
//
// Created by 洪鑫 on 16/2/17.
// Copyright © 2016年 Teambition. All rights reserved.
//
import UIKit
let kMessageLabelPadding: CGFloat = 10
class MessageLabel: UILabel {
override func draw(_ rect: CGRect) {
super.drawText(in: rect.inset(by: UIEdgeInsets(top: 0, left: kMessageLabelPadding, bottom: 0, right: kMessageLabelPadding)))
}
}
| mit |
leeaken/LTMap | LTMap/LTLocationMap/LocationManager/LTGeocodeManager.swift | 1 | 3204 | //
// LTGeocodeManager.swift
// LTMap
//
// POI地理位置搜索
// 国内调用高德poi,国外使用谷歌webservice
// Created by aken on 2017/6/2.
// Copyright © 2017年 LTMap. All rights reserved.
//
import UIKit
class LTGeocodeManager {
fileprivate var dataCompletion:SearchCompletion?
fileprivate var searchManager:LTGeocodeProtocol?
private var location:CLLocationCoordinate2D?
/// 默认构造是用国内高德poi
init(){
searchManager = createSearchCountry(type: .LTCN)
}
/// 通过构造参数经纬度来初始化poi搜索,国内使用高德,国外使用谷歌
///
/// - Parameter coordinate: 经纬度
init(coordinate:CLLocationCoordinate2D) {
location = coordinate
if isInChina() {
searchManager = createSearchCountry(type: .LTCN)
} else {
searchManager = createSearchCountry(type: .LTAbroad)
}
}
/// MARK: -- 私有方法
private func isInChina() ->Bool {
// 默认为中国
if !CLLocationCoordinate2DIsValid(location!) {
return true
}
return AMapLocationDataAvailableForCoordinate(location!)
}
private func createSearchCountry(type:LTGeocodeType) -> LTGeocodeProtocol? {
switch type {
case .LTCN:
return LTGaodeGeocode()
case.LTAbroad:
return LTGoogleGeocode()
}
}
func switchSearchCountry(type:LTGeocodeType) {
// 如果当前type已经创建了,则直接返回
if searchManager?.type != type {
searchManager = createSearchCountry(type:type)
}
}
/// MARK: -- 公共方法
func searchReGeocodeWithCoordinate(coordinate: CLLocationCoordinate2D,completion:@escaping(SearchCompletion)) {
if !CLLocationCoordinate2DIsValid(coordinate) {
print("输入的经纬度不合法")
return
}
searchManager?.searchReGeocodeWithCoordinate(coordinate: coordinate, completion: completion)
}
func searchNearbyWithCoordinate(param:LTPOISearchAroundArg,completion:@escaping(SearchCompletion)) {
guard let coordinate = param.location,CLLocationCoordinate2DIsValid(coordinate) else {
print("输入的经纬度不合法")
return
}
searchManager?.searchNearbyWithCoordinate(param: param, completion: completion)
}
func searchInputTipsAutoCompletionWithKeyword(param:LTPOISearchAroundArg,completion:@escaping(SearchCompletion)) {
searchManager?.searchInputTipsAutoCompletionWithKeyword(param: param, completion: completion)
}
func searchPlaceWithKeyWord(param:LTPOISearchAroundArg,completion:@escaping(SearchCompletion)) {
searchManager?.searchPlaceWithKeyWord(param: param, completion: completion)
}
}
| mit |
prometheon/MLNimbleNinja | Nimble Ninja/MLCloudGenerator.swift | 2 | 1431 | //
// MLCloudGenerator.swift
// Nimble Ninja
//
// Created by Michael Leech on 1/30/15.
// Copyright (c) 2015 CrashCourseCode. All rights reserved.
//
import Foundation
import SpriteKit
class MLCloudGenerator: SKSpriteNode {
let CLOUD_WIDTH: CGFloat = 125.0
let CLOUD_HEIGHT: CGFloat = 55.0
var generationTimer: NSTimer!
func populate(num: Int) {
for var i = 0; i < num; i++ {
let cloud = MLCloud(size: CGSizeMake(CLOUD_WIDTH, CLOUD_HEIGHT))
let x = CGFloat(arc4random_uniform(UInt32(size.width))) - size.width/2
let y = CGFloat(arc4random_uniform(UInt32(size.height))) - size.height/2
cloud.position = CGPointMake(x, y)
cloud.zPosition = -1
addChild(cloud)
}
}
func startGeneratingWithSpawnTime(seconds: NSTimeInterval) {
generationTimer = NSTimer.scheduledTimerWithTimeInterval(seconds, target: self, selector: "generateCloud", userInfo: nil, repeats: true)
}
func stopGenerating() {
generationTimer.invalidate()
}
func generateCloud() {
let x = size.width/2 + CLOUD_WIDTH/2
let y = CGFloat(arc4random_uniform(UInt32(size.height))) - size.height/2
let cloud = MLCloud(size: CGSizeMake(CLOUD_WIDTH, CLOUD_HEIGHT))
cloud.position = CGPointMake(x, y)
cloud.zPosition = -1
addChild(cloud)
}
} | mit |
lukejmann/FBLA2017 | Pods/Instructions/Sources/Protocols/Public/CoachMarkSkipView.swift | 1 | 1655 | // CoachMarkSkipView.swift
//
// Copyright (c) 2015, 2016 Frédéric Maquin <fred@ephread.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 UIKit
/// A protocol to which all the "skip views" must conform.
public protocol CoachMarkSkipView : class {
/// The control that will trigger the stop, in the display flow.
var skipControl: UIControl? { get }
var asView: UIView? { get }
}
public extension CoachMarkSkipView {
public var skipControl: UIControl? {
return nil
}
}
public extension CoachMarkSkipView where Self: UIView {
public var asView: UIView? {
return self
}
}
| mit |
ps12138/dribbbleAPI | Model/Comment.swift | 1 | 1376 | //
// Comment.swift
// DribbbleModuleFramework
//
// Created by PSL on 12/7/16.
// Copyright © 2016 PSL. All rights reserved.
//
import Foundation
open class Comment {
open let id: Int
open var body: String
open let likes_count: Int
open let likes_url: String
open let created_at: String
open let updated_at: String
open let user: User
open var commentBody: CommentBody?
init?(dict: Dictionary<String, AnyObject>?) {
guard
let id = dict?[CommentKey.id] as? Int,
let body = dict?[CommentKey.body] as? String,
let likes_count = dict?[CommentKey.likes_count] as? Int,
let likes_url = dict?[CommentKey.likes_url] as? String,
let created_at = dict?[CommentKey.created_at] as? String,
let updated_at = dict?[CommentKey.updated_at] as? String,
let user = User(dict: dict?[ShotKey.user] as? Dictionary<String, AnyObject>)
else {
return nil
}
self.id = id
self.body = body
self.likes_count = likes_count
self.likes_url = likes_url
self.created_at = created_at
self.updated_at = updated_at
self.user = user
}
public func translateBody(dict: Dictionary<String, AnyObject>?) {
self.commentBody = CommentBody(dict: dict)
}
}
| mit |
YouareMylovelyGirl/Sina-Weibo | 新浪微博/新浪微博/AppDelegate.swift | 1 | 2703 | //
// AppDelegate.swift
// 新浪微博
//
// Created by 阳光 on 2017/6/5.
// Copyright © 2017年 YG. All rights reserved.
//
import UIKit
//iOS 10推出用户提醒
import UserNotifications
import SVProgressHUD
import AFNetworking
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//应用程序额外设置
setupAdditions()
//设置启动
window = UIWindow()
window?.backgroundColor = UIColor.white
window?.rootViewController = MainTabBarController()
window?.makeKeyAndVisible()
//异步加载网络数据
loadAppInfo()
return true
}
}
//MARK: - 设置应用程序额外信息
extension AppDelegate {
fileprivate func setupAdditions() {
//1. 设置 SVPregressHUD 最小接触时间
SVProgressHUD.setMinimumDismissTimeInterval(1.0)
//2. 设置网络加载指示器
AFNetworkActivityIndicatorManager.shared().isEnabled = true
//3. 设置用户授权显示通知
//最新用户提示 是检测设备版本, 如果是10.0 以上
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound, .carPlay]) { (success, error) in
print("授权" + (success ? "成功" : "失败")
)}
} else {
//取得用户授权显示通知"上方的提示条/ 声音/ BadgeNumber" 过期方法 10.0 一下
let notifySetting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
//这是一个单利
UIApplication.shared.registerUserNotificationSettings(notifySetting)
}
}
}
//从服务器加载应用程序信息
extension AppDelegate {
fileprivate func loadAppInfo() {
//1. 模拟异步
DispatchQueue.global().async {
//1> url
let url = Bundle.main.url(forResource: "Main.json", withExtension: nil)
//2> data
let data = NSData(contentsOf: url!)
//3> 写入磁盘
let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let jsonPath = (docDir as NSString).appendingPathComponent("Main.json")
//直接保存在沙盒, 等待下一次程序启动
data?.write(toFile: jsonPath, atomically: true)
print("应用程序加载完毕\(jsonPath)")
}
}
}
| apache-2.0 |
jloloew/IMSOHAPPYRIGHTNOW | IMSOHAPPYRIGHTNOW/AppDelegate.swift | 1 | 2059 | //
// AppDelegate.swift
// IMSOHAPPYRIGHTNOW
//
// Created by Justin Loew on 9/22/15.
// Copyright © 2015 Justin Loew. 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:.
}
}
| gpl-3.0 |
warnerbros/cpe-manifest-ios-data | Source/Network/ProductAPIUtil.swift | 1 | 958 | //
// ProductAPIUtil.swift
//
import Foundation
public protocol ProductAPIUtil {
static var APIDomain: String { get }
static var APINamespace: String { get }
var featureAPIID: String? { get set }
var productCategories: [ProductCategory]? { get set }
func getProductFrameTimes(completion: @escaping (_ frameTimes: [Double]?) -> Void) -> URLSessionDataTask?
func getProductCategories(completion: ((_ productCategories: [ProductCategory]?) -> Void)?) -> URLSessionDataTask?
func getFrameProducts(_ frameTime: Double, completion: @escaping (_ products: [ProductItem]?) -> Void) -> URLSessionDataTask?
func getCategoryProducts(_ categoryID: String?, completion: @escaping (_ products: [ProductItem]?) -> Void) -> URLSessionDataTask?
func getProductDetails(_ productID: String, completion: @escaping (_ product: ProductItem?) -> Void) -> URLSessionDataTask
func closestFrameTime(_ timeInSeconds: Double) -> Double
}
| apache-2.0 |
johnno1962d/swift | stdlib/public/core/Builtin.swift | 2 | 18659 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Definitions that make elements of Builtin usable in real code
// without gobs of boilerplate.
/// Returns the contiguous memory footprint of `T`.
///
/// Does not include any dynamically-allocated or "remote" storage.
/// In particular, `sizeof(X.self)`, when `X` is a class type, is the
/// same regardless of how many stored properties `X` has.
@_transparent
@warn_unused_result
public func sizeof<T>(_:T.Type) -> Int {
return Int(Builtin.sizeof(T.self))
}
/// Returns the contiguous memory footprint of `T`.
///
/// Does not include any dynamically-allocated or "remote" storage.
/// In particular, `sizeof(a)`, when `a` is a class instance, is the
/// same regardless of how many stored properties `a` has.
@_transparent
@warn_unused_result
public func sizeofValue<T>(_:T) -> Int {
return sizeof(T.self)
}
/// Returns the minimum memory alignment of `T`.
@_transparent
@warn_unused_result
public func alignof<T>(_:T.Type) -> Int {
return Int(Builtin.alignof(T.self))
}
/// Returns the minimum memory alignment of `T`.
@_transparent
@warn_unused_result
public func alignofValue<T>(_:T) -> Int {
return alignof(T.self)
}
/// Returns the least possible interval between distinct instances of
/// `T` in memory. The result is always positive.
@_transparent
@warn_unused_result
public func strideof<T>(_:T.Type) -> Int {
return Int(Builtin.strideof_nonzero(T.self))
}
/// Returns the least possible interval between distinct instances of
/// `T` in memory. The result is always positive.
@_transparent
@warn_unused_result
public func strideofValue<T>(_:T) -> Int {
return strideof(T.self)
}
@_versioned
@warn_unused_result
internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int {
_sanityCheck(offset >= 0)
_sanityCheck(alignment > 0)
_sanityCheck(_isPowerOf2(alignment))
// Note, given that offset is >= 0, and alignment > 0, we don't
// need to underflow check the -1, as it can never underflow.
let x = (offset + alignment &- 1)
// Note, as alignment is a power of 2, we'll use masking to efficiently
// get the aligned value
return x & ~(alignment &- 1)
}
/// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe.
@_transparent
@warn_unused_result
public // @testable
func _canBeClass<T>(_: T.Type) -> Int8 {
return Int8(Builtin.canBeClass(T.self))
}
/// Returns the bits of `x`, interpreted as having type `U`.
///
/// - Warning: Breaks the guarantees of Swift's type system; use
/// with extreme care. There's almost always a better way to do
/// anything.
///
@_transparent
@warn_unused_result
public func unsafeBitCast<T, U>(_ x: T, to: U.Type) -> U {
_precondition(sizeof(T.self) == sizeof(U.self),
"can't unsafeBitCast between types of different sizes")
return Builtin.reinterpretCast(x)
}
/// `unsafeBitCast` something to `AnyObject`.
@_transparent
@warn_unused_result
public func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject {
return unsafeBitCast(x, to: AnyObject.self)
}
@_transparent
@warn_unused_result
func ==(lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@_transparent
@warn_unused_result
func !=(lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return !(lhs == rhs)
}
@_transparent
@warn_unused_result
func ==(lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@_transparent
@warn_unused_result
func !=(lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return !(lhs == rhs)
}
/// Returns `true` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
@warn_unused_result
public func == (t0: Any.Type?, t1: Any.Type?) -> Bool {
return unsafeBitCast(t0, to: Int.self) == unsafeBitCast(t1, to: Int.self)
}
/// Returns `false` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
@warn_unused_result
public func != (t0: Any.Type?, t1: Any.Type?) -> Bool {
return !(t0 == t1)
}
/// Tell the optimizer that this code is unreachable if condition is
/// known at compile-time to be true. If condition is false, or true
/// but not a compile-time constant, this call has no effect.
@_transparent
internal func _unreachable(_ condition: Bool = true) {
if condition {
// FIXME: use a parameterized version of Builtin.unreachable when
// <rdar://problem/16806232> is closed.
Builtin.unreachable()
}
}
/// Tell the optimizer that this code is unreachable if this builtin is
/// reachable after constant folding build configuration builtins.
@_versioned @_transparent @noreturn internal
func _conditionallyUnreachable() {
Builtin.conditionallyUnreachable()
}
@_versioned
@warn_unused_result
@_silgen_name("swift_isClassOrObjCExistentialType")
func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool
/// Returns `true` iff `T` is a class type or an `@objc` existential such as
/// `AnyObject`.
@_versioned
@inline(__always)
@warn_unused_result
internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool {
let tmp = _canBeClass(x)
// Is not a class.
if tmp == 0 {
return false
// Is a class.
} else if tmp == 1 {
return true
}
// Maybe a class.
return _swift_isClassOrObjCExistentialType(x)
}
/// Returns an `UnsafePointer` to the storage used for `object`. There's
/// not much you can do with this other than use it to identify the
/// object.
@_transparent
@warn_unused_result
public func unsafeAddress(of object: AnyObject) -> UnsafePointer<Void> {
return UnsafePointer(Builtin.bridgeToRawPointer(object))
}
@available(*, unavailable, renamed: "unsafeAddress(of:)")
public func unsafeAddressOf(_ object: AnyObject) -> UnsafePointer<Void> {
fatalError("unavailable function can't be called")
}
/// Converts a reference of type `T` to a reference of type `U` after
/// unwrapping one level of Optional.
///
/// Unwrapped `T` and `U` must be convertible to AnyObject. They may
/// be either a class or a class protocol. Either T, U, or both may be
/// optional references.
@_transparent
@warn_unused_result
public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U {
return Builtin.castReference(x)
}
/// - returns: `x as T`.
///
/// - Precondition: `x is T`. In particular, in -O builds, no test is
/// performed to ensure that `x` actually has dynamic type `T`.
///
/// - Warning: Trades safety for performance. Use `unsafeDowncast`
/// only when `x as T` has proven to be a performance problem and you
/// are confident that, always, `x is T`. It is better than an
/// `unsafeBitCast` because it's more restrictive, and because
/// checking is still performed in debug builds.
@_transparent
@warn_unused_result
public func unsafeDowncast<T : AnyObject>(_ x: AnyObject, to: T.Type) -> T {
_debugPrecondition(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
@inline(__always)
@warn_unused_result
public func _getUnsafePointerToStoredProperties(_ x: AnyObject)
-> UnsafeMutablePointer<UInt8> {
let storedPropertyOffset = _roundUp(
sizeof(_HeapObject.self),
toAlignment: alignof(Optional<AnyObject>.self))
return UnsafeMutablePointer<UInt8>(Builtin.bridgeToRawPointer(x)) +
storedPropertyOffset
}
//===----------------------------------------------------------------------===//
// Branch hints
//===----------------------------------------------------------------------===//
// Use @_semantics to indicate that the optimizer recognizes the
// semantics of these function calls. This won't be necessary with
// mandatory generic inlining.
@_versioned
@_transparent
@_semantics("branchhint")
@warn_unused_result
internal func _branchHint<C : Boolean>(_ actual: C, expected: Bool)
-> Bool {
return Bool(Builtin.int_expect_Int1(actual.boolValue._value, expected._value))
}
/// Optimizer hint that `x` is expected to be `true`.
@_transparent
@_semantics("fastpath")
@warn_unused_result
public func _fastPath<C: Boolean>(_ x: C) -> Bool {
return _branchHint(x.boolValue, expected: true)
}
/// Optimizer hint that `x` is expected to be `false`.
@_transparent
@_semantics("slowpath")
@warn_unused_result
public func _slowPath<C : Boolean>(_ x: C) -> Bool {
return _branchHint(x.boolValue, expected: false)
}
/// Optimizer hint that the code where this function is called is on the fast
/// path.
@_transparent
public func _onFastPath() {
Builtin.onFastPath()
}
//===--- Runtime shim wrappers --------------------------------------------===//
/// Returns `true` iff the class indicated by `theClass` uses native
/// Swift reference-counting.
@_versioned
@inline(__always)
@warn_unused_result
internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool {
#if _runtime(_ObjC)
return swift_objc_class_usesNativeSwiftReferenceCounting(
unsafeAddress(of: theClass)
)
#else
return true
#endif
}
@warn_unused_result
@_silgen_name("swift_class_getInstanceExtents")
func swift_class_getInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@warn_unused_result
@_silgen_name("swift_objc_class_unknownGetInstanceExtents")
func swift_objc_class_unknownGetInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
/// - Returns:
@inline(__always)
@warn_unused_result
internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int {
#if _runtime(_ObjC)
return Int(swift_objc_class_unknownGetInstanceExtents(theClass).positive)
#else
return Int(swift_class_getInstanceExtents(theClass).positive)
#endif
}
//===--- Builtin.BridgeObject ---------------------------------------------===//
#if arch(i386) || arch(arm)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0003 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0002 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#elseif arch(x86_64)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x7F00_0000_0000_0006 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 1 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0x8000_0000_0000_0001 }
}
#elseif arch(arm64)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x7F00_0000_0000_0007 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0x8000_0000_0000_0000 }
}
#elseif arch(powerpc64) || arch(powerpc64le)
@_versioned
internal var _objectPointerSpareBits: UInt {
@inline(__always) get { return 0x0000_0000_0000_0007 }
}
@_versioned
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0000_0000_0002 }
}
@_versioned
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get { return 0 }
}
@_versioned
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return 0 }
}
#endif
/// Extract the raw bits of `x`.
@_versioned
@inline(__always)
@warn_unused_result
internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
/// Extract the raw spare bits of `x`.
@_versioned
@inline(__always)
@warn_unused_result
internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt {
return _bitPattern(x) & _objectPointerSpareBits
}
@_versioned
@inline(__always)
@warn_unused_result
internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool {
return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0
}
/// Create a `BridgeObject` around the given `nativeObject` with the
/// given spare bits.
///
/// Reference-counting and other operations on this
/// object will have access to the knowledge that it is native.
///
/// - Precondition: `bits & _objectPointerIsObjCBit == 0`,
/// `bits & _objectPointerSpareBits == bits`.
@_versioned
@inline(__always)
@warn_unused_result
internal func _makeNativeBridgeObject(
_ nativeObject: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(
(bits & _objectPointerIsObjCBit) == 0,
"BridgeObject is treated as non-native when ObjC bit is set"
)
return _makeBridgeObject(nativeObject, bits)
}
/// Create a `BridgeObject` around the given `objCObject`.
@inline(__always)
@warn_unused_result
public // @testable
func _makeObjCBridgeObject(
_ objCObject: AnyObject
) -> Builtin.BridgeObject {
return _makeBridgeObject(
objCObject,
_isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit)
}
/// Create a `BridgeObject` around the given `object` with the
/// given spare bits.
///
/// - Precondition:
///
/// 1. `bits & _objectPointerSpareBits == bits`
/// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise,
/// `object` is either a native object, or `bits ==
/// _objectPointerIsObjCBit`.
@_versioned
@inline(__always)
@warn_unused_result
internal func _makeBridgeObject(
_ object: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(!_isObjCTaggedPointer(object) || bits == 0,
"Tagged pointers cannot be combined with bits")
_sanityCheck(
_isObjCTaggedPointer(object)
|| _usesNativeSwiftReferenceCounting(object.dynamicType)
|| bits == _objectPointerIsObjCBit,
"All spare bits must be set in non-native, non-tagged bridge objects"
)
_sanityCheck(
bits & _objectPointerSpareBits == bits,
"Can't store non-spare bits into Builtin.BridgeObject")
return Builtin.castToBridgeObject(
object, bits._builtinWordValue
)
}
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// a root class or class protocol.
@inline(__always)
@warn_unused_result
public // @testable
func _getSuperclass(_ t: AnyClass) -> AnyClass? {
return unsafeBitCast(
swift_class_getSuperclass(unsafeBitCast(t, to: OpaquePointer.self)),
to: AnyClass.self)
}
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// not a class, is a root class, or is a class protocol.
@inline(__always)
@warn_unused_result
public // @testable
func _getSuperclass(_ t: Any.Type) -> AnyClass? {
return (t as? AnyClass).flatMap { _getSuperclass($0) }
}
//===--- Builtin.IsUnique -------------------------------------------------===//
// _isUnique functions must take an inout object because they rely on
// Builtin.isUnique which requires an inout reference to preserve
// source-level copies in the presence of ARC optimization.
//
// Taking an inout object makes sense for two additional reasons:
//
// 1. You should only call it when about to mutate the object.
// Doing so otherwise implies a race condition if the buffer is
// shared across threads.
//
// 2. When it is not an inout function, self is passed by
// value... thus bumping the reference count and disturbing the
// result we are trying to observe, Dr. Heisenberg!
//
// _isUnique and _isUniquePinned cannot be made public or the compiler
// will attempt to generate generic code for the transparent function
// and type checking will fail.
/// Returns `true` if `object` is uniquely referenced.
@_versioned
@_transparent
@warn_unused_result
internal func _isUnique<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUnique(&object))
}
/// Returns `true` if `object` is uniquely referenced or pinned.
@_versioned
@_transparent
@warn_unused_result
internal func _isUniqueOrPinned<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUniqueOrPinned(&object))
}
/// Returns `true` if `object` is uniquely referenced.
/// This provides sanity checks on top of the Builtin.
@_transparent
@warn_unused_result
public // @testable
func _isUnique_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero, so
// force cast it to BridgeObject and check the spare bits.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
(Builtin.reinterpretCast(object) as AnyObject).dynamicType))
return Bool(Builtin.isUnique_native(&object))
}
/// Returns `true` if `object` is uniquely referenced or pinned.
/// This provides sanity checks on top of the Builtin.
@_transparent
@warn_unused_result
public // @testable
func _isUniqueOrPinned_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
(Builtin.reinterpretCast(object) as AnyObject).dynamicType))
return Bool(Builtin.isUniqueOrPinned_native(&object))
}
/// Returns `true` if type is a POD type. A POD type is a type that does not
/// require any special handling on copying or destruction.
@_transparent
@warn_unused_result
public // @testable
func _isPOD<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.ispod(type))
}
/// Returns `true` if type is nominally an Optional type.
@_transparent
@warn_unused_result
public // @testable
func _isOptional<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isOptional(type))
}
@available(*, unavailable, message: "Removed in Swift 3. Please use Optional.unsafelyUnwrapped instead.")
public func unsafeUnwrap<T>(_ nonEmpty: T?) -> T {
fatalError("unavailable function can't be called")
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.