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 |
---|---|---|---|---|---|
swiftmi/swiftmi-app | swiftmi/swiftmi/SplotLightHelper.swift | 2 | 1941 | //
// SplotLightHelper.swift
// swiftmi
//
// Created by yangyin on 15/11/2.
// Copyright © 2015年 swiftmi. All rights reserved.
//
import CoreSpotlight
import MobileCoreServices
open class SplotlightHelper:NSObject
{
static var domainIdentifier:String = Bundle.main.bundleIdentifier!;
class func AddItemToCoreSpotlight(_ id:String,title:String,contentDescription:String)
{
if #available(iOS 9.0, *) {
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
attributeSet.title = title;
attributeSet.contentDescription = contentDescription;
let item = CSSearchableItem(uniqueIdentifier: id, domainIdentifier: domainIdentifier, attributeSet: attributeSet)
// expire after a month
item.expirationDate = Date(timeInterval: 30*24*60*60, since:Date())
CSSearchableIndex.default().indexSearchableItems([item], completionHandler: { error -> Void in
if let err = error
{
print("index error:\(err.localizedDescription)")
}else{
print("index success")
}
})
} else {
// Fallback on earlier versions
}
}
class func RemoveItemFromCoreSplotlight(_ id:String)
{
if #available(iOS 9.0, *) {
CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: [id]) { error -> Void in
if let err = error {
print("remove index error: \(err.localizedDescription)")
} else {
print("Search item successfully removed!")
}
}
} else {
// Fallback on earlier versions
}
}
}
| mit |
devxoul/Drrrible | Drrrible/Sources/Networking/Plugins/AuthPlugin.swift | 1 | 606 | //
// AuthPlugin.swift
// Drrrible
//
// Created by Suyeol Jeon on 09/03/2017.
// Copyright © 2017 Suyeol Jeon. All rights reserved.
//
import Moya
struct AuthPlugin: PluginType {
fileprivate let authService: AuthServiceType
init(authService: AuthServiceType) {
self.authService = authService
}
func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
var request = request
if let accessToken = self.authService.currentAccessToken?.accessToken {
request.addValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
}
return request
}
}
| mit |
noehou/TWB | TWB/TWB/Tools/Common.swift | 1 | 298 | //
// Common.swift
// TWB
//
// Created by Tommaso on 2017/5/11.
// Copyright © 2017年 Tommaso. All rights reserved.
//
import Foundation
//MARK:- 授权的常量
let app_key = "1265505535"
let app_secret = "029c86a9dea17a4cb613c5ac967630ef"
let redirect_uri = "https://www.365fwy.com"
| mit |
angelopino/APJExtensions | Tests/UserDefaultTest.swift | 1 | 1092 | //
// UserDefaultTest.swift
// APJExtensionsiOSTests
//
// Created by Angelo Pino on 22/05/2020.
// Copyright © 2020 Pino, Angelo. All rights reserved.
//
import XCTest
class UserDefaultTest: XCTestCase {
struct TestModel {
@UserDefault("firstname", defaultValue: "Giuseppe")
var firstname: String?
@UserDefault("lastname", defaultValue: "Rossi")
var lastname: String?
}
func testUserDefault() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
var model = TestModel()
model.firstname = nil
XCTAssertEqual(model.firstname, "Giuseppe")
XCTAssertEqual(model.lastname, "Rossi")
model.firstname = "Mario"
XCTAssertEqual(model.firstname, "Mario")
let model2 = TestModel()
XCTAssertEqual(model2.firstname, "Mario")
UserDefaults.standard.set(2, forKey: "firstname")
XCTAssertEqual(model2.firstname, "Giuseppe")
}
}
| mit |
KagasiraBunJee/TryHard | TryHard/VCLoader.swift | 1 | 1602 | //
// UIViewController+storyboardLoad.swift
// FashionSwapp
//
// Created by chublix on 9/6/15.
// Copyright (c) 2015 eKreative. All rights reserved.
//
import UIKit
import Foundation
enum FOStoryboard : String {
case Main
case Bluetooth
case Accessory
case Tesseract
case ImageSelector
case ImageProcessing
case VideoProcessing
case Audio
case SIP
}
class VCLoader<VC: UIViewController> {
class func load(storyboardName storyboard: String!) -> VC {
let className = NSStringFromClass(VC.self).componentsSeparatedByString(".").last!
return VCLoader<VC>.load(storyboardName: storyboard, inStoryboardID: className)
}
class func load(storyboardName storyboard: String!, inStoryboardID: String!) -> VC {
let storyboard = UIStoryboard(name: storyboard, bundle: NSBundle.mainBundle())
return storyboard.instantiateViewControllerWithIdentifier(inStoryboardID) as! VC
}
}
extension VCLoader {
class func load(storyboardId storyboard: FOStoryboard) -> VC {
return VCLoader<VC>.load(storyboardName: storyboard.rawValue)
}
class func load(storyboardId storyboard: FOStoryboard, inStoryboardID: String!) -> VC {
let storyboard = UIStoryboard(name: storyboard.rawValue, bundle: NSBundle.mainBundle())
return storyboard.instantiateViewControllerWithIdentifier(inStoryboardID) as! VC
}
class func loadInitial(storyboardId storyboard: FOStoryboard) -> VC {
let storyboard = UIStoryboard(name: storyboard.rawValue, bundle: NSBundle.mainBundle())
return storyboard.instantiateInitialViewController() as! VC
}
}
| mit |
SECH-Tag-EEXCESS-Browser/iOSX-App | Team UI/Browser/Browser/JSONData.swift | 1 | 2834 | //
// JSONParser.swift
// Browser
//
// Created by Burak Erol on 10.12.15.
// Copyright © 2015 SECH-Tag-EEXCESS-Browser. All rights reserved.
//
import Foundation
enum JSONData {
case JSONObject([String:JSONData])
case JSONArray([JSONData])
case JSONString(String)
case JSONNumber(NSNumber)
case JSONBool(Bool)
var object : [String : JSONData]? {
switch self {
case .JSONObject(let aData):
return aData
default:
return nil
}
}
var array : [JSONData]? {
switch self {
case .JSONArray(let aData):
return aData
default:
return nil
}
}
var string : String? {
switch self {
case .JSONString(let aData):
return aData
default:
return nil
}
}
var integer : Int? {
switch self {
case .JSONNumber(let aData):
return aData.integerValue
default:
return nil
}
}
var bool: Bool? {
switch self {
case .JSONBool(let value):
return value
default:
return nil
}
}
subscript(i: Int) -> JSONData? {
get {
switch self {
case .JSONArray(let value):
return value[i]
default:
return nil
}
}
}
subscript(key: String) -> JSONData? {
get {
switch self {
case .JSONObject(let value):
return value[key]
default:
return nil
}
}
}
static func fromObject(object: AnyObject) -> JSONData? {
switch object {
case let value as String:
return JSONData.JSONString(value as String)
case let value as NSNumber:
return JSONData.JSONNumber(value)
case let value as NSDictionary:
var jsonObject: [String:JSONData] = [:]
for (key, value) : (AnyObject, AnyObject) in value {
if let key = key as? String {
if let value = JSONData.fromObject(value) {
jsonObject[key] = value
} else {
return nil
}
}
}
return JSONData.JSONObject(jsonObject)
case let value as NSArray:
var jsonArray: [JSONData] = []
for v in value {
if let v = JSONData.fromObject(v) {
jsonArray.append(v)
} else {
return nil
}
}
return JSONData.JSONArray(jsonArray)
default:
return nil
}
}
} | mit |
teaxus/TSAppEninge | Source/Basic/Controller/TSImagePicker/TSImagePicker.swift | 1 | 4316 | //
// TSImagePicker.swift
// StandardProject
//
// Created by teaxus on 16/1/7.
// Copyright © 2016年 teaxus. All rights reserved.
//
import UIKit
//import TSAppEngine
import AssetsLibrary
class TSImageCamera:UIImagePickerController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var action:ReturnArrayLib_URL_Image?
var VC_push:UIViewController?
var useSourceType = UIImagePickerControllerSourceType.camera
func show(after_select:@escaping ReturnArrayLib_URL_Image){
self.action = after_select
self.delegate = self
self.modalTransitionStyle = .coverVertical//设置换场动画
self.allowsEditing = true
self.navigationBar.tintColor = UIColor.red
let author = ALAssetsLibrary.authorizationStatus()
if author == .restricted || author == .denied{
}
else{
self.sourceType = useSourceType
}
VC_push?.present(self, animated: false) { () -> Void in
self.setNeedsStatusBarAppearanceUpdate()//改变后需要及时刷新的调用
}
}
//MARK:imagepicker代理方法
private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image_upload = info[UIImagePickerControllerEditedImage] as! UIImage
self.VC_push?.dismiss(animated: true, completion: { () -> Void in
self.action?([],[],[image_upload])
})
}
}
public class TSImagePicker: NSObject ,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
let imagePicker_now = TSImageCamera()
var action:ReturnArrayLib_URL_Image?
var max:Int = 9999
let VC_now_appear:TSAppEngineViewController? = TSAppEngineViewController.VC_now_appear
var arry_other_action = [UIAlertAction]()
public convenience init(action_return:@escaping ReturnArrayLib_URL_Image,max_select:Int) {
self.init()
action = action_return
max = max_select
}
public func show(){
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil)
let deleteAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.default, handler: { (_) -> Void in
self.imagePicker_now.useSourceType = .camera
self.imagePicker_now.VC_push = self.VC_now_appear
self.imagePicker_now.show(after_select: { (_, _, arr_image) -> Void in
self.action?([],[],arr_image)
})
})
let archiveAction = UIAlertAction(title: "从相册选择", style: UIAlertActionStyle.default, handler: {(_) -> Void in
if self.max == 1{//选择只是一张的时候
self.imagePicker_now.useSourceType = .photoLibrary
self.imagePicker_now.VC_push = self.VC_now_appear
self.imagePicker_now.show(after_select: { (_, _, arr_image) -> Void in
self.action?([],[],arr_image)
})
}
else{//当多选的时候
//MARK:从相片册选择
let VC = TSImagePickViewController(nibName: "TSImagePickViewController", bundle: nil)
VC.max_select = self.max
VC.action = {(arr_asset,arr_url,arr_image) -> Void in
self.action?(arr_asset,arr_url,arr_image)
}
self.VC_now_appear?.navigationController?.pushViewController(VC, animated: true)
}
})
alertController.addAction(cancelAction)
alertController.addAction(deleteAction)
alertController.addAction(archiveAction)
for action in arry_other_action{
alertController.addAction(action)
}
self.VC_now_appear?.present(alertController, animated: true, completion: { () -> Void in
})
}
//MARK:Action sheet代理方法
public func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
if buttonIndex == 1{//拍照
}
else if buttonIndex == 2{
}
}
}
| mit |
MitchellPhillips22/TIY-Assignments | Day 8/Calculator1/Calculator1/ViewController.swift | 1 | 367 | //
// ViewController.swift
// Calculator1
//
// Created by Mitchell Phillips on 2/10/16.
// Copyright © 2016 Mitchell Phillips. All rights reserved.
//
import UIKit
class Calculator {
var value1 = 0
var hasTappedNumber = false
var hasCalculated = false
@IBAction func numberTapped(sender: UIBorderButton) {
}
}
| cc0-1.0 |
cabarique/TheProposalGame | MyProposalGame/Libraries/SKUtils/Int+Extensions.swift | 19 | 2676 | /*
* Copyright (c) 2013-2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import CoreGraphics
public extension Int {
/**
* Ensures that the integer value stays with the specified range.
*/
public func clamped(range: Range<Int>) -> Int {
return (self < range.startIndex) ? range.startIndex : ((self >= range.endIndex) ? range.endIndex - 1: self)
}
/**
* Ensures that the integer value stays with the specified range.
*/
public mutating func clamp(range: Range<Int>) -> Int {
self = clamped(range)
return self
}
/**
* Ensures that the integer value stays between the given values, inclusive.
*/
public func clamped(v1: Int, _ v2: Int) -> Int {
let min = v1 < v2 ? v1 : v2
let max = v1 > v2 ? v1 : v2
return self < min ? min : (self > max ? max : self)
}
/**
* Ensures that the integer value stays between the given values, inclusive.
*/
public mutating func clamp(v1: Int, _ v2: Int) -> Int {
self = clamped(v1, v2)
return self
}
/**
* Returns a random integer in the specified range.
*/
public static func random(range: Range<Int>) -> Int {
return Int(arc4random_uniform(UInt32(range.endIndex - range.startIndex))) + range.startIndex
}
/**
* Returns a random integer between 0 and n-1.
*/
public static func random(n: Int) -> Int {
return Int(arc4random_uniform(UInt32(n)))
}
/**
* Returns a random integer in the range min...max, inclusive.
*/
public static func random(min min: Int, max: Int) -> Int {
assert(min < max)
return Int(arc4random_uniform(UInt32(max - min + 1))) + min
}
}
| mit |
Tanglo/VergeOfStrife | Vos Map Maker/VoSMap.swift | 1 | 2000 | //
// VoSMap.swift
// VergeOfStrife
//
// Created by Lee Walsh on 30/03/2015.
// Copyright (c) 2015 Lee David Walsh. All rights reserved.
//
import Cocoa
struct VoSSize {
var width = 0.0
var height = 0.0
}
struct VoSPoint {
var x = 0.0
var y = 0.0
}
struct VoSRect {
var origin = VoSPoint(x: 0.0, y: 0.0)
var size = VoSSize(width: 0.0, height: 0.0)
}
class VoSMap: NSObject, NSCoding {
var grid: VoSGrid
var tileSetName: String
var tileSize: VoSSize
override init() {
grid = VoSGrid()
tileSetName = "Default"
tileSize = VoSSize(width: 50, height: 50.0)
}
required init(coder aDecoder: NSCoder) {
self.grid = aDecoder.decodeObjectForKey("grid") as! VoSGrid
self.tileSetName = aDecoder.decodeObjectForKey("tileSetName") as! String
self.tileSize = VoSSize()
self.tileSize.width = aDecoder.decodeDoubleForKey("tileSize.width")
self.tileSize.height = aDecoder.decodeDoubleForKey("tileSize.height")
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(grid, forKey: "grid")
aCoder.encodeObject(tileSetName, forKey: "tileSetName")
aCoder.encodeDouble(tileSize.width, forKey: "tileSize.width")
aCoder.encodeDouble(tileSize.height, forKey: "tileSize.height")
}
func importMapFromString(mapString: String) {
let crSet = NSCharacterSet(charactersInString: "\n\r")
let newMapRows = reverse(mapString.componentsSeparatedByCharactersInSet(crSet))
let rowCount = newMapRows.count
var colCount = 0
var tileCodes = [String]()
for mapRow in newMapRows {
let newTilesCodes = mapRow.componentsSeparatedByString(",")
tileCodes += newTilesCodes
if newTilesCodes.count > colCount {
colCount = newTilesCodes.count
}
}
grid = VoSGrid(rows: rowCount, columns: colCount, tileValues: tileCodes)
}
} | mit |
beeth0ven/BNKit | BNKit/Source/Fundation+/TimeInterval+.swift | 1 | 418 | //
// TimeInterval.swift
// WorkMap
//
// Created by luojie on 16/10/13.
// Copyright © 2016年 LuoJie. All rights reserved.
//
import Foundation
extension TimeInterval {
public var minutes: TimeInterval {
return self * 60
}
public var hours: TimeInterval {
return self * 60.0.minutes
}
public var days: TimeInterval {
return self * 24.0.hours
}
}
| mit |
stripe/stripe-ios | StripeIdentity/StripeIdentity/Source/NativeComponents/Views/IdentityFlowView.swift | 1 | 11575 | //
// IdentityFlowView.swift
// StripeIdentity
//
// Created by Mel Ludowise on 10/28/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
@_spi(STP) import StripeCore
@_spi(STP) import StripeUICore
import UIKit
protocol IdentityFlowViewDelegate: AnyObject {
func scrollViewFullyLaiedOut(_ scrollView: UIScrollView)
}
// swift-format-ignore: DontRepeatTypeInStaticProperties
/// Container view with a scroll view used in `IdentityFlowViewController`
class IdentityFlowView: UIView {
typealias ContentViewModel = ViewModel.Content
struct Style {
static let defaultContentViewInsets = NSDirectionalEdgeInsets(
top: 16,
leading: 16,
bottom: 16,
trailing: 16
)
static let buttonSpacing: CGFloat = 10
static let buttonInsets = NSDirectionalEdgeInsets(
top: 8,
leading: 16,
bottom: 8,
trailing: 16
)
static var buttonFont: UIFont {
return IdentityUI.preferredFont(forTextStyle: .body, weight: .medium)
}
static func buttonConfiguration(isPrimary: Bool) -> Button.Configuration {
var config: Button.Configuration = isPrimary ? .primary() : .secondary()
config.font = buttonFont
return config
}
static let buttonBackgroundBlurStyle: UIBlurEffect.Style = {
if #available(iOS 13.0, *) {
return .systemUltraThinMaterial
} else {
return .regular
}
}()
}
struct ViewModel {
struct Button {
enum State {
case enabled
case disabled
case loading
}
let text: String
let state: State
let isPrimary: Bool
let didTap: () -> Void
init(
text: String,
state: State = .enabled,
isPrimary: Bool = true,
didTap: @escaping () -> Void
) {
self.text = text
self.state = state
self.isPrimary = isPrimary
self.didTap = didTap
}
}
struct Content: Equatable {
let view: UIView
let inset: NSDirectionalEdgeInsets?
}
let headerViewModel: HeaderView.ViewModel?
let contentViewModel: Content
let buttons: [Button]
var scrollViewDelegate: UIScrollViewDelegate? = nil
var flowViewDelegate: IdentityFlowViewDelegate? = nil
}
private let headerView = HeaderView()
private let insetContentView = UIView()
private let scrollView = UIScrollView()
private let scrollContainerStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .fill
return stackView
}()
private let buttonStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .fill
stackView.spacing = Style.buttonSpacing
return stackView
}()
private let buttonBackgroundBlurView = UIVisualEffectView(
effect: UIBlurEffect(
style: Style.buttonBackgroundBlurStyle
)
)
private var flowViewDelegate: IdentityFlowViewDelegate? = nil
// MARK: Configured properties
private var contentViewModel: ContentViewModel?
private var buttons: [Button] = []
private var buttonTapActions: [() -> Void] = []
// MARK: - Init
init() {
super.init(frame: .zero)
backgroundColor = .systemBackground
installViews()
installConstraints()
}
required init?(
coder: NSCoder
) {
fatalError("init(coder:) has not been implemented")
}
/// Configures the view.
///
/// - Note: This method changes the view hierarchy and activates new
/// constraints which can affect screen render performance. It should only be
/// called from a view controller's `init` or `viewDidLoad`.
func configure(with viewModel: ViewModel) {
configureHeaderView(with: viewModel.headerViewModel)
configureContentView(with: viewModel.contentViewModel)
configureButtons(with: viewModel.buttons)
flowViewDelegate = viewModel.flowViewDelegate
if let scrollViewDelegate = viewModel.scrollViewDelegate {
scrollView.delegate = scrollViewDelegate
}
}
func adjustScrollViewForKeyboard(_ windowEndFrame: CGRect, isKeyboardHidden: Bool) {
let endFrame = convert(windowEndFrame, from: window)
// Adjust bottom inset to make space for keyboard
let bottomInset =
isKeyboardHidden ? 0 : (endFrame.height - frame.height + scrollView.frame.maxY)
scrollView.contentInset.bottom = bottomInset
scrollView.verticalScrollIndicatorInsets.bottom = bottomInset
scrollView.horizontalScrollIndicatorInsets.bottom = bottomInset
}
override func layoutSubviews() {
super.layoutSubviews()
// Update the scrollView's inset based on the height of the button
// container so that the content displays above the container plus
// buttonSpacing when scrolled all the way to the bottom
let bottomInset = buttonBackgroundBlurView.frame.height + Style.buttonSpacing
scrollView.verticalScrollIndicatorInsets.bottom = bottomInset
scrollView.contentInset.bottom = bottomInset
if scrollView.contentSize.height > 0 {
flowViewDelegate?.scrollViewFullyLaiedOut(scrollView)
}
}
}
// MARK: - Private Helpers
extension IdentityFlowView {
fileprivate func installViews() {
// Install scroll subviews: header + content
scrollContainerStackView.addArrangedSubview(headerView)
scrollContainerStackView.addArrangedSubview(insetContentView)
scrollView.addAndPinSubview(scrollContainerStackView)
// Arrange container stack view: scroll + button
addAndPinSubview(scrollView)
addSubview(buttonBackgroundBlurView)
buttonBackgroundBlurView.contentView.addAndPinSubviewToSafeArea(
buttonStackView,
insets: Style.buttonInsets
)
}
fileprivate func installConstraints() {
buttonBackgroundBlurView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// Constrain buttons to bottom
buttonBackgroundBlurView.leadingAnchor.constraint(equalTo: leadingAnchor),
buttonBackgroundBlurView.trailingAnchor.constraint(equalTo: trailingAnchor),
buttonBackgroundBlurView.bottomAnchor.constraint(equalTo: bottomAnchor),
// Make scroll view's content full-width
scrollView.contentLayoutGuide.leadingAnchor.constraint(
equalTo: scrollView.leadingAnchor
),
scrollView.contentLayoutGuide.trailingAnchor.constraint(
equalTo: scrollView.trailingAnchor
),
])
}
@objc fileprivate func didTapButton(button: Button) {
buttonTapActions.stp_boundSafeObject(at: button.index)?()
}
}
// MARK: - Private Helpers: View Configurations
extension IdentityFlowView {
fileprivate func configureButtons(with buttonViewModels: [ViewModel.Button]) {
// If there are no buttons to display, hide the container view
guard buttonViewModels.count > 0 else {
buttonBackgroundBlurView.isHidden = true
return
}
buttonBackgroundBlurView.isHidden = false
// Configure buttons and tapActions based from models after we ensure
// there are the right number of buttons
defer {
// Configure buttons
zip(buttonViewModels, buttons).forEach { (viewModel, button) in
button.configure(with: viewModel)
}
// Cache tap actions
buttonTapActions = buttonViewModels.map { $0.didTap }
}
// Only rebuild buttons if the number of buttons has changed
guard buttonViewModels.count != buttons.count else {
return
}
// Remove old buttons and create new ones and add them to the stack view
buttons.forEach { $0.removeFromSuperview() }
buttons = buttonViewModels.enumerated().map { index, _ in
let button = Button(
index: index,
target: self,
action: #selector(didTapButton(button:))
)
buttonStackView.addArrangedSubview(button)
return button
}
}
fileprivate func configureContentView(with contentViewModel: ContentViewModel) {
guard self.contentViewModel != contentViewModel else {
// Nothing to do if view hasn't changed
return
}
self.contentViewModel?.view.removeFromSuperview()
self.contentViewModel = contentViewModel
insetContentView.addAndPinSubview(
contentViewModel.view,
insets: contentViewModel.inset ?? Style.defaultContentViewInsets
)
}
fileprivate func configureHeaderView(with viewModel: HeaderView.ViewModel?) {
if let headerViewModel = viewModel {
headerView.configure(with: headerViewModel)
headerView.isHidden = false
} else {
headerView.isHidden = true
}
}
}
extension IdentityFlowView.ViewModel {
init(
headerViewModel: HeaderView.ViewModel?,
contentView: UIView,
buttonText: String,
state: Button.State = .enabled,
didTapButton: @escaping () -> Void
) {
self.init(
headerViewModel: headerViewModel,
contentViewModel: .init(view: contentView, inset: nil),
buttons: [
.init(
text: buttonText,
state: state,
isPrimary: true,
didTap: didTapButton
)
]
)
}
init(
headerViewModel: HeaderView.ViewModel?,
contentView: UIView,
buttons: [Button]
) {
self.init(
headerViewModel: headerViewModel,
contentViewModel: .init(view: contentView, inset: nil),
buttons: buttons
)
}
}
extension IdentityFlowView.ViewModel.Button {
static func continueButton(
state: State = .enabled,
didTap: @escaping () -> Void
) -> Self {
return .init(
text: String.Localized.continue,
state: state,
isPrimary: true,
didTap: didTap
)
}
}
extension StripeUICore.Button {
fileprivate convenience init(
index: Int,
target: Any?,
action: Selector
) {
self.init()
self.tag = index
addTarget(target, action: action, for: .touchUpInside)
}
fileprivate var index: Int {
return tag
}
fileprivate func configure(with viewModel: IdentityFlowView.ViewModel.Button) {
self.title = viewModel.text
self.configuration = IdentityFlowView.Style.buttonConfiguration(
isPrimary: viewModel.isPrimary
)
self.isEnabled = viewModel.state == .enabled
self.isLoading = viewModel.state == .loading
}
}
| mit |
tuarua/Swift-IOS-ANE | framework_src/native_library/FreSwiftExampleANE/FreSwift/FreSwiftHelper.swift | 1 | 19988 | /* Copyright 2017 Tua Rua Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
public class FreSwiftHelper {
private static var logger: FreSwiftLogger {
return FreSwiftLogger.shared
}
@discardableResult
static func callMethod(_ rawValue: FREObject?, name: String, args: [Any?]) -> FREObject? {
guard let rv = rawValue else {
return nil
}
let argsArray: NSPointerArray = NSPointerArray(options: .opaqueMemory)
for i in 0..<args.count {
argsArray.addPointer(newObject(any: args[i]))
}
var ret: FREObject?
var thrownException: FREObject?
var numArgs: UInt32 = 0
numArgs = UInt32((argsArray.count))
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRECallObjectMethod(object: rv, methodName: name,
argc: numArgs, argv: argsArray,
result: &ret, thrownException: &thrownException)
#else
let status = FRECallObjectMethod(rv, name, numArgs, arrayToFREArray(argsArray), &ret, &thrownException)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot call method \(name) on \(rv.toString())",
stackTrace: getActionscriptException(thrownException),
type: getErrorCode(status))
return nil
}
static func getAsString(_ rawValue: FREObject) -> String? {
var len: UInt32 = 0
var valuePtr: UnsafePointer<UInt8>?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectAsUTF8(object: rawValue,
length: &len, value: &valuePtr)
#else
let status = FREGetObjectAsUTF8(rawValue, &len, &valuePtr)
#endif
if FRE_OK == status {
return NSString(bytes: valuePtr!, length: Int(len), encoding: String.Encoding.utf8.rawValue) as String?
}
logger.error(message: "cannot get FREObject \(rawValue.toString(true)) as String",
type: getErrorCode(status))
return nil
}
static func getAsBool(_ rawValue: FREObject) -> Bool? {
var val: UInt32 = 0
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectAsBool(object: rawValue, value: &val)
#else
let status = FREGetObjectAsBool(rawValue, &val)
#endif
if FRE_OK == status { return val == 1 }
logger.error(message: "cannot get FREObject \(rawValue.toString()) as Bool",
type: getErrorCode(status))
return nil
}
static func getAsDouble(_ rawValue: FREObject) -> Double? {
var ret: Double = 0.0
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectAsDouble(object: rawValue, value: &ret)
#else
let status = FREGetObjectAsDouble(rawValue, &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot get FREObject \(rawValue.toString()) as Double",
type: getErrorCode(status))
return nil
}
static func getAsDate(_ rawValue: FREObject) -> Date? {
if let timeFre = rawValue["time"],
let time = getAsDouble(timeFre) {
return Date(timeIntervalSince1970: time / 1000.0)
}
return nil
}
static func getAsInt(_ rawValue: FREObject) -> Int? {
var ret: Int32 = 0
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectAsInt32(object: rawValue, value: &ret)
#else
let status = FREGetObjectAsInt32(rawValue, &ret)
#endif
if FRE_OK == status { return Int(ret) }
logger.error(message: "cannot get FREObject \(rawValue.toString()) as Int",
type: getErrorCode(status))
return nil
}
static func getAsUInt(_ rawValue: FREObject) -> UInt? {
var ret: UInt32 = 0
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectAsUint32(object: rawValue, value: &ret)
#else
let status = FREGetObjectAsUint32(rawValue, &ret)
#endif
if FRE_OK == status { return UInt(ret) }
logger.error(message: "cannot get FREObject \(rawValue.toString()) as UInt",
type: getErrorCode(status))
return nil
}
static func getAsId(_ rawValue: FREObject?) -> Any? {
guard let rv = rawValue else { return nil }
let objectType: FreObjectTypeSwift = getType(rv)
switch objectType {
case .int:
return getAsInt(rv)
case .vector, .array:
return FREArray(rv).value
case .string:
return getAsString(rv)
case .boolean:
return getAsBool(rv)
case .object, .class:
return getAsDictionary(rv) as [String: AnyObject]?
case .number:
return getAsDouble(rv)
case .bitmapdata:
return FreBitmapDataSwift(freObject: rv).asCGImage()
case .bytearray:
let asByteArray = FreByteArraySwift(freByteArray: rv)
let byteData = asByteArray.value
asByteArray.releaseBytes()
return byteData
case .point:
return CGPoint(rv)
case .rectangle:
return CGRect(rv)
case .date:
return getAsDate(rv)
case .null:
return nil
}
}
public static func newObject(any: Any?) -> FREObject? {
if any == nil {
return nil
} else if any is FREObject, let v = any as? FREObject {
return (v)
} else if any is FreObjectSwift, let v = any as? FreObjectSwift {
return v.rawValue
} else if any is String, let v = any as? String {
return newObject(v)
} else if any is Int, let v = any as? Int {
return newObject(v)
} else if any is Int32, let v = any as? Int32 {
return newObject(Int(v))
} else if any is UInt, let v = any as? UInt {
return newObject(v)
} else if any is UInt32, let v = any as? UInt32 {
return newObject(UInt(v))
} else if any is Double, let v = any as? Double {
return newObject(v)
} else if any is CGFloat, let v = any as? CGFloat {
return newObject(v)
} else if any is Float, let v = any as? Float {
return newObject(Double(v))
} else if any is Bool, let v = any as? Bool {
return newObject(v)
} else if any is Date, let v = any as? Date {
return newObject(v)
} else if any is CGRect, let v = any as? CGRect {
return v.toFREObject()
} else if any is CGPoint, let v = any as? CGPoint {
return v.toFREObject()
} else if any is NSNumber, let v = any as? NSNumber {
return v.toFREObject()
}
return nil
}
public static func arrayToFREArray(_ array: NSPointerArray?) -> UnsafeMutablePointer<FREObject?>? {
if let array = array {
let ret = UnsafeMutablePointer<FREObject?>.allocate(capacity: array.count)
for i in 0..<array.count {
ret[i] = array.pointer(at: i)
}
return ret
}
return nil
}
public static func getType(_ rawValue: FREObject?) -> FreObjectTypeSwift {
guard let rawValue = rawValue else { return FreObjectTypeSwift.null }
var objectType = FRE_TYPE_NULL
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectType(object: rawValue, objectType: &objectType)
#else
let status = FREGetObjectType(rawValue, &objectType)
#endif
if FRE_OK == status {
let type = FreObjectTypeSwift(rawValue: objectType.rawValue) ?? FreObjectTypeSwift.null
return FreObjectTypeSwift.number == type || FreObjectTypeSwift.object == type
? getActionscriptType(rawValue)
: type
}
logger.error(message: "cannot get type", type: getErrorCode(status))
return FreObjectTypeSwift.null
}
fileprivate static func getActionscriptType(_ rawValue: FREObject) -> FreObjectTypeSwift {
if let type = rawValue.className?.lowercased() {
if type == "int" {
return FreObjectTypeSwift.int
} else if type == "date" {
return FreObjectTypeSwift.date
} else if type == "string" {
return FreObjectTypeSwift.string
} else if type == "number" {
return FreObjectTypeSwift.number
} else if type == "boolean" {
return FreObjectTypeSwift.boolean
} else if type == "flash.geom::rectangle" {
return FreObjectTypeSwift.rectangle
} else if type == "flash.geom::point" {
return FreObjectTypeSwift.point
} else {
return FreObjectTypeSwift.class
}
}
return FreObjectTypeSwift.null
}
static func getAsDictionary(_ rawValue: FREObject) -> [String: AnyObject]? {
var ret = [String: AnyObject]()
guard let aneUtils = FREObject(className: "com.tuarua.fre.ANEUtils"),
let classProps = aneUtils.call(method: "getClassProps", args: rawValue) else {
return nil
}
let array = FREArray(classProps)
for fre in array {
if let propNameAs = fre["name"],
let propName = String(propNameAs),
let propValAs = rawValue[propName],
let propVal = FreObjectSwift(propValAs).value {
ret.updateValue(propVal as AnyObject, forKey: propName)
}
}
return ret
}
static func getAsDictionary(_ rawValue: FREObject) -> [String: Any]? {
var ret = [String: Any]()
guard let aneUtils = FREObject(className: "com.tuarua.fre.ANEUtils"),
let classProps = aneUtils.call(method: "getClassProps", args: rawValue) else {
return nil
}
let array = FREArray(classProps)
for fre in array {
if let propNameAs = fre["name"],
let propName = String(propNameAs),
let propValAs = rawValue[propName],
let propVal = FreObjectSwift(propValAs).value {
ret.updateValue(propVal as Any, forKey: propName)
}
}
return ret
}
static func getAsDictionary(_ rawValue: FREObject) -> [String: NSObject]? {
var ret = [String: NSObject]()
guard let aneUtils = FREObject(className: "com.tuarua.fre.ANEUtils"),
let classProps = aneUtils.call(method: "getClassProps", args: rawValue) else {
return nil
}
let array = FREArray(classProps)
for fre in array {
if let propNameAs = fre["name"],
let propName = String(propNameAs),
let propValAs = rawValue[propName],
let propVal = FreObjectSwift(propValAs).value,
let pv = propVal as? NSObject {
ret.updateValue(pv, forKey: propName)
}
}
return ret
}
static func getAsArray(_ rawValue: FREObject) -> [Any]? {
var ret: [Any] = [Any]()
let array = FREArray(rawValue)
for fre in array {
if let v = FreObjectSwift(fre).value {
ret.append(v)
}
}
return ret
}
public static func getProperty(rawValue: FREObject, name: String) -> FREObject? {
var ret: FREObject?
var thrownException: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectProperty(object: rawValue,
propertyName: name,
propertyValue: &ret,
thrownException: &thrownException)
#else
let status = FREGetObjectProperty(rawValue, name, &ret, &thrownException)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot get property \(name) of \(rawValue.toString())",
stackTrace: getActionscriptException(thrownException),
type: getErrorCode(status))
return nil
}
public static func setProperty(rawValue: FREObject, name: String, prop: FREObject?) {
var thrownException: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRESetObjectProperty(object: rawValue,
propertyName: name,
propertyValue: prop,
thrownException: &thrownException)
#else
let status = FRESetObjectProperty(rawValue, name, prop, &thrownException)
#endif
if FRE_OK == status { return }
logger.error(message: "cannot set property \(name) of \(rawValue.toString()) to \(FreObjectSwift(prop).value ?? "unknown")",
stackTrace: getActionscriptException(thrownException),
type: getErrorCode(status))
}
static func getActionscriptException(_ thrownException: FREObject?) -> String {
guard let thrownException = thrownException else {
return ""
}
guard FreObjectTypeSwift.class == thrownException.type else {
return ""
}
guard thrownException.hasOwnProperty(name: "getStackTrace"),
let asStackTrace = thrownException.call(method: "getStackTrace"),
FreObjectTypeSwift.string == asStackTrace.type,
let ret = String(asStackTrace)
else {
return ""
}
return ret
}
public static func newObject(_ string: String) -> FREObject? {
var ret: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObjectFromUTF8(length: UInt32(string.utf8.count),
value: string, object: &ret)
#else
let status = FRENewObjectFromUTF8(UInt32(string.utf8.count), string, &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create FREObject from \(string)",
type: getErrorCode(status))
return nil
}
public static func newObject(_ double: Double) -> FREObject? {
var ret: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObjectFromDouble(value: double, object: &ret)
#else
let status = FRENewObjectFromDouble(double, &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create FREObject from \(double)",
type: getErrorCode(status))
return nil
}
public static func newObject(_ cgFloat: CGFloat) -> FREObject? {
var ret: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObjectFromDouble(value: Double(cgFloat), object: &ret)
#else
let status = FRENewObjectFromDouble(Double(cgFloat), &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create FREObject from \(cgFloat)",
type: getErrorCode(status))
return nil
}
public static func newObject(_ date: Date) -> FREObject? {
var ret: FREObject?
let secs: Double = Double(date.timeIntervalSince1970) * 1000.0
let argsArray: NSPointerArray = NSPointerArray(options: .opaqueMemory)
argsArray.addPointer(secs.toFREObject())
ret = newObject(className: "Date", argsArray)
return ret
}
public static func newObject(_ int: Int) -> FREObject? {
var ret: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObjectFromInt32(value: Int32(int), object: &ret)
#else
let status = FRENewObjectFromInt32(Int32(int), &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create FREObject from \(int)",
type: getErrorCode(status))
return nil
}
public static func newObject(_ uint: UInt) -> FREObject? {
var ret: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObjectFromUint32(value: UInt32(uint), object: &ret)
#else
let status = FRENewObjectFromUint32(UInt32(uint), &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create FREObject from \(uint)",
type: getErrorCode(status))
return nil
}
public static func newObject(_ bool: Bool) -> FREObject? {
var ret: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObjectFromBool(value: bool, object: &ret)
#else
let b: UInt32 = (bool == true) ? 1 : 0
let status = FRENewObjectFromBool(b, &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create FREObject from \(bool)",
type: getErrorCode(status))
return nil
}
public static func newObject(className: String, _ args: NSPointerArray?) -> FREObject? {
var ret: FREObject?
var thrownException: FREObject?
var numArgs: UInt32 = 0
if args != nil {
numArgs = UInt32((args?.count)!)
}
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObject(className: className, argc: numArgs, argv: args,
object: &ret, thrownException: &thrownException)
#else
let status = FRENewObject(className, numArgs, arrayToFREArray(args), &ret, &thrownException)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create new class \(className)",
stackTrace: getActionscriptException(thrownException),
type: getErrorCode(status))
return nil
}
public static func newObject(className: String) -> FREObject? {
var ret: FREObject?
var thrownException: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObject(className: className, argc: 0, argv: nil,
object: &ret, thrownException: &thrownException)
#else
let status = FRENewObject(className, 0, nil, &ret, &thrownException)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create new class \(className)",
stackTrace: getActionscriptException(thrownException),
type: getErrorCode(status))
return nil
}
static func getErrorCode(_ result: FREResult) -> FreError.Code {
switch result {
case FRE_NO_SUCH_NAME:
return .noSuchName
case FRE_INVALID_OBJECT:
return .invalidObject
case FRE_TYPE_MISMATCH:
return .typeMismatch
case FRE_ACTIONSCRIPT_ERROR:
return .actionscriptError
case FRE_INVALID_ARGUMENT:
return .invalidArgument
case FRE_READ_ONLY:
return .readOnly
case FRE_WRONG_THREAD:
return .wrongThread
case FRE_ILLEGAL_STATE:
return .illegalState
case FRE_INSUFFICIENT_MEMORY:
return .insufficientMemory
default:
return .ok
}
}
}
| apache-2.0 |
qRoC/Loobee | Tests/LoobeeTests/Library/AssertionConcern/Assertion/StartsEndsTests.swift | 1 | 2818 | // This file is part of the Loobee package.
//
// (c) Andrey Savitsky <contact@qroc.pro>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
import XCTest
#if canImport(Loobee)
@testable import Loobee
#else
@testable import LoobeeAssertionConcern
#endif
internal final class StartsEndsTests: BaseAssertionsTests {
///
func testStartsWithStringValidCase() {
self.assertMustBeValid(assert("hello", startsWith: "hel"))
}
///
func testStartsWithEmptyRequiredString() {
self.assertMustBeValid(assert("hello", startsWith: ""))
}
///
func testStartsWithSubstringValidCase() {
let testString = "hello"
self.assertMustBeValid(assert(testString, startsWith: testString.prefix(3)))
}
///
func testStartsWithStringNotValidCase() {
self.assertMustBeNotValid(assert("hello", startsWith: "elo"))
}
///
func testStartsWithSubstringNotValidCase() {
let testString = "hello"
self.assertMustBeNotValid(assert(testString, startsWith: testString.dropFirst().prefix(3)))
}
///
func testEndsWithStringValidCase() {
self.assertMustBeValid(assert("hello", endsWith: "llo"))
}
///
func testEndsWithEmptyRequiredString() {
self.assertMustBeValid(assert("hello", endsWith: ""))
}
///
func testEndsWithSubstringValidCase() {
let testString = "hello"
self.assertMustBeValid(assert(testString, endsWith: testString.suffix(3)))
}
///
func testEndsWithStringNotValidCase() {
self.assertMustBeNotValid(assert("hello", endsWith: "ell"))
}
///
func testEndsWithSubstringNotValidCase() {
let testString = "hello"
self.assertMustBeNotValid(assert(testString, endsWith: testString.dropLast().suffix(3)))
}
///
func testStartsWithDefaultMessage() {
let message = kStartsWithDefaultMessage.description
self.assertMustBeNotValid(
assert("b", startsWith: "a"),
withMessage: message
)
}
///
func testStartsWithCustomMessage() {
let message = "Test"
self.assertMustBeNotValid(
assert("b", startsWith: "a", orNotification: message),
withMessage: message
)
}
///
func testEndsWithDefaultMessage() {
let message = kEndsWithDefaultMessage.description
self.assertMustBeNotValid(
assert("b", endsWith: "a"),
withMessage: message
)
}
///
func testEndsWithCustomMessage() {
let message = "Test"
self.assertMustBeNotValid(
assert("b", endsWith: "a", orNotification: message),
withMessage: message
)
}
}
| mit |
wdkk/CAIM | Metal/caimmetal04/CAIMMetal/CAIMColor+MTLColor.swift | 15 | 616 | //
// CAIMColor+MTLColor.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
#if os(macOS) || (os(iOS) && !arch(x86_64))
import Foundation
import Metal
extension CAIMColor {
public var float4:Float4 { return Float4(self.R, self.G, self.B, self.A) }
public var metalColor:MTLClearColor {
return MTLClearColor(red:Double(self.R), green:Double(self.G), blue:Double(self.B), alpha:Double(self.A))
}
}
#endif
| mit |
austinzheng/swift-compiler-crashes | fixed/25211-llvm-smallvectorimpl-swift-diagnosticargument-operator.swift | 7 | 224 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol a{{{{{}}}}typealias d:d
class d
class d:Array
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/10112-bool.swift | 11 | 244 | // 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 d<T where j: P {
var b {
struct d {
init( ) {
struct d<T where j: A
| mit |
austinzheng/swift-compiler-crashes | crashes-fuzzing/26868-std-function-func-swift-type-subst.swift | 4 | 212 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B<c,A{func c<a{{struct d<a{class x:B
| mit |
austinzheng/swift-compiler-crashes | fixed/26409-swift-tuplepattern-createsimple.swift | 7 | 214 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
({func a{init(}}{class b{class A{class
case,
| mit |
imex94/KCLTech-iOS-2015 | Hackalendar/Hackalendar/HackalendarWatch Extension/ExtensionDelegate.swift | 1 | 1005 | //
// ExtensionDelegate.swift
// HackalendarWatch Extension
//
// Created by Alex Telek on 08/12/2015.
// Copyright © 2015 Alex Telek. All rights reserved.
//
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
}
func applicationDidBecomeActive() {
// 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 applicationWillResignActive() {
// 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, etc.
}
}
| mit |
jum/Objective-Zip | Objective-Zip Tests/Objective-Zip_Swift_Tests.swift | 2 | 17922 | //
// Objective-Zip_Swift_Tests.swift
// Objective-Zip v. 1.0.5
//
// Created by Gianluca Bertani on 20/09/15.
// Copyright 2009-2017 Gianluca Bertani. 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 Gianluca Bertani nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES LOSS OF USE, DATA, OR PROFITS OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
import XCTest
let HUGE_TEST_BLOCK_LENGTH = 50000
let HUGE_TEST_NUMBER_OF_BLOCKS = 100000
let MAC_TEST_ZIP = "UEsDBBQACAAIAPWF10IAAAAAAAAAAAAAAAANABAAdGVzdF9maWxlLnR4dFVYDACQCsdRjQrHUfYB9gHzT8pKTS7JLEvVjcosUPBNTFYoSS0uUUjLzEnlAgBQSwcIlXE92h4AAAAcAAAAUEsDBAoAAAAAAACG10IAAAAAAAAAAAAAAAAJABAAX19NQUNPU1gvVVgMAKAKx1GgCsdR9gH2AVBLAwQUAAgACAD1hddCAAAAAAAAAAAAAAAAGAAQAF9fTUFDT1NYLy5fdGVzdF9maWxlLnR4dFVYDACQCsdRjQrHUfYB9gFjYBVjZ2BiYPBNTFbwD1aIUIACkBgDJxAbAXElEIP4qxmIAo4hIUFQJkjHHCDmR1PCiBAXT87P1UssKMhJ1QtJrShxzUvOT8nMSwdKlpak6VpYGxqbGBmaW1qYAABQSwcIcBqNwF0AAACrAAAAUEsBAhUDFAAIAAgA9YXXQpVxPdoeAAAAHAAAAA0ADAAAAAAAAAAAQKSBAAAAAHRlc3RfZmlsZS50eHRVWAgAkArHUY0Kx1FQSwECFQMKAAAAAAAAhtdCAAAAAAAAAAAAAAAACQAMAAAAAAAAAABA/UFpAAAAX19NQUNPU1gvVVgIAKAKx1GgCsdRUEsBAhUDFAAIAAgA9YXXQnAajcBdAAAAqwAAABgADAAAAAAAAAAAQKSBoAAAAF9fTUFDT1NYLy5fdGVzdF9maWxlLnR4dFVYCACQCsdRjQrHUVBLBQYAAAAAAwADANwAAABTAQAAAAA="
let WIN_TEST_ZIP = "UEsDBBQAAAAAAMmF10L4VbPKIQAAACEAAAANAAAAdGVzdF9maWxlLnR4dE9iamVjdGl2ZS1aaXAgV2luZG93cyB0ZXN0IGZpbGUNClBLAQIUABQAAAAAAMmF10L4VbPKIQAAACEAAAANAAAAAAAAAAEAIAAAAAAAAAB0ZXN0X2ZpbGUudHh0UEsFBgAAAAABAAEAOwAAAEwAAAAAAA=="
class Objective_Zip_Swift_Tests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func test01_ZipAndUnzip() {
let documentsUrl = URL(fileURLWithPath:NSHomeDirectory(), isDirectory:true).appendingPathComponent("Documents")
let fileUrl = documentsUrl.appendingPathComponent("test.zip")
let filePath = fileUrl.path
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {}
defer {
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {}
}
do {
NSLog("Test 1: opening zip file for writing...")
let zipFile = try OZZipFile(fileName:filePath, mode:OZZipFileMode.create)
XCTAssertNotNil(zipFile)
NSLog("Test 1: adding first file...")
let stream1 = try zipFile.writeInZip(withName: "abc.txt", fileDate:Date(timeIntervalSinceNow:-86400.0), compressionLevel:OZZipCompressionLevel.best)
XCTAssertNotNil(stream1)
NSLog("Test 1: writing to first file's stream...")
let text = "abc"
try stream1.write(text.data(using: String.Encoding.utf8)!)
NSLog("Test 1: closing first file's stream...")
try stream1.finishedWriting()
NSLog("Test 1: adding second file...")
let file2name = "x/y/z/xyz.txt"
let stream2 = try zipFile.writeInZip(withName: file2name, compressionLevel:OZZipCompressionLevel.none)
XCTAssertNotNil(stream2)
NSLog("Test 1: writing to second file's stream...")
let text2 = "XYZ"
try stream2.write(text2.data(using: String.Encoding.utf8)!)
NSLog("Test 1: closing second file's stream...")
try stream2.finishedWriting()
NSLog("Test 1: closing zip file...")
try zipFile.close()
NSLog("Test 1: opening zip file for reading...")
let unzipFile = try OZZipFile(fileName:filePath, mode:OZZipFileMode.unzip)
XCTAssertNotNil(unzipFile)
NSLog("Test 1: reading file infos...")
let infos = try unzipFile.listFileInZipInfos()
XCTAssertEqual(2, infos.count)
let info1 = infos[0] as! OZFileInZipInfo
XCTAssertEqualWithAccuracy(Date().timeIntervalSinceReferenceDate, info1.date.timeIntervalSinceReferenceDate + 86400, accuracy:5.0)
NSLog("Test 1: - \(info1.name) \(info1.date) \(info1.size) (\(info1.level))")
let info2 = infos[1] as! OZFileInZipInfo
XCTAssertEqualWithAccuracy(Date().timeIntervalSinceReferenceDate, info2.date.timeIntervalSinceReferenceDate, accuracy:5.0)
NSLog("Test 1: - \(info2.name) \(info2.date) \(info2.size) (\(info2.level))")
NSLog("Test 1: opening first file...")
try unzipFile.goToFirstFileInZip()
let read1 = try unzipFile.readCurrentFileInZip()
XCTAssertNotNil(read1)
NSLog("Test 1: reading from first file's stream...")
let data1 = NSMutableData(length:256)!
let bytesRead1 = try read1.readData(withBuffer: data1)
XCTAssertEqual(3, bytesRead1)
let fileText1 = NSString(bytes:data1.bytes, length:Int(bytesRead1), encoding:String.Encoding.utf8.rawValue)
XCTAssertEqual("abc", fileText1)
NSLog("Test 1: closing first file's stream...")
try read1.finishedReading()
NSLog("Test 1: opening second file...")
try unzipFile.locateFile(inZip: file2name)
let read2 = try unzipFile.readCurrentFileInZip()
XCTAssertNotNil(read2)
NSLog("Test 1: reading from second file's stream...")
let data2 = NSMutableData(length:256)!
let bytesRead2 = try read2.readData(withBuffer: data2)
XCTAssertEqual(3, bytesRead2)
let fileText2 = NSString(bytes:data2.bytes, length:Int(bytesRead2), encoding:String.Encoding.utf8.rawValue)
XCTAssertEqual("XYZ", fileText2)
NSLog("Test 1: closing second file's stream...")
try read2.finishedReading()
NSLog("Test 1: closing zip file...")
try unzipFile.close()
NSLog("Test 1: test terminated succesfully")
} catch let error as NSError {
NSLog("Test 1: error caught: \(error.code) - \(error.userInfo[NSLocalizedFailureReasonErrorKey]!)")
XCTFail("Error caught: \(error.code) - \(error.userInfo[NSLocalizedFailureReasonErrorKey]!)")
} catch let error {
NSLog("Test 1: generic error caught: \(error)")
XCTFail("Generic error caught: \(error)")
}
}
/*
* Uncomment to execute this test, but be careful: takes 5 minutes and consumes 5 GB of disk space
*
func test02_ZipAndUnzip5GB() {
let documentsUrl = NSURL(fileURLWithPath:NSHomeDirectory(), isDirectory:true).URLByAppendingPathComponent("Documents")
let fileUrl = documentsUrl.URLByAppendingPathComponent("huge_test.zip")
let filePath = fileUrl.path!
do {
try NSFileManager.defaultManager().removeItemAtPath(filePath)
} catch {}
defer {
do {
try NSFileManager.defaultManager().removeItemAtPath(filePath)
} catch {}
}
do {
NSLog("Test 2: opening zip file for writing...")
let zipFile = try OZZipFile(fileName:filePath, mode:OZZipFileMode.Create)
XCTAssertNotNil(zipFile)
NSLog("Test 2: adding file...")
let stream = try zipFile.writeFileInZipWithName("huge_file.txt", compressionLevel:OZZipCompressionLevel.Best)
XCTAssertNotNil(stream)
NSLog("Test 2: writing to file's stream...")
let data = NSMutableData(length:HUGE_TEST_BLOCK_LENGTH)!
SecRandomCopyBytes(kSecRandomDefault, data.length, UnsafeMutablePointer<UInt8>(data.mutableBytes))
let checkData = data.subdataWithRange(NSMakeRange(0, 100))
let buffer = NSMutableData(length:HUGE_TEST_BLOCK_LENGTH)! // For use later
for (var i = 0; i < HUGE_TEST_NUMBER_OF_BLOCKS; i++) {
try stream.writeData(data)
if (i % 100 == 0) {
NSLog("Test 2: written \((data.length / 1024) * (i + 1)) KB...")
}
}
NSLog("Test 2: closing file's stream...")
try stream.finishedWriting()
NSLog("Test 2: closing zip file...")
try zipFile.close()
NSLog("Test 2: opening zip file for reading...")
let unzipFile = try OZZipFile(fileName:filePath, mode:OZZipFileMode.Unzip)
XCTAssertNotNil(unzipFile)
NSLog("Test 1: reading file infos...")
let infos = try unzipFile.listFileInZipInfos()
XCTAssertEqual(1, infos.count)
let info1 = infos[0] as! OZFileInZipInfo
XCTAssertEqual(info1.length, UInt64(HUGE_TEST_NUMBER_OF_BLOCKS) * UInt64(HUGE_TEST_BLOCK_LENGTH))
NSLog("Test 1: - \(info1.name) \(info1.date) \(info1.size) (\(info1.level))")
NSLog("Test 2: opening file...")
try unzipFile.goToFirstFileInZip()
let read = try unzipFile.readCurrentFileInZip()
XCTAssertNotNil(read)
NSLog("Test 2: reading from file's stream...")
for (var i = 0; i < HUGE_TEST_NUMBER_OF_BLOCKS; i++) {
let bytesRead = try read.readDataWithBuffer(buffer)
XCTAssertEqual(data.length, bytesRead)
let range = buffer.rangeOfData(checkData, options:NSDataSearchOptions(), range:NSMakeRange(0, buffer.length))
XCTAssertEqual(0, range.location)
if (i % 100 == 0) {
NSLog("Test 2: read \((buffer.length / 1024) * (i + 1))) KB...")
}
}
NSLog("Test 2: closing file's stream...")
try read.finishedReading()
NSLog("Test 2: closing zip file...")
try unzipFile.close()
NSLog("Test 2: test terminated succesfully")
} catch let error as NSError {
NSLog("Test 2: error caught: \(error.code) - \(error.userInfo[NSLocalizedFailureReasonErrorKey])")
XCTFail("Error caught: \(error.code) - \(error.userInfo[NSLocalizedFailureReasonErrorKey])")
}
}
*/
func test03_UnzipMacZipFile() -> () {
let documentsUrl = URL(fileURLWithPath:NSHomeDirectory(), isDirectory:true).appendingPathComponent("Documents")
let fileUrl = documentsUrl.appendingPathComponent("mac_test_file.zip")
let filePath = fileUrl.path
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {}
let macZipData = Data(base64Encoded:MAC_TEST_ZIP, options:NSData.Base64DecodingOptions())!
try? macZipData.write(to: URL(fileURLWithPath: filePath), options: [])
defer {
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {}
}
do {
NSLog("Test 3: opening zip file for reading...")
let unzipFile = try OZZipFile(fileName:filePath, mode:OZZipFileMode.unzip)
XCTAssertNotNil(unzipFile)
NSLog("Test 3: opening file...")
try unzipFile.goToFirstFileInZip()
let read = try unzipFile.readCurrentFileInZip()
XCTAssertNotNil(read)
NSLog("Test 3: reading from file's stream...")
let buffer = NSMutableData(length:1024)!
let bytesRead = try read.readData(withBuffer: buffer)
let fileText = NSString(bytes:buffer.bytes, length:Int(bytesRead), encoding:String.Encoding.utf8.rawValue)
XCTAssertEqual("Objective-Zip Mac test file\n", fileText)
NSLog("Test 3: closing file's stream...")
try read.finishedReading()
NSLog("Test 3: closing zip file...")
try unzipFile.close()
NSLog("Test 3: test terminated succesfully")
} catch let error as NSError {
NSLog("Test 3: error caught: \(error.code) - \(error.userInfo[NSLocalizedFailureReasonErrorKey]!)")
XCTFail("Error caught: \(error.code) - \(error.userInfo[NSLocalizedFailureReasonErrorKey]!)")
}
}
func test04_UnzipWinZipFile() {
let documentsUrl = URL(fileURLWithPath:NSHomeDirectory(), isDirectory:true).appendingPathComponent("Documents")
let fileUrl = documentsUrl.appendingPathComponent("win_test_file.zip")
let filePath = fileUrl.path
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {}
let winZipData = Data(base64Encoded:WIN_TEST_ZIP, options:NSData.Base64DecodingOptions())!
try? winZipData.write(to: URL(fileURLWithPath: filePath), options: [])
defer {
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {}
}
do {
NSLog("Test 4: opening zip file for reading...")
let unzipFile = try OZZipFile(fileName:filePath, mode:OZZipFileMode.unzip)
XCTAssertNotNil(unzipFile)
NSLog("Test 4: opening file...")
try unzipFile.goToFirstFileInZip()
let read = try unzipFile.readCurrentFileInZip()
XCTAssertNotNil(read)
NSLog("Test 4: reading from file's stream...")
let buffer = NSMutableData(length:1024)!
let bytesRead = try read.readData(withBuffer: buffer)
let fileText = NSString(bytes:buffer.bytes, length:Int(bytesRead), encoding:String.Encoding.utf8.rawValue)
XCTAssertEqual("Objective-Zip Windows test file\r\n", fileText)
NSLog("Test 4: closing file's stream...")
try read.finishedReading()
NSLog("Test 4: closing zip file...")
try unzipFile.close()
NSLog("Test 4: test terminated succesfully")
} catch let error as NSError {
NSLog("Test 4: error caught: \(error.code) - \(error.userInfo[NSLocalizedFailureReasonErrorKey]!)")
XCTFail("Error caught: \(error.code) - \(error.userInfo[NSLocalizedFailureReasonErrorKey]!)")
}
}
func test05_ErrorWrapping() {
let fileUrl = URL(fileURLWithPath:"/root.zip", isDirectory:false)
let filePath = fileUrl.path
defer {
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {}
}
do {
NSLog("Test 5: opening impossible zip file for writing...")
let zipFile = try OZZipFile(fileName:filePath, mode:OZZipFileMode.create)
try zipFile.close()
NSLog("Test 5: test failed, no error reported")
XCTFail("No error reported")
} catch let error as NSError {
XCTAssertEqual(OZ_ERROR_NO_SUCH_FILE, error.code)
NSLog("Test 5: test terminated succesfully")
}
}
}
| bsd-3-clause |
xuvw/AsyncDisplayKit | examples/Swift/Sample/AppDelegate.swift | 16 | 1095 | /* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.backgroundColor = UIColor.whiteColor()
window.rootViewController = ViewController()
window.makeKeyAndVisible()
self.window = window
return true
}
}
| bsd-3-clause |
akane/Gaikan | GaikanTests/UIKit/Extension/UILabelSpec.swift | 1 | 1005 | //
// This file is part of Gaikan
//
// Created by JC on 11/09/15.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code
//
import Foundation
import Quick
import Nimble
import Gaikan
class UILabelSpec: QuickSpec {
override func spec() {
var label: UILabel!
beforeEach {
label = UILabel()
}
describe("styleInline") {
var style: StyleRule!
context("when giving style") {
it("should inherit view styles") {
style = [ .tintColor: UIColor.blue ]
label.styleInline = style
expect(label.tintColor) == UIColor.blue
}
it("should apply color") {
style = [ .color: UIColor.red ]
label.styleInline = style
expect(label.textColor) == UIColor.red
}
}
}
}
}
| mit |
universonic/shadowsocks-macos | Shadowsocks/PreferencesWinController.swift | 1 | 1132 | //
// PreferencesWinController.swift
// Shadowsocks
//
// Created by 邱宇舟 on 2017/3/11.
// Copyright 2019 Shadowsocks Community. All rights reserved.
//
import Cocoa
import RxCocoa
import RxSwift
class PreferencesWinController: NSWindowController {
@IBOutlet weak var toolbar: NSToolbar!
@IBOutlet weak var tabView: NSTabView!
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
toolbar.selectedItemIdentifier = NSToolbarItem.Identifier(rawValue: "general")
}
@objc func windowWillClose(_ notification: Notification) {
NotificationCenter.default
.post(name: NOTIFY_CONF_CHANGED, object: nil)
}
@IBAction func toolbarAction(sender: NSToolbarItem) {
tabView.selectTabViewItem(withIdentifier: sender.itemIdentifier)
}
@IBAction func resetProxyExceptions(sender: NSButton) {
let defaults = UserDefaults.standard
defaults.removeObject(forKey: "ProxyExceptions")
}
}
| gpl-3.0 |
apple/swift | test/DebugInfo/archetype.swift | 31 | 1117 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | %FileCheck %s
protocol IntegerArithmetic {
static func uncheckedSubtract(_ lhs: Self, rhs: Self) -> (Self, Bool)
}
protocol RandomAccessIndex : IntegerArithmetic {
associatedtype Distance : IntegerArithmetic
static func uncheckedSubtract(_ lhs: Self, rhs: Self) -> (Distance, Bool)
}
// archetype.ExistentialTuple <A : RandomAccessIndex, B>(x : A, y : A) -> B
// CHECK: !DISubprogram(name: "ExistentialTuple", linkageName: "$s9archetype16ExistentialTuple
// CHECK-SAME: line: [[@LINE+2]]
// CHECK-SAME: DISPFlagDefinition
func ExistentialTuple<T: RandomAccessIndex>(_ x: T, y: T) -> T.Distance {
// (B, Swift.Bool)
// CHECK: !DILocalVariable(name: "tmp"
// CHECK-SAME: line: [[@LINE+2]]
// CHECK-SAME: type: ![[TT:[0-9]+]]
var tmp : (T.Distance, Bool) = T.uncheckedSubtract(x, rhs: y)
return _overflowChecked((tmp.0, tmp.1))
}
// CHECK: ![[TT]] = !DICompositeType(tag: DW_TAG_structure_type,
// CHECK-SAME: name: "$s8Distance9archetype17RandomAccessIndexPQz_SbtD"
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/15666-swift-sourcemanager-getmessage.swift | 11 | 203 | // 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 e {
init(
= ( {
class
case ,
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/08898-swift-sourcemanager-getmessage.swift | 11 | 261 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
init {
protocol B {
extension NSSet {
var d {
class A {
var d = [ {
{
func a {
class
case ,
| mit |
tardieu/swift | test/SILOptimizer/specialize_ext.swift | 4 | 516 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -O -emit-sil -primary-file %s | %FileCheck %s
struct XXX<T> {
init(t : T) {m_t = t}
mutating
func foo(_ t : T) -> Int {m_t = t; return 4}
var m_t : T
}
extension XXX {
@inline(never)
mutating
func bar(_ x : T) { self.m_t = x}
}
public func exp1() {
var J = XXX<Int>(t: 4)
J.bar(3)
}
// Make sure that we are able to specialize the extension 'bar'
//CHECK: sil shared [noinline] @_T014specialize_ext3XXXV3bar{{[_0-9a-zA-Z]*}}FSi_Tg5
| apache-2.0 |
brentdax/swift | stdlib/public/core/Optional.swift | 1 | 26579 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that represents either a wrapped value or `nil`, the absence of a
/// value.
///
/// You use the `Optional` type whenever you use optional values, even if you
/// never type the word `Optional`. Swift's type system usually shows the
/// wrapped type's name with a trailing question mark (`?`) instead of showing
/// the full type name. For example, if a variable has the type `Int?`, that's
/// just another way of writing `Optional<Int>`. The shortened form is
/// preferred for ease of reading and writing code.
///
/// The types of `shortForm` and `longForm` in the following code sample are
/// the same:
///
/// let shortForm: Int? = Int("42")
/// let longForm: Optional<Int> = Int("42")
///
/// The `Optional` type is an enumeration with two cases. `Optional.none` is
/// equivalent to the `nil` literal. `Optional.some(Wrapped)` stores a wrapped
/// value. For example:
///
/// let number: Int? = Optional.some(42)
/// let noNumber: Int? = Optional.none
/// print(noNumber == nil)
/// // Prints "true"
///
/// You must unwrap the value of an `Optional` instance before you can use it
/// in many contexts. Because Swift provides several ways to safely unwrap
/// optional values, you can choose the one that helps you write clear,
/// concise code.
///
/// The following examples use this dictionary of image names and file paths:
///
/// let imagePaths = ["star": "/glyphs/star.png",
/// "portrait": "/images/content/portrait.jpg",
/// "spacer": "/images/shared/spacer.gif"]
///
/// Getting a dictionary's value using a key returns an optional value, so
/// `imagePaths["star"]` has type `Optional<String>` or, written in the
/// preferred manner, `String?`.
///
/// Optional Binding
/// ----------------
///
/// To conditionally bind the wrapped value of an `Optional` instance to a new
/// variable, use one of the optional binding control structures, including
/// `if let`, `guard let`, and `switch`.
///
/// if let starPath = imagePaths["star"] {
/// print("The star image is at '\(starPath)'")
/// } else {
/// print("Couldn't find the star image")
/// }
/// // Prints "The star image is at '/glyphs/star.png'"
///
/// Optional Chaining
/// -----------------
///
/// To safely access the properties and methods of a wrapped instance, use the
/// postfix optional chaining operator (postfix `?`). The following example uses
/// optional chaining to access the `hasSuffix(_:)` method on a `String?`
/// instance.
///
/// if imagePaths["star"]?.hasSuffix(".png") == true {
/// print("The star image is in PNG format")
/// }
/// // Prints "The star image is in PNG format"
///
/// Using the Nil-Coalescing Operator
/// ---------------------------------
///
/// Use the nil-coalescing operator (`??`) to supply a default value in case
/// the `Optional` instance is `nil`. Here a default path is supplied for an
/// image that is missing from `imagePaths`.
///
/// let defaultImagePath = "/images/default.png"
/// let heartPath = imagePaths["heart"] ?? defaultImagePath
/// print(heartPath)
/// // Prints "/images/default.png"
///
/// The `??` operator also works with another `Optional` instance on the
/// right-hand side. As a result, you can chain multiple `??` operators
/// together.
///
/// let shapePath = imagePaths["cir"] ?? imagePaths["squ"] ?? defaultImagePath
/// print(shapePath)
/// // Prints "/images/default.png"
///
/// Unconditional Unwrapping
/// ------------------------
///
/// When you're certain that an instance of `Optional` contains a value, you
/// can unconditionally unwrap the value by using the forced
/// unwrap operator (postfix `!`). For example, the result of the failable `Int`
/// initializer is unconditionally unwrapped in the example below.
///
/// let number = Int("42")!
/// print(number)
/// // Prints "42"
///
/// You can also perform unconditional optional chaining by using the postfix
/// `!` operator.
///
/// let isPNG = imagePaths["star"]!.hasSuffix(".png")
/// print(isPNG)
/// // Prints "true"
///
/// Unconditionally unwrapping a `nil` instance with `!` triggers a runtime
/// error.
@_frozen
public enum Optional<Wrapped> : ExpressibleByNilLiteral {
// The compiler has special knowledge of Optional<Wrapped>, including the fact
// that it is an `enum` with cases named `none` and `some`.
/// The absence of a value.
///
/// In code, the absence of a value is typically written using the `nil`
/// literal rather than the explicit `.none` enumeration case.
case none
/// The presence of a value, stored as `Wrapped`.
case some(Wrapped)
/// Creates an instance that stores the given value.
@_transparent
public init(_ some: Wrapped) { self = .some(some) }
/// Evaluates the given closure when this `Optional` instance is not `nil`,
/// passing the unwrapped value as a parameter.
///
/// Use the `map` method with a closure that returns a nonoptional value.
/// This example performs an arithmetic operation on an
/// optional integer.
///
/// let possibleNumber: Int? = Int("42")
/// let possibleSquare = possibleNumber.map { $0 * $0 }
/// print(possibleSquare)
/// // Prints "Optional(1764)"
///
/// let noNumber: Int? = nil
/// let noSquare = noNumber.map { $0 * $0 }
/// print(noSquare)
/// // Prints "nil"
///
/// - Parameter transform: A closure that takes the unwrapped value
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
@inlinable
public func map<U>(
_ transform: (Wrapped) throws -> U
) rethrows -> U? {
switch self {
case .some(let y):
return .some(try transform(y))
case .none:
return .none
}
}
/// Evaluates the given closure when this `Optional` instance is not `nil`,
/// passing the unwrapped value as a parameter.
///
/// Use the `flatMap` method with a closure that returns an optional value.
/// This example performs an arithmetic operation with an optional result on
/// an optional integer.
///
/// let possibleNumber: Int? = Int("42")
/// let nonOverflowingSquare = possibleNumber.flatMap { x -> Int? in
/// let (result, overflowed) = x.multipliedReportingOverflow(by: x)
/// return overflowed ? nil : result
/// }
/// print(nonOverflowingSquare)
/// // Prints "Optional(1764)"
///
/// - Parameter transform: A closure that takes the unwrapped value
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
@inlinable
public func flatMap<U>(
_ transform: (Wrapped) throws -> U?
) rethrows -> U? {
switch self {
case .some(let y):
return try transform(y)
case .none:
return .none
}
}
/// Creates an instance initialized with `nil`.
///
/// Do not call this initializer directly. It is used by the compiler when you
/// initialize an `Optional` instance with a `nil` literal. For example:
///
/// var i: Index? = nil
///
/// In this example, the assignment to the `i` variable calls this
/// initializer behind the scenes.
@_transparent
public init(nilLiteral: ()) {
self = .none
}
/// The wrapped value of this instance, unwrapped without checking whether
/// the instance is `nil`.
///
/// The `unsafelyUnwrapped` property provides the same value as the forced
/// unwrap operator (postfix `!`). However, in optimized builds (`-O`), no
/// check is performed to ensure that the current instance actually has a
/// value. Accessing this property in the case of a `nil` value is a serious
/// programming error and could lead to undefined behavior or a runtime
/// error.
///
/// In debug builds (`-Onone`), the `unsafelyUnwrapped` property has the same
/// behavior as using the postfix `!` operator and triggers a runtime error
/// if the instance is `nil`.
///
/// The `unsafelyUnwrapped` property is recommended over calling the
/// `unsafeBitCast(_:)` function because the property is more restrictive
/// and because accessing the property still performs checking in debug
/// builds.
///
/// - Warning: This property trades safety for performance. Use
/// `unsafelyUnwrapped` only when you are confident that this instance
/// will never be equal to `nil` and only after you've tried using the
/// postfix `!` operator.
@inlinable
public var unsafelyUnwrapped: Wrapped {
@inline(__always)
get {
if let x = self {
return x
}
_debugPreconditionFailure("unsafelyUnwrapped of nil optional")
}
}
/// - Returns: `unsafelyUnwrapped`.
///
/// This version is for internal stdlib use; it avoids any checking
/// overhead for users, even in Debug builds.
@inlinable
internal var _unsafelyUnwrappedUnchecked: Wrapped {
@inline(__always)
get {
if let x = self {
return x
}
_sanityCheckFailure("_unsafelyUnwrappedUnchecked of nil optional")
}
}
}
extension Optional : CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
switch self {
case .some(let value):
var result = "Optional("
debugPrint(value, terminator: "", to: &result)
result += ")"
return result
case .none:
return "nil"
}
}
}
extension Optional : CustomReflectable {
public var customMirror: Mirror {
switch self {
case .some(let value):
return Mirror(
self,
children: [ "some": value ],
displayStyle: .optional)
case .none:
return Mirror(self, children: [:], displayStyle: .optional)
}
}
}
@_transparent
public // COMPILER_INTRINSIC
func _diagnoseUnexpectedNilOptional(_filenameStart: Builtin.RawPointer,
_filenameLength: Builtin.Word,
_filenameIsASCII: Builtin.Int1,
_line: Builtin.Word,
_isImplicitUnwrap: Builtin.Int1) {
_preconditionFailure(
Bool(_isImplicitUnwrap)
? "Unexpectedly found nil while implicitly unwrapping an Optional value"
: "Unexpectedly found nil while unwrapping an Optional value",
file: StaticString(_start: _filenameStart,
utf8CodeUnitCount: _filenameLength,
isASCII: _filenameIsASCII),
line: UInt(_line))
}
extension Optional : Equatable where Wrapped : Equatable {
/// Returns a Boolean value indicating whether two optional instances are
/// equal.
///
/// Use this equal-to operator (`==`) to compare any two optional instances of
/// a type that conforms to the `Equatable` protocol. The comparison returns
/// `true` if both arguments are `nil` or if the two arguments wrap values
/// that are equal. Conversely, the comparison returns `false` if only one of
/// the arguments is `nil` or if the two arguments wrap values that are not
/// equal.
///
/// let group1 = [1, 2, 3, 4, 5]
/// let group2 = [1, 3, 5, 7, 9]
/// if group1.first == group2.first {
/// print("The two groups start the same.")
/// }
/// // Prints "The two groups start the same."
///
/// You can also use this operator to compare a nonoptional value to an
/// optional that wraps the same type. The nonoptional value is wrapped as an
/// optional before the comparison is made. In the following example, the
/// `numberToMatch` constant is wrapped as an optional before comparing to the
/// optional `numberFromString`:
///
/// let numberToFind: Int = 23
/// let numberFromString: Int? = Int("23") // Optional(23)
/// if numberToFind == numberFromString {
/// print("It's a match!")
/// }
/// // Prints "It's a match!"
///
/// An instance that is expressed as a literal can also be used with this
/// operator. In the next example, an integer literal is compared with the
/// optional integer `numberFromString`. The literal `23` is inferred as an
/// `Int` instance and then wrapped as an optional before the comparison is
/// performed.
///
/// if 23 == numberFromString {
/// print("It's a match!")
/// }
/// // Prints "It's a match!"
///
/// - Parameters:
/// - lhs: An optional value to compare.
/// - rhs: Another optional value to compare.
@inlinable
public static func ==(lhs: Wrapped?, rhs: Wrapped?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l == r
case (nil, nil):
return true
default:
return false
}
}
}
extension Optional: Hashable where Wrapped: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
switch self {
case .none:
hasher.combine(0 as UInt8)
case .some(let wrapped):
hasher.combine(1 as UInt8)
hasher.combine(wrapped)
}
}
}
// Enable pattern matching against the nil literal, even if the element type
// isn't equatable.
@_fixed_layout
public struct _OptionalNilComparisonType : ExpressibleByNilLiteral {
/// Create an instance initialized with `nil`.
@_transparent
public init(nilLiteral: ()) {
}
}
extension Optional {
/// Returns a Boolean value indicating whether an argument matches `nil`.
///
/// You can use the pattern-matching operator (`~=`) to test whether an
/// optional instance is `nil` even when the wrapped value's type does not
/// conform to the `Equatable` protocol. The pattern-matching operator is used
/// internally in `case` statements for pattern matching.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type, and then uses a `switch`
/// statement to determine whether the stream is `nil` or has a configured
/// value. When evaluating the `nil` case of the `switch` statement, this
/// operator is called behind the scenes.
///
/// var stream: DataStream? = nil
/// switch stream {
/// case nil:
/// print("No data stream is configured.")
/// case let x?:
/// print("The data stream has \(x.availableBytes) bytes available.")
/// }
/// // Prints "No data stream is configured."
///
/// - Note: To test whether an instance is `nil` in an `if` statement, use the
/// equal-to operator (`==`) instead of the pattern-matching operator. The
/// pattern-matching operator is primarily intended to enable `case`
/// statement pattern matching.
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to match against `nil`.
@_transparent
public static func ~=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some:
return false
case .none:
return true
}
}
// Enable equality comparisons against the nil literal, even if the
// element type isn't equatable
/// Returns a Boolean value indicating whether the left-hand-side argument is
/// `nil`.
///
/// You can use this equal-to operator (`==`) to test whether an optional
/// instance is `nil` even when the wrapped value's type does not conform to
/// the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` is
/// `nil`.
///
/// var stream: DataStream? = nil
/// if stream == nil {
/// print("No data stream is configured.")
/// }
/// // Prints "No data stream is configured."
///
/// - Parameters:
/// - lhs: A value to compare to `nil`.
/// - rhs: A `nil` literal.
@_transparent
public static func ==(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
switch lhs {
case .some:
return false
case .none:
return true
}
}
/// Returns a Boolean value indicating whether the left-hand-side argument is
/// not `nil`.
///
/// You can use this not-equal-to operator (`!=`) to test whether an optional
/// instance is not `nil` even when the wrapped value's type does not conform
/// to the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` wraps
/// a value and is therefore not `nil`.
///
/// var stream: DataStream? = fetchDataStream()
/// if stream != nil {
/// print("The data stream has been configured.")
/// }
/// // Prints "The data stream has been configured."
///
/// - Parameters:
/// - lhs: A value to compare to `nil`.
/// - rhs: A `nil` literal.
@_transparent
public static func !=(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
switch lhs {
case .some:
return true
case .none:
return false
}
}
/// Returns a Boolean value indicating whether the right-hand-side argument is
/// `nil`.
///
/// You can use this equal-to operator (`==`) to test whether an optional
/// instance is `nil` even when the wrapped value's type does not conform to
/// the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` is
/// `nil`.
///
/// var stream: DataStream? = nil
/// if nil == stream {
/// print("No data stream is configured.")
/// }
/// // Prints "No data stream is configured."
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to compare to `nil`.
@_transparent
public static func ==(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some:
return false
case .none:
return true
}
}
/// Returns a Boolean value indicating whether the right-hand-side argument is
/// not `nil`.
///
/// You can use this not-equal-to operator (`!=`) to test whether an optional
/// instance is not `nil` even when the wrapped value's type does not conform
/// to the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` wraps
/// a value and is therefore not `nil`.
///
/// var stream: DataStream? = fetchDataStream()
/// if nil != stream {
/// print("The data stream has been configured.")
/// }
/// // Prints "The data stream has been configured."
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to compare to `nil`.
@_transparent
public static func !=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some:
return true
case .none:
return false
}
}
}
/// Performs a nil-coalescing operation, returning the wrapped value of an
/// `Optional` instance or a default value.
///
/// A nil-coalescing operation unwraps the left-hand side if it has a value, or
/// it returns the right-hand side as a default. The result of this operation
/// will have the nonoptional type of the left-hand side's `Wrapped` type.
///
/// This operator uses short-circuit evaluation: `optional` is checked first,
/// and `defaultValue` is evaluated only if `optional` is `nil`. For example:
///
/// func getDefault() -> Int {
/// print("Calculating default...")
/// return 42
/// }
///
/// let goodNumber = Int("100") ?? getDefault()
/// // goodNumber == 100
///
/// let notSoGoodNumber = Int("invalid-input") ?? getDefault()
/// // Prints "Calculating default..."
/// // notSoGoodNumber == 42
///
/// In this example, `goodNumber` is assigned a value of `100` because
/// `Int("100")` succeeded in returning a non-`nil` result. When
/// `notSoGoodNumber` is initialized, `Int("invalid-input")` fails and returns
/// `nil`, and so the `getDefault()` method is called to supply a default
/// value.
///
/// - Parameters:
/// - optional: An optional value.
/// - defaultValue: A value to use as a default. `defaultValue` is the same
/// type as the `Wrapped` type of `optional`.
@_transparent
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T)
rethrows -> T {
switch optional {
case .some(let value):
return value
case .none:
return try defaultValue()
}
}
/// Performs a nil-coalescing operation, returning the wrapped value of an
/// `Optional` instance or a default `Optional` value.
///
/// A nil-coalescing operation unwraps the left-hand side if it has a value, or
/// returns the right-hand side as a default. The result of this operation
/// will be the same type as its arguments.
///
/// This operator uses short-circuit evaluation: `optional` is checked first,
/// and `defaultValue` is evaluated only if `optional` is `nil`. For example:
///
/// let goodNumber = Int("100") ?? Int("42")
/// print(goodNumber)
/// // Prints "Optional(100)"
///
/// let notSoGoodNumber = Int("invalid-input") ?? Int("42")
/// print(notSoGoodNumber)
/// // Prints "Optional(42)"
///
/// In this example, `goodNumber` is assigned a value of `100` because
/// `Int("100")` succeeds in returning a non-`nil` result. When
/// `notSoGoodNumber` is initialized, `Int("invalid-input")` fails and returns
/// `nil`, and so `Int("42")` is called to supply a default value.
///
/// Because the result of this nil-coalescing operation is itself an optional
/// value, you can chain default values by using `??` multiple times. The
/// first optional value that isn't `nil` stops the chain and becomes the
/// result of the whole expression. The next example tries to find the correct
/// text for a greeting in two separate dictionaries before falling back to a
/// static default.
///
/// let greeting = userPrefs[greetingKey] ??
/// defaults[greetingKey] ?? "Greetings!"
///
/// If `userPrefs[greetingKey]` has a value, that value is assigned to
/// `greeting`. If not, any value in `defaults[greetingKey]` will succeed, and
/// if not that, `greeting` will be set to the nonoptional default value,
/// `"Greetings!"`.
///
/// - Parameters:
/// - optional: An optional value.
/// - defaultValue: A value to use as a default. `defaultValue` and
/// `optional` have the same type.
@_transparent
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T?)
rethrows -> T? {
switch optional {
case .some(let value):
return value
case .none:
return try defaultValue()
}
}
//===----------------------------------------------------------------------===//
// Bridging
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
extension Optional : _ObjectiveCBridgeable {
// The object that represents `none` for an Optional of this type.
@inlinable // FIXME(sil-serialize-all)
internal static var _nilSentinel : AnyObject {
@_silgen_name("_swift_Foundation_getOptionalNilSentinelObject")
get
}
@inlinable // FIXME(sil-serialize-all)
public func _bridgeToObjectiveC() -> AnyObject {
// Bridge a wrapped value by unwrapping.
if let value = self {
return _bridgeAnythingToObjectiveC(value)
}
// Bridge nil using a sentinel.
return type(of: self)._nilSentinel
}
@inlinable // FIXME(sil-serialize-all)
public static func _forceBridgeFromObjectiveC(
_ source: AnyObject,
result: inout Optional<Wrapped>?
) {
// Map the nil sentinel back to .none.
// NB that the signature of _forceBridgeFromObjectiveC adds another level
// of optionality, so we need to wrap the immediate result of the conversion
// in `.some`.
if source === _nilSentinel {
result = .some(.none)
return
}
// Otherwise, force-bridge the underlying value.
let unwrappedResult = source as! Wrapped
result = .some(.some(unwrappedResult))
}
@inlinable // FIXME(sil-serialize-all)
public static func _conditionallyBridgeFromObjectiveC(
_ source: AnyObject,
result: inout Optional<Wrapped>?
) -> Bool {
// Map the nil sentinel back to .none.
// NB that the signature of _forceBridgeFromObjectiveC adds another level
// of optionality, so we need to wrap the immediate result of the conversion
// in `.some` to indicate success of the bridging operation, with a nil
// result.
if source === _nilSentinel {
result = .some(.none)
return true
}
// Otherwise, try to bridge the underlying value.
if let unwrappedResult = source as? Wrapped {
result = .some(.some(unwrappedResult))
return true
} else {
result = .none
return false
}
}
@inlinable // FIXME(sil-serialize-all)
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)
-> Optional<Wrapped> {
if let nonnullSource = source {
// Map the nil sentinel back to none.
if nonnullSource === _nilSentinel {
return .none
} else {
return .some(nonnullSource as! Wrapped)
}
} else {
// If we unexpectedly got nil, just map it to `none` too.
return .none
}
}
}
#endif
| apache-2.0 |
ReiVerdugo/uikit-fundamentals | MYOA/MYOA/ViewController.swift | 1 | 512 | //
// ViewController.swift
// MYOA
//
// Created by Reinaldo Verdugo on 24/10/16.
// Copyright © 2016 Reinaldo Verdugo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
Hypercubesoft/HCFramework | HCFramework/Managers/HCImagePicker.swift | 1 | 6357 | //
// HCImagePicker.swift
// iOSTemplate
//
// Created by Hypercube 2 on 10/3/17.
// Copyright © 2017 Hypercube. All rights reserved.
//
import UIKit
public typealias CompletionHandler = (_ success:Bool, _ res:AnyObject?) -> Void
// NOTE: Add NSCameraUsageDescription to plist file
open class HCImagePicker: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
open var imageSelectionInProgress = false
open var imageSelectCompletitionHandler:CompletionHandler?
public static let sharedManager: HCImagePicker =
{
let instance = HCImagePicker()
return instance
}()
/// Open UIImagePickerController with Camera like source type with the possibility of setting Completition Handler Function.
///
/// - Parameters:
/// - completitionHandler: Completion Handler Function. By default it is not set.
open func takePictureFromCamera(allowEditing: Bool = true, completitionHandler:CompletionHandler? = nil)
{
self.imageSelectCompletitionHandler = completitionHandler
self.openCamera(allowEditing: allowEditing)
}
/// Open UIImagePickerController with PhotosAlbum like source type with the possibility of setting Completition Handler Function.
///
/// - Parameters:
/// - completitionHandler: Completion Handler Function. By default it is not set.
open func getPictureFromGallery(allowEditing: Bool = true, completitionHandler:CompletionHandler? = nil)
{
self.imageSelectCompletitionHandler = completitionHandler
self.openGallery(allowEditing: allowEditing)
}
/// Open dialog to choose the image source from where the image will be obtained.
///
/// - Parameters:
/// - title: Dialog title. Default value is "Select picture".
/// - fromCameraButtonTitle: From camera button title. Default value is "From Camera".
/// - fromGalleryButtonTitle: From gallery button title. Default value is "From Gallery".
/// - cancelButtonTitle: Cancel button title. Default value is "Cancel".
/// - completitionHandler: Completion Handler Function. By default it is not set.
open func selectPicture(title:String = "Select picture", fromCameraButtonTitle:String = "From Camera", fromGalleryButtonTitle:String = "From Gallery", cancelButtonTitle:String = "Cancel", allowEditing: Bool = true, completitionHandler:CompletionHandler? = nil)
{
self.imageSelectCompletitionHandler = completitionHandler
HCDialog.showDialogWithMultipleActions(message: "", title: title, alertButtonTitles:
[
fromCameraButtonTitle,
fromGalleryButtonTitle,
cancelButtonTitle]
, alertButtonActions:
[
{ (alert) in
self.openCamera(allowEditing: allowEditing)
},
{ (alert) in
self.openGallery(allowEditing: allowEditing)
},
nil
], alertButtonStyles:
[
.default,
.default,
.cancel
])
}
/// Open UIImagePickerController with Camera like source type
private func openCamera(allowEditing: Bool)
{
if UIImagePickerController.isSourceTypeAvailable(.camera)
{
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.allowsEditing = allowEditing
imageSelectionInProgress = true
UIApplication.shared.keyWindow?.rootViewController?.present(imagePicker, animated: true, completion: nil)
}
}
/// Open UIImagePickerController with PhotosAlbum like source type
private func openGallery(allowEditing: Bool)
{
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum;
imagePicker.allowsEditing = allowEditing
imageSelectionInProgress = true
UIApplication.shared.keyWindow?.rootViewController?.present(imagePicker, animated: true, completion: nil)
}
}
/// Fix orientation for image. This is useful in some cases, for example, when image taken from camera has wrong orientation after upload to server.
///
/// - Parameter img: Image for which we need to fix orientation
/// - Returns: Image with valid orientation
private func fixOrientation(img: UIImage) -> UIImage {
if (img.imageOrientation == .up) {
return img
}
UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale)
let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
img.draw(in: rect)
let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return normalizedImage
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true) {
if picker.allowsEditing
{
if let image = info[UIImagePickerController.InfoKey.editedImage.rawValue] as? UIImage {
if let completion = self.imageSelectCompletitionHandler
{
completion(true, self.fixOrientation(img: image))
}
}
} else {
if let image = info[UIImagePickerController.InfoKey.originalImage.rawValue] as? UIImage {
if let completion = self.imageSelectCompletitionHandler
{
completion(true, self.fixOrientation(img: image))
}
}
}
}
}
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: {
if let completion = self.imageSelectCompletitionHandler
{
completion(false, nil)
}
})
}
}
| mit |
jakeheis/Shout | Sources/Shout/SSH.swift | 1 | 8648 | //
// SSH.swift
// Shout
//
// Created by Jake Heiser on 3/4/18.
//
import Foundation
import Socket
/// Manages an SSH session
public class SSH {
public enum PtyType: String {
case vanilla
case vt100
case vt102
case vt220
case ansi
case xterm
}
/// Connects to a remote server and opens an SSH session
///
/// - Parameters:
/// - host: the host to connect to
/// - port: the port to connect to; default 22
/// - username: the username to login with
/// - authMethod: the authentication method to use while logging in
/// - execution: the block executed with the open, authenticated SSH session
/// - Throws: SSHError if the session fails at any point
public static func connect(host: String, port: Int32 = 22, username: String, authMethod: SSHAuthMethod, execution: (_ ssh: SSH) throws -> ()) throws {
let ssh = try SSH(host: host, port: port)
try ssh.authenticate(username: username, authMethod: authMethod)
try execution(ssh)
}
let session: Session
private let sock: Socket
public var ptyType: PtyType? = nil
/// Creates a new SSH session
///
/// - Parameters:
/// - host: the host to connect to
/// - port: the port to connect to; default 22
/// - timeout: timeout to use (in msec); default 0
/// - Throws: SSHError if the SSH session couldn't be created
public init(host: String, port: Int32 = 22, timeout: UInt = 0) throws {
self.sock = try Socket.create()
self.session = try Session()
session.blocking = 1
try sock.connect(to: host, port: port, timeout: timeout)
try session.handshake(over: sock)
}
/// Authenticate the session using a public/private key pair
///
/// - Parameters:
/// - username: the username to login with
/// - privateKey: the path to the private key
/// - publicKey: the path to the public key; defaults to private key path + ".pub"
/// - passphrase: the passphrase encrypting the key; defaults to nil
/// - Throws: SSHError if authentication fails
public func authenticate(username: String, privateKey: String, publicKey: String? = nil, passphrase: String? = nil) throws {
let key = SSHKey(privateKey: privateKey, publicKey: publicKey, passphrase: passphrase)
try authenticate(username: username, authMethod: key)
}
/// Authenticate the session using a password
///
/// - Parameters:
/// - username: the username to login with
/// - password: the user's password
/// - Throws: SSHError if authentication fails
public func authenticate(username: String, password: String) throws {
try authenticate(username: username, authMethod: SSHPassword(password))
}
/// Authenticate the session using the SSH agent
///
/// - Parameter username: the username to login with
/// - Throws: SSHError if authentication fails
public func authenticateByAgent(username: String) throws {
try authenticate(username: username, authMethod: SSHAgent())
}
/// Authenticate the session using the given authentication method
///
/// - Parameters:
/// - username: the username to login with
/// - authMethod: the authentication method to use
/// - Throws: SSHError if authentication fails
public func authenticate(username: String, authMethod: SSHAuthMethod) throws {
try authMethod.authenticate(ssh: self, username: username)
}
/// Execute a command on the remote server
///
/// - Parameters:
/// - command: the command to execute
/// - silent: whether or not to execute the command silently; defaults to false
/// - Returns: exit code of the command
/// - Throws: SSHError if the command couldn't be executed
@discardableResult
public func execute(_ command: String, silent: Bool = false) throws -> Int32 {
return try execute(command, output: { (output) in
if silent == false {
print(output, terminator: "")
fflush(stdout)
}
})
}
/// Execute a command on the remote server and capture the output
///
/// - Parameter command: the command to execute
/// - Returns: a tuple with the exit code of the command and the output of the command
/// - Throws: SSHError if the command couldn't be executed
public func capture(_ command: String) throws -> (status: Int32, output: String) {
var ongoing = ""
let status = try execute(command) { (output) in
ongoing += output
}
return (status, ongoing)
}
/// Execute a command on the remote server
///
/// - Parameters:
/// - command: the command to execute
/// - output: block handler called every time a chunk of command output is received
/// - Returns: exit code of the command
/// - Throws: SSHError if the command couldn't be executed
public func execute(_ command: String, output: ((_ output: String) -> ())) throws -> Int32 {
let channel = try session.openCommandChannel()
if let ptyType = ptyType {
try channel.requestPty(type: ptyType.rawValue)
}
try channel.exec(command: command)
var dataLeft = true
while dataLeft {
switch channel.readData() {
case .data(let data):
guard let str = String(data: data, encoding: .utf8) else {
throw SSHError.genericError("SSH failed to create string using UTF8 encoding")
}
output(str)
case .done:
dataLeft = false
case .eagain:
break
case .error(let error):
throw error
}
}
try channel.close()
return channel.exitStatus()
}
/// Upload a file from the local device to the remote server
///
/// - Parameters:
/// - localURL: the path to the existing file on the local device
/// - remotePath: the location on the remote server whether the file should be uploaded to
/// - permissions: the file permissions to create the new file with; defaults to FilePermissions.default
/// - Throws: SSHError if local file can't be read or upload fails
@discardableResult
public func sendFile(localURL: URL, remotePath: String, permissions: FilePermissions = .default) throws -> Int32 {
guard let resources = try? localURL.resourceValues(forKeys: [.fileSizeKey]),
let fileSize = resources.fileSize,
let inputStream = InputStream(url: localURL) else {
throw SSHError.genericError("couldn't open file at \(localURL)")
}
let channel = try session.openSCPChannel(fileSize: Int64(fileSize), remotePath: remotePath, permissions: permissions)
inputStream.open()
defer { inputStream.close() }
let bufferSize = Int(Channel.packetDefaultSize)
var buffer = Data(capacity: bufferSize)
while inputStream.hasBytesAvailable {
let bytesRead: Int = try buffer.withUnsafeMutableBytes {
guard let pointer = $0.bindMemory(to: UInt8.self).baseAddress else {
throw SSHError.genericError("SSH write failed to bind buffer memory")
}
return inputStream.read(pointer, maxLength: bufferSize)
}
if bytesRead == 0 { break }
var bytesSent = 0
while bytesSent < bytesRead {
let chunk = bytesSent == 0 ? buffer : buffer.advanced(by: bytesSent)
switch channel.write(data: chunk, length: bytesRead - bytesSent) {
case .written(let count):
bytesSent += count
case .eagain:
break
case .error(let error):
throw error
}
}
}
try channel.sendEOF()
try channel.waitEOF()
try channel.close()
try channel.waitClosed()
return channel.exitStatus()
}
/// Open an SFTP session with the remote server
///
/// - Returns: the opened SFTP session
/// - Throws: SSHError if an SFTP session could not be opened
public func openSftp() throws -> SFTP {
return try session.openSftp()
}
}
| mit |
honghaoz/2048-Solver-AI | 2048 AI/AI/AI-Expectimax.swift | 1 | 12636 | // Copyright © 2019 ChouTi. All rights reserved.
import Foundation
class AIExpectimax {
var dimension: Int = 0
weak var gameModel: Game2048!
init(gameModel: Game2048) {
self.gameModel = gameModel
self.dimension = gameModel.dimension
}
func nextCommand() -> MoveCommand? {
if GameModelHelper.isGameEnded(&gameModel.gameBoard) {
return nil
} else {
let (command, _) = _nextCommand(&gameModel.gameBoard, level: 0)
return command
}
}
func _nextCommand(_ gameBoard: inout SquareGameBoard<UnsafeMutablePointer<Tile>>, level: Int = 0, maxDepth: Int = 3) -> (MoveCommand?, Double) {
var choosenCommand: MoveCommand?
var maxScore: Double = 0.0
let commands = GameModelHelper.validMoveCommandsInGameBoard(&gameBoard, shuffle: false)
for command in commands {
// Copy a new board, Alloc
var copyGameBoard = GameModelHelper.copyGameBoard(&gameBoard)
// Perform command
_ = GameModelHelper.performMoveCommand(command, onGameBoard: ©GameBoard)
// var (score, (x, y)) = evaluateUsingMonoHeuristic(GameModelHelper.intGameBoardFromGameBoard(©GameBoard))
// GameModelHelper.insertTile(©GameBoard, pos: (y, x), value: 2)
var score = heuristicSMonotonic(©GameBoard)
GameModelHelper.insertTileAtRandomLocation(©GameBoard)
if level < maxDepth {
let (nextCommand, nextLevelScore) = _nextCommand(©GameBoard, level: level + 1, maxDepth: maxDepth)
if nextCommand != nil {
score += nextLevelScore * pow(0.9, Double(level) + 1.0)
}
}
if score > maxScore {
maxScore = score
choosenCommand = command
}
// Dealloc
GameModelHelper.deallocGameBoard(©GameBoard)
// Expectimax
// score += heuristicScore(&gameBoardCopy)
// // availableSpot
// let availableSpots = GameModelHelper.gameBoardEmptySpots(&gameBoardCopy)
// if availableSpots.count == 0 {
// // Dealloc
// GameModelHelper.deallocGameBoard(&gameBoardCopy)
// continue
// }
//
// for eachAvailableSpot in availableSpots {
// // Try to insert 2
// GameModelHelper.insertTile(&gameBoardCopy, pos: eachAvailableSpot, value: 2)
// score += heuristicScore(&gameBoardCopy) * 0.85 * powf(0.25, Float(level))
// var (_, nextLevelScore) = _nextCommand(&gameBoardCopy, level: level + 1, maxDepth: maxDepth)
// score += nextLevelScore
//
// // Restore
// gameBoardCopy[eachAvailableSpot.0, eachAvailableSpot.1].pointee = .Empty
//
// // Try to insert 4
// GameModelHelper.insertTile(&gameBoardCopy, pos: eachAvailableSpot, value: 4)
// score += heuristicScore(&gameBoardCopy) * 0.15 * powf(0.25, Float(level))
// (_, nextLevelScore) = _nextCommand(&gameBoardCopy, level: level + 1, maxDepth: maxDepth)
// score += nextLevelScore
//
// // Restore
// gameBoardCopy[eachAvailableSpot.0, eachAvailableSpot.1].pointee = .Empty
// }
}
return (choosenCommand, maxScore)
}
// MARK: Heuristic
func heuristicScore(_ gameBoard: inout SquareGameBoard<UnsafeMutablePointer<Tile>>) -> Double {
let myScore = heuristicSMonotonic(&gameBoard)
return myScore
}
func heuristicSMonotonic(_ gameBoard: inout SquareGameBoard<UnsafeMutablePointer<Tile>>) -> Double {
let ratio: Double = 0.25
var maxScore: Double = -1.0
// Construct 8 different patterns into one linear array
// Direction for the first row
for startDirection in 0..<2 {
// Whether flip the board
for flip in 0..<2 {
// Whether it's row or column
for rOrC in 0..<2 {
var oneDimension = [UnsafeMutablePointer<Tile>]()
for row in stride(from: 0, to: dimension, by: 2) {
let firstRow = (flip != 0) ? (dimension - 1 - row) : row
if rOrC != 0 {
oneDimension.append(contentsOf: gameBoard.getRow(firstRow, reversed: startDirection != 0))
} else {
oneDimension.append(contentsOf: gameBoard.getColumn(firstRow, reversed: startDirection != 0))
}
let secondRow = (flip != 0) ? (dimension - 1 - row - 1) : row + 1
if secondRow >= 0, secondRow < dimension {
if rOrC != 0 {
oneDimension.append(contentsOf: gameBoard.getRow(firstRow, reversed: startDirection == 0))
} else {
oneDimension.append(contentsOf: gameBoard.getColumn(firstRow, reversed: startDirection == 0))
}
}
}
var weight: Double = 1.0
var result: Double = 0.0
for (_, tile) in oneDimension.enumerated() {
switch tile.pointee {
case .Empty:
break
case let .Number(num):
result += Double(num) * weight
}
weight *= ratio
}
if result > maxScore {
maxScore = result
}
}
}
}
return maxScore
}
func heuristicFreeTiles(_ gameBoard: inout SquareGameBoard<UnsafeMutablePointer<Tile>>) -> Float {
let maxLimit: Float = Float(dimension * dimension)
return Float(GameModelHelper.gameBoardEmptySpotsCount(&gameBoard)) / maxLimit * 12
}
func heuristicMonotonicity(_ gameBoard: inout SquareGameBoard<UnsafeMutablePointer<Tile>>) -> Float {
let r: Float = 0.25
let dimension = gameBoard.dimension
var maxResult: Float = 0.0
var result: Float = 0.0
// Top Left
for i in 0..<dimension {
for j in 0..<dimension {
switch gameBoard[i, j].pointee {
case .Empty:
continue
case let .Number(num):
result += Float(num) * pow(r, Float(i + j))
}
}
}
if result > maxResult {
maxResult = result
}
// Top Right
result = 0
for i in 0..<dimension {
for j in stride(from: dimension - 1, to: -1, by: -1) {
switch gameBoard[i, j].pointee {
case .Empty:
continue
case .Number:
result += pow(r, Float(i + j))
}
}
}
if result > maxResult {
maxResult = result
}
// Bottom Left
result = 0
for i in stride(from: dimension - 1, to: -1, by: -1) {
for j in 0..<dimension {
switch gameBoard[i, j].pointee {
case .Empty:
continue
case .Number:
result += pow(r, Float(i + j))
}
}
}
if result > maxResult {
maxResult = result
}
// Bottom Right
result = 0
for i in stride(from: dimension - 1, to: -1, by: -1) {
for j in stride(from: dimension - 1, to: -1, by: -1) {
switch gameBoard[i, j].pointee {
case .Empty:
continue
case .Number:
result += pow(r, Float(i + j))
}
}
}
if result > maxResult {
maxResult = result
}
return maxResult
}
private func evaluateUsingMonoHeuristic(gameboard: [[Int]], ratio: Double = 0.25) -> (Double, (Int, Int)) {
let d = gameboard.count
var hasZero = false
for i in 0..<d {
for j in 0..<d {
if gameboard[i][j] == 0 {
hasZero = true
}
}
}
assert(hasZero == true, "")
let yRange = (0...gameboard.count - 1).map { $0 }
let yRangeReverse = Array((0...gameboard.count - 1).map { $0 }.reversed())
let xRange = yRange
let xRangeReverse = yRangeReverse
let size = gameboard.count
// Array that contains evaluation results and initial tiles
var results: [Double] = [Double]()
var initialTiles: [(Int, Int)] = [(Int, Int)]()
// Row first, col first
var tempResult = 0.0
var initialTile: (Int, Int) = (-1, -1)
var reverse = false
var weight = 1.0
for j in yRange {
let jCopy = j
for i in xRange {
let iCopy = !reverse ? i : size - i - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x, y) = (initialTile.0, initialTile.1)
initialTiles.append((x, y))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for j in yRange {
let jCopy = j
for i in xRangeReverse {
let iCopy = !reverse ? i : size - i - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x2, y2) = (initialTile.0, initialTile.1)
initialTiles.append((x2, y2))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for i in xRange {
let iCopy = i
for j in yRange {
let jCopy = !reverse ? j : size - j - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x3, y3) = (initialTile.0, initialTile.1)
initialTiles.append((x3, y3))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for i in xRange {
let iCopy = i
for j in yRangeReverse {
let jCopy = !reverse ? j : size - j - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x4, y4) = (initialTile.0, initialTile.1)
initialTiles.append((x4, y4))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for j in yRangeReverse {
let jCopy = j
for i in xRangeReverse {
let iCopy = !reverse ? i : size - i - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x5, y5) = (initialTile.0, initialTile.1)
initialTiles.append((x5, y5))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for j in yRangeReverse {
let jCopy = j
for i in xRange {
let iCopy = !reverse ? i : size - i - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x6, y6) = (initialTile.0, initialTile.1)
initialTiles.append((x6, y6))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for i in xRangeReverse {
let iCopy = i
for j in yRange {
let jCopy = !reverse ? j : size - j - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x7, y7) = (initialTile.0, initialTile.1)
initialTiles.append((x7, y7))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for i in xRangeReverse {
let iCopy = i
for j in yRangeReverse {
let jCopy = !reverse ? j : size - j - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x8, y8) = (initialTile.0, initialTile.1)
initialTiles.append((x8, y8))
let maxIndex = results.findMaxIndex()
return (results[maxIndex], initialTiles[maxIndex])
}
}
| gpl-2.0 |
okerivy/AlgorithmLeetCode | AlgorithmLeetCode/AlgorithmLeetCode/M_82_RemoveDuplicatesFromSortedListII.swift | 1 | 2647 | //
// M_82_RemoveDuplicatesFromSortedListII.swift
// AlgorithmLeetCode
//
// Created by okerivy on 2017/3/23.
// Copyright © 2017年 okerivy. All rights reserved.
//
import Foundation
// MARK: - 题目名称: 82. Remove Duplicates from Sorted List II
/* MARK: - 所属类别:
标签: Linked List
相关题目:
*/
/* MARK: - 题目英文:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
*/
/* MARK: - 题目翻译:
给定一个已排序的链表,删除所有具有重复编号的节点,只留下与原始列表不同的数字。
例如,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
*/
/* MARK: - 解题思路:
需要在一个有序的链表里面删除所有的重复元素的节点。因为不同于上题可以保留一个,这次需要全部删除,所以我们遍历的时候需要记录一个prev节点,用来处理删除节点之后节点重新连接的问题。
*/
/* MARK: - 复杂度分析:
*/
// MARK: - 代码:
private class Solution {
func deleteDuplicates(_ head: SinglyListNode?) -> SinglyListNode? {
if head == nil || head?.next == nil {
return head
}
var p = head
// 记录初始位置
let dummy = CreatSinglyList().convertArrayToSinglyList([-1])
dummy?.next = head
var prev = dummy
while p != nil && p?.next != nil {
if p?.next?.val == p?.val {
//如果有重复,则继续遍历,直到不重复的节点
var n = p?.next?.next
while n != nil {
if p?.val != n?.val {
break
}
n = n?.next
}
prev?.next = n
p = n
} else {
//如果没有重复,则prev为p,next为p->next
prev = p
p = p?.next
}
}
return dummy?.next
}
}
// MARK: - 测试代码:
func RemoveDuplicatesFromSortedListII() {
// 单链表
var head1 = CreatSinglyList().convertArrayToSinglyList([1, 2, 3, 3, 5, 6, 6, 6, 7, 8])
var head2 = CreatSinglyList().convertArrayToSinglyList([1, 1, 1, 1, 5, 6, 6, 6, 7, 8])
head1 = Solution().deleteDuplicates(head1)
head2 = Solution().deleteDuplicates(head2)
print(head1 ?? "没有找到")
print(head2 ?? "没有找到")
}
| mit |
BillZong/ChessManualOfGo | ChessManualOfGo/ChessManualOfGo/AppDelegate.swift | 1 | 2146 | //
// AppDelegate.swift
// ChessManualOfGo
//
// Created by BillZong on 16/1/5.
// Copyright © 2016年 BillZong. 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 |
xuech/OMS-WH | OMS-WH/Utilities/Libs/DatePickerDialog.swift | 1 | 12832 | import Foundation
import UIKit
private extension Selector {
static let buttonTapped = #selector(DatePickerDialog.buttonTapped)
static let deviceOrientationDidChange = #selector(DatePickerDialog.deviceOrientationDidChange)
}
open class DatePickerDialog: UIView {
public typealias DatePickerCallback = ( Date? ) -> Void
// MARK: - Constants
private let kDatePickerDialogDefaultButtonHeight: CGFloat = 50
private let kDatePickerDialogDefaultButtonSpacerHeight: CGFloat = 1
private let kDatePickerDialogCornerRadius: CGFloat = 7
private let kDatePickerDialogDoneButtonTag: Int = 1
// MARK: - Views
private var dialogView: UIView!
private var titleLabel: UILabel!
open var datePicker: UIDatePicker!
private var cancelButton: UIButton!
private var doneButton: UIButton!
// MARK: - Variables
private var defaultDate: Date?
private var datePickerMode: UIDatePickerMode?
private var callback: DatePickerCallback?
var showCancelButton:Bool = false
var locale: Locale?
private var textColor: UIColor!
private var buttonColor: UIColor!
private var font: UIFont!
// MARK: - Dialog initialization
public init(textColor: UIColor = UIColor.black, buttonColor: UIColor = UIColor.blue, font: UIFont = .boldSystemFont(ofSize: 15), locale: Locale? = nil, showCancelButton:Bool = true) {
super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
self.textColor = textColor
self.buttonColor = buttonColor
self.font = font
self.showCancelButton = showCancelButton
self.locale = locale
setupView()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setupView() {
self.dialogView = createContainerView()
self.dialogView!.layer.shouldRasterize = true
self.dialogView!.layer.rasterizationScale = UIScreen.main.scale
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
self.dialogView!.layer.opacity = 0.5
self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1)
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.addSubview(self.dialogView!)
}
/// Handle device orientation changes
@objc func deviceOrientationDidChange(_ notification: Notification) {
self.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
let screenSize = countScreenSize()
let dialogSize = CGSize(width: 300, height: 230 + kDatePickerDialogDefaultButtonHeight + kDatePickerDialogDefaultButtonSpacerHeight)
dialogView.frame = CGRect(x: (screenSize.width - dialogSize.width) / 2, y: (screenSize.height - dialogSize.height) / 2, width: dialogSize.width, height: dialogSize.height)
}
/// Create the dialog view, and animate opening the dialog
open func show(_ title: String, doneButtonTitle: String = "Done", cancelButtonTitle: String = "Cancel", defaultDate: Date = Date(), minimumDate: Date? = nil, maximumDate: Date? = nil, datePickerMode: UIDatePickerMode = .dateAndTime, callback: @escaping DatePickerCallback) {
self.titleLabel.text = title
self.doneButton.setTitle(doneButtonTitle, for: .normal)
if showCancelButton {
self.cancelButton.setTitle(cancelButtonTitle, for: .normal)
}
self.datePickerMode = datePickerMode
self.callback = callback
self.defaultDate = defaultDate
self.datePicker.datePickerMode = self.datePickerMode ?? UIDatePickerMode.date
self.datePicker.date = self.defaultDate ?? Date()
self.datePicker.maximumDate = maximumDate
self.datePicker.minimumDate = minimumDate
if let locale = self.locale {
self.datePicker.locale = locale
}
/* Add dialog to main window */
guard let appDelegate = UIApplication.shared.delegate else { fatalError() }
guard let window = appDelegate.window else { fatalError() }
window?.addSubview(self)
window?.bringSubview(toFront: self)
window?.endEditing(true)
NotificationCenter.default.addObserver(self, selector: .deviceOrientationDidChange, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
/* Anim */
UIView.animate(
withDuration: 0.2,
delay: 0,
options: .curveEaseInOut,
animations: {
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
self.dialogView!.layer.opacity = 1
self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1)
}
)
}
/// Dialog close animation then cleaning and removing the view from the parent
private func close() {
NotificationCenter.default.removeObserver(self)
let currentTransform = self.dialogView.layer.transform
let startRotation = (self.value(forKeyPath: "layer.transform.rotation.z") as? NSNumber) as? Double ?? 0.0
let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + .pi * 270 / 180), 0, 0, 0)
self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1))
self.dialogView.layer.opacity = 1
UIView.animate(
withDuration: 0.2,
delay: 0,
options: [],
animations: {
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1))
self.dialogView.layer.opacity = 0
}) { (finished) in
for v in self.subviews {
v.removeFromSuperview()
}
self.removeFromSuperview()
self.setupView()
}
}
/// Creates the container view here: create the dialog, then add the custom content and buttons
private func createContainerView() -> UIView {
let screenSize = countScreenSize()
let dialogSize = CGSize(
width: 300,
height: 230
+ kDatePickerDialogDefaultButtonHeight
+ kDatePickerDialogDefaultButtonSpacerHeight)
// For the black background
self.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
// This is the dialog's container; we attach the custom content and the buttons to this one
let dialogContainer = UIView(frame: CGRect(x: (screenSize.width - dialogSize.width) / 2, y: (screenSize.height - dialogSize.height) / 2, width: dialogSize.width, height: dialogSize.height))
// First, we style the dialog to match the iOS8 UIAlertView >>>
let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer)
gradient.frame = dialogContainer.bounds
gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).cgColor,
UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).cgColor,
UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).cgColor]
let cornerRadius = kDatePickerDialogCornerRadius
gradient.cornerRadius = cornerRadius
dialogContainer.layer.insertSublayer(gradient, at: 0)
dialogContainer.layer.cornerRadius = cornerRadius
dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).cgColor
dialogContainer.layer.borderWidth = 1
dialogContainer.layer.shadowRadius = cornerRadius + 5
dialogContainer.layer.shadowOpacity = 0.1
dialogContainer.layer.shadowOffset = CGSize(width: 0 - (cornerRadius + 5) / 2, height: 0 - (cornerRadius + 5) / 2)
dialogContainer.layer.shadowColor = UIColor.black.cgColor
dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).cgPath
// There is a line above the button
let lineView = UIView(frame: CGRect(x: 0, y: dialogContainer.bounds.size.height - kDatePickerDialogDefaultButtonHeight - kDatePickerDialogDefaultButtonSpacerHeight, width: dialogContainer.bounds.size.width, height: kDatePickerDialogDefaultButtonSpacerHeight))
lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1)
dialogContainer.addSubview(lineView)
//Title
self.titleLabel = UILabel(frame: CGRect(x: 10, y: 10, width: 280, height: 30))
self.titleLabel.textAlignment = .center
self.titleLabel.textColor = self.textColor
self.titleLabel.font = self.font.withSize(17)
dialogContainer.addSubview(self.titleLabel)
self.datePicker = UIDatePicker(frame: CGRect(x: 0, y: 30, width: 0, height: 0))
self.datePicker.setValue(self.textColor, forKeyPath: "textColor")
self.datePicker.autoresizingMask = .flexibleRightMargin
self.datePicker.frame.size.width = 300
self.datePicker.frame.size.height = 216
dialogContainer.addSubview(self.datePicker)
// Add the buttons
addButtonsToView(container: dialogContainer)
return dialogContainer
}
/// Add buttons to container
private func addButtonsToView(container: UIView) {
var buttonWidth = container.bounds.size.width / 2
var leftButtonFrame = CGRect(
x: 0,
y: container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
width: buttonWidth,
height: kDatePickerDialogDefaultButtonHeight
)
var rightButtonFrame = CGRect(
x: buttonWidth,
y: container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
width: buttonWidth,
height: kDatePickerDialogDefaultButtonHeight
)
if showCancelButton == false {
buttonWidth = container.bounds.size.width
leftButtonFrame = CGRect()
rightButtonFrame = CGRect(
x: 0,
y: container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
width: buttonWidth,
height: kDatePickerDialogDefaultButtonHeight
)
}
let interfaceLayoutDirection = UIApplication.shared.userInterfaceLayoutDirection
let isLeftToRightDirection = interfaceLayoutDirection == .leftToRight
if showCancelButton {
self.cancelButton = UIButton(type: .custom) as UIButton
self.cancelButton.frame = isLeftToRightDirection ? leftButtonFrame : rightButtonFrame
self.cancelButton.setTitleColor(UIColor.lightGray, for: .normal)
self.cancelButton.setTitleColor(UIColor.lightGray, for: .highlighted)
self.cancelButton.titleLabel!.font = self.font.withSize(14)
self.cancelButton.layer.cornerRadius = kDatePickerDialogCornerRadius
self.cancelButton.addTarget(self, action: .buttonTapped, for: .touchUpInside)
container.addSubview(self.cancelButton)
}
self.doneButton = UIButton(type: .custom) as UIButton
self.doneButton.frame = isLeftToRightDirection ? rightButtonFrame : leftButtonFrame
self.doneButton.tag = kDatePickerDialogDoneButtonTag
self.doneButton.setTitleColor(self.buttonColor, for: .normal)
self.doneButton.setTitleColor(self.buttonColor, for: .highlighted)
self.doneButton.titleLabel!.font = self.font.withSize(14)
self.doneButton.layer.cornerRadius = kDatePickerDialogCornerRadius
self.doneButton.addTarget(self, action: .buttonTapped, for: .touchUpInside)
container.addSubview(self.doneButton)
}
@objc func buttonTapped(sender: UIButton!) {
if sender.tag == kDatePickerDialogDoneButtonTag {
self.callback?(self.datePicker.date)
} else {
self.callback?(nil)
}
close()
}
// MARK: - Helpers
/// Count and return the screen's size
func countScreenSize() -> CGSize {
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
return CGSize(width: screenWidth, height: screenHeight)
}
}
| mit |
danger/danger-swift | Sources/Danger/DangerResults.swift | 1 | 1019 | import Foundation
// MARK: - Violation
/// The result of a warn, message, or fail.
public struct Violation: Encodable {
let message: String
let file: String?
let line: Int?
init(message: String, file: String? = nil, line: Int? = nil) {
self.message = message
self.file = file
self.line = line
}
}
/// Meta information for showing in the text info
public struct Meta: Encodable {
let runtimeName = "Danger Swift"
let runtimeHref = "https://danger.systems/swift"
}
// MARK: - Results
/// The representation of what running a Dangerfile generates.
struct DangerResults: Encodable {
/// Failed messages.
var fails = [Violation]()
/// Messages for info.
var warnings = [Violation]()
/// A set of messages to show inline.
var messages = [Violation]()
/// Markdown messages to attach at the bottom of the comment.
var markdowns = [Violation]()
/// Information to pass back to Danger JS about the runtime
let meta = Meta()
}
| mit |
craftsmanship-toledo/katangapp-ios | Katanga/ViewModels/FavoriteBusStopsViewModel.swift | 1 | 1024 | /**
* Copyright 2016-today Software Craftmanship Toledo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*!
@author Víctor Galán
*/
import Foundation
import RxCocoa
struct FavoriteBusStopsViewModel {
let busStopRepository: BusStopRepository
init(busStopRepository: BusStopRepository = BusStopRepository()) {
self.busStopRepository = busStopRepository
}
func removeFavorite(busStop: BusStop) {
busStopRepository.remove(busStop)
}
func getFavorites() -> [BusStop] {
return busStopRepository.getAll()
}
}
| apache-2.0 |
Constructor-io/constructorio-client-swift | AutocompleteClient/FW/Logic/Result/CIOResult.swift | 1 | 2354 | //
// CIOResult.swift
// AutocompleteClient
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
/**
Struct encapsulating a result with associated metadata and variations
*/
@objc
public class CIOResult: NSObject {
/**
The value (or name) of the result
*/
public let value: String
/**
Additional data about the result
*/
public let data: CIOResultData
/**
Terms associated with the result that was matched on
*/
public let matchedTerms: [String]
/**
Variations for the result
*/
public let variations: [CIOResult]
/**
Variations map for the result
*/
public let variationsMap: Any
/**
Additional metadata
*/
public let json: JSONObject
/**
The underlying recommendations strategy for the result (only applies to recommendations)
*/
public let strategy: CIORecommendationsStrategy
/**
Labels associated with the result item
*/
public let labels: [String: Bool]
/**
Create a result object
- Parameters:
- json: JSON data from the server response
*/
public init?(json: JSONObject) {
guard let dataObj = json["data"] as? JSONObject else { return nil }
guard let value = json["value"] as? String else { return nil }
guard let data = CIOResultData(json: dataObj) else { return nil }
let matchedTerms = (json["matched_terms"] as? [String]) ?? [String]()
let variationsObj = json["variations"] as? [JSONObject]
let variations: [CIOResult] = variationsObj?.compactMap { obj in return CIOResult(json: obj) } ?? []
let variationsMap = json["variations_map"] as Any
let strategyData = json["strategy"] as? JSONObject ?? [String: Any]()
let labels = json["labels"] as? [String: Bool] ?? [:]
let strategy = CIORecommendationsStrategy(json: strategyData)!
self.value = value
self.data = data
self.matchedTerms = matchedTerms
self.variations = variations
self.json = json
self.strategy = strategy
self.variationsMap = variationsMap
self.labels = labels
}
}
extension CIOResult: Identifiable {
public var id: String {
return data.id ?? "variation"
}
}
| mit |
OlegKetrar/NumberPad | Sources/NumberPad.swift | 1 | 6226 | //
// NumberPad.swift
// NumberPad
//
// Created by Oleg Ketrar on 27.11.16.
// Copyright © 2016 Oleg Ketrar. All rights reserved.
//
import UIKit
/// Number keyboard with Return button.
/// Can be configured with custom styles.
/// Can have plus (+) or dot (.) as optional button.
public final class NumberPad: UIInputView, Reusable {
/// Uses default style.
private struct DefaultStyle: KeyboardStyle {}
// MARK:
private let visualEffectView: UIVisualEffectView = {
return UIVisualEffectView(frame: CGRect.zero)
}()
private var onTextInputClosure: (String) -> Void = { _ in }
private var onBackspaceClosure: () -> Void = {}
private var onActionClosure: () -> Void = {}
private let optionalKey: Key.Optional?
// MARK: Outlets
@IBOutlet private weak var contentView: UIView!
@IBOutlet private weak var zeroButton: UIButton!
@IBOutlet private weak var optionalButton: UIButton!
@IBOutlet private weak var actionButton: UIButton!
@IBOutlet private var digitButtons: [UIButton]!
@IBOutlet private weak var backspaceButton: LongPressButton!
// MARK: Init
override public init(frame: CGRect, inputViewStyle: UIInputViewStyle) {
optionalKey = nil
super.init(frame: frame, inputViewStyle: inputViewStyle)
replaceWithNib()
defaultConfiguring()
}
required public init?(coder aDecoder: NSCoder) {
optionalKey = nil
super.init(coder: aDecoder)
replaceWithNib()
defaultConfiguring()
}
/// Creates keyboard without optional key.
public convenience init() {
self.init(optionalKey: nil)
}
/// Main initializer.
/// - parameter optionalKey: pass `nil` if you do not need optional button.
public init(optionalKey: Key.Optional?) {
self.optionalKey = optionalKey
super.init(frame: .zero, inputViewStyle: .keyboard)
replaceWithNib()
defaultConfiguring()
autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
private func defaultConfiguring() {
// adjust actionButton title font size
actionButton.titleLabel?.numberOfLines = 1
actionButton.titleLabel?.adjustsFontSizeToFitWidth = true
actionButton.titleLabel?.minimumScaleFactor = 0.5
actionButton.titleLabel?.lineBreakMode = .byClipping
// configure additional buttons
if optionalKey == nil {
optionalButton.removeFromSuperview()
backspaceButton.pinToSuperview(attribute: .right)
}
// observe continius holds
backspaceButton.addAction(forContiniusHoldWith: 0.1) { [weak self] in
self?.didPress(key: .backspace)
}
// apply default style
with(style: DefaultStyle())
}
// MARK: Actions
@IBAction private func digitButtonDidPressed(_ button: UIButton) {
// validate button tag (indexes is same as elements)
guard let buttonDigit = (0..<10).index(of: button.tag - 1) else { return }
didPress(key: .digit(buttonDigit))
}
@IBAction private func optionalButtonDidPressed() {
guard let key = optionalKey else { return }
didPress(key: .optional(key))
}
@IBAction private func actionButtonDidPressed() {
didPress(key: .action)
}
private func didPress(key: Key) {
// inform delegate
switch key {
case .digit(let digit): onTextInputClosure("\(digit)")
case .optional(.plus): onTextInputClosure("+")
case .optional(.dot): onTextInputClosure(".")
case .action: onActionClosure()
case .backspace: onBackspaceClosure()
}
// play click
switch key {
case .digit(_),
.backspace,
.optional: UIDevice.current.playInputClick()
default:
break
}
}
// MARK: Configure
/// Apply custom visual style to keyboard.
/// - parameter style: custom style.
@discardableResult
public func with(style: KeyboardStyle) -> Self {
var buttonsTuple: [(UIButton, Key)] = digitButtons.enumerated().map { ($1, .digit($0)) }
buttonsTuple.append((actionButton, .action))
buttonsTuple.append((backspaceButton, .backspace))
if let optionalKey = optionalKey {
buttonsTuple.append((optionalButton, .optional(optionalKey)))
}
buttonsTuple.forEach { (button, key) in
button.setAttributedTitle(style.attributedTitleFor(key: key, state: .normal), for: .normal)
button.setAttributedTitle(style.attributedTitleFor(key: key, state: .selected), for: .selected)
button.setAttributedTitle(style.attributedTitleFor(key: key, state: .highlighted), for: .highlighted)
button.setImage(style.imageFor(key: key, state: .normal), for: .normal)
button.setImage(style.imageFor(key: key, state: .selected), for: .selected)
button.setImage(style.imageFor(key: key, state: .highlighted), for: .highlighted)
button.setBackgroundImage(style.backgroundImageFor(key: key, state: .normal), for: .normal)
button.setBackgroundImage(style.backgroundImageFor(key: key, state: .selected), for: .selected)
button.setBackgroundImage(style.backgroundImageFor(key: key, state: .highlighted), for: .highlighted)
button.layer.borderWidth = 0.5 * style.separatorThickness
button.layer.borderColor = style.separatorColor.cgColor
}
return self
}
@discardableResult
public func onTextInput(_ closure: @escaping (String) -> Void) -> Self {
onTextInputClosure = closure
return self
}
@discardableResult
public func onBackspace(_ closure: @escaping () -> Void) -> Self {
onBackspaceClosure = closure
return self
}
@discardableResult
public func onReturn(_ closure: @escaping () -> Void) -> Self {
onActionClosure = closure
return self
}
}
extension NumberPad: UIInputViewAudioFeedback {
public var enableInputClicksWhenVisible: Bool { return true }
}
| mit |
Cezar2005/SuperChat | SuperChat/UtilityClasses.swift | 1 | 974 | import Foundation
//The service provides utility methods.
class UtilityClasses {
//The function convers a string value in format '{key: value}' to json object. The json object is a Dictionary type.
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]
if error != nil {
println(error)
}
return json
}
return nil
}
//The function checks the string for invalid characters.
func containsOnlyLetters(input: String) -> Bool {
for chr in input {
if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) {
return false
}
}
return true
}
} | lgpl-3.0 |
gregomni/swift | SwiftCompilerSources/Sources/SIL/Utils.swift | 3 | 7617 | //===--- Utils.swift - some SIL utilities ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SILBridging
//===----------------------------------------------------------------------===//
// Lists
//===----------------------------------------------------------------------===//
public protocol ListNode : AnyObject {
associatedtype Element
var next: Element? { get }
var previous: Element? { get }
/// The first node in the list. Used to implement `reversed()`.
var _firstInList: Element { get }
/// The last node in the list. Used to implement `reversed()`.
var _lastInList: Element { get }
}
public struct List<NodeType: ListNode> :
CollectionLikeSequence, IteratorProtocol where NodeType.Element == NodeType {
private var currentNode: NodeType?
public init(first: NodeType?) { currentNode = first }
public mutating func next() -> NodeType? {
if let node = currentNode {
currentNode = node.next
return node
}
return nil
}
public var first: NodeType? { currentNode }
public func reversed() -> ReverseList<NodeType> {
if let node = first {
return ReverseList(first: node._lastInList)
}
return ReverseList(first: nil)
}
}
public struct ReverseList<NodeType: ListNode> :
CollectionLikeSequence, IteratorProtocol where NodeType.Element == NodeType {
private var currentNode: NodeType?
public init(first: NodeType?) { currentNode = first }
public mutating func next() -> NodeType? {
if let node = currentNode {
currentNode = node.previous
return node
}
return nil
}
public var first: NodeType? { currentNode }
public func reversed() -> ReverseList<NodeType> {
if let node = first {
return ReverseList(first: node._firstInList)
}
return ReverseList(first: nil)
}
}
//===----------------------------------------------------------------------===//
// Sequence Utilities
//===----------------------------------------------------------------------===//
/// Types conforming to `HasName` will be displayed by their name (instead of the
/// full object) in collection descriptions.
///
/// This is useful to make collections, e.g. of BasicBlocks or Functions, readable.
public protocol HasName {
var name: String { get }
}
private struct CustomMirrorChild : CustomStringConvertible, CustomReflectable {
public var description: String
public var customMirror: Mirror { Mirror(self, children: []) }
public init(description: String) { self.description = description }
}
/// Makes a Sequence's `description` and `customMirror` formatted like Array, e.g. [a, b, c].
public protocol FormattedLikeArray : Sequence, CustomStringConvertible, CustomReflectable {
}
extension FormattedLikeArray {
/// Display a Sequence in an array like format, e.g. [a, b, c]
public var description: String {
"[" + map {
if let named = $0 as? HasName {
return named.name
}
return String(describing: $0)
}.joined(separator: ", ") + "]"
}
/// The mirror which adds the children of a Sequence, similar to `Array`.
public var customMirror: Mirror {
// If the one-line description is not too large, print that instead of the
// children in separate lines.
if description.count <= 80 {
return Mirror(self, children: [])
}
let c: [Mirror.Child] = map {
let val: Any
if let named = $0 as? HasName {
val = CustomMirrorChild(description: named.name)
} else {
val = $0
}
return (label: nil, value: val)
}
return Mirror(self, children: c, displayStyle: .collection)
}
}
/// A Sequence which is not consuming and therefore behaves like a Collection.
///
/// Many sequences in SIL and the optimizer should be collections but cannot
/// because their Index cannot conform to Comparable. Those sequences conform
/// to CollectionLikeSequence.
///
/// For convenience it also inherits from FormattedLikeArray.
public protocol CollectionLikeSequence : FormattedLikeArray {
}
public extension CollectionLikeSequence {
var isEmpty: Bool { !contains(where: { _ in true }) }
}
// Also make the lazy sequences a CollectionLikeSequence if the underlying sequence is one.
extension LazySequence : CollectionLikeSequence,
FormattedLikeArray, CustomStringConvertible, CustomReflectable
where Base: CollectionLikeSequence {}
extension FlattenSequence : CollectionLikeSequence,
FormattedLikeArray, CustomStringConvertible, CustomReflectable
where Base: CollectionLikeSequence {}
extension LazyMapSequence : CollectionLikeSequence,
FormattedLikeArray, CustomStringConvertible, CustomReflectable
where Base: CollectionLikeSequence {}
extension LazyFilterSequence : CollectionLikeSequence,
FormattedLikeArray, CustomStringConvertible, CustomReflectable
where Base: CollectionLikeSequence {}
//===----------------------------------------------------------------------===//
// String parsing
//===----------------------------------------------------------------------===//
public struct StringParser {
private var s: Substring
private let originalLength: Int
private mutating func consumeWhitespace() {
s = s.drop { $0.isWhitespace }
}
public init(_ string: String) {
s = Substring(string)
originalLength = string.count
}
mutating func isEmpty() -> Bool {
consumeWhitespace()
return s.isEmpty
}
public mutating func consume(_ str: String) -> Bool {
consumeWhitespace()
if !s.starts(with: str) { return false }
s = s.dropFirst(str.count)
return true
}
public mutating func consumeInt(withWhiteSpace: Bool = true) -> Int? {
if withWhiteSpace {
consumeWhitespace()
}
var intStr = ""
s = s.drop {
if $0.isNumber {
intStr.append($0)
return true
}
return false
}
return Int(intStr)
}
public mutating func consumeIdentifier() -> String? {
consumeWhitespace()
var name = ""
s = s.drop {
if $0.isLetter {
name.append($0)
return true
}
return false
}
return name.isEmpty ? nil : name
}
public func throwError(_ message: StaticString) throws -> Never {
throw ParsingError(message: message, position: originalLength - s.count)
}
}
public struct ParsingError : Error {
public let message: StaticString
public let position: Int
}
//===----------------------------------------------------------------------===//
// Bridging Utilities
//===----------------------------------------------------------------------===//
extension Array where Element == Value {
public func withBridgedValues<T>(_ c: (BridgedValueArray) -> T) -> T {
return self.withUnsafeBytes { valPtr in
assert(valPtr.count == self.count * 16)
return c(BridgedValueArray(data: valPtr.baseAddress, count: self.count))
}
}
}
| apache-2.0 |
watson-developer-cloud/ios-sdk | Sources/SpeechToTextV1/Models/AudioResources.swift | 1 | 1525 | /**
* (C) Copyright IBM Corp. 2018, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
Information about the audio resources from a custom acoustic model.
*/
public struct AudioResources: Codable, Equatable {
/**
The total minutes of accumulated audio summed over all of the valid audio resources for the custom acoustic model.
You can use this value to determine whether the custom model has too little or too much audio to begin training.
*/
public var totalMinutesOfAudio: Double
/**
An array of `AudioResource` objects that provides information about the audio resources of the custom acoustic
model. The array is empty if the custom model has no audio resources.
*/
public var audio: [AudioResource]
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case totalMinutesOfAudio = "total_minutes_of_audio"
case audio = "audio"
}
}
| apache-2.0 |
mshhmzh/firefox-ios | Client/Frontend/Intro/IntroViewController.swift | 2 | 20752 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
struct IntroViewControllerUX {
static let Width = 375
static let Height = 667
static let CardSlides = ["organize", "customize", "share", "choose", "sync"]
static let NumberOfCards = CardSlides.count
static let PagerCenterOffsetFromScrollViewBottom = 30
static let StartBrowsingButtonTitle = NSLocalizedString("Start Browsing", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo")
static let StartBrowsingButtonColor = UIColor(rgb: 0x363B40)
static let StartBrowsingButtonHeight = 56
static let SignInButtonTitle = NSLocalizedString("Sign in to Firefox", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo")
static let SignInButtonColor = UIColor(red: 0.259, green: 0.49, blue: 0.831, alpha: 1.0)
static let SignInButtonHeight = 46
static let SignInButtonCornerRadius = CGFloat(4)
static let CardTextLineHeight = CGFloat(6)
static let CardTitleOrganize = NSLocalizedString("Organize", tableName: "Intro", comment: "Title for one of the panels in the First Run tour.")
static let CardTitleCustomize = NSLocalizedString("Customize", tableName: "Intro", comment: "Title for one of the panels in the First Run tour.")
static let CardTitleShare = NSLocalizedString("Share", tableName: "Intro", comment: "Title for one of the panels in the First Run tour.")
static let CardTitleChoose = NSLocalizedString("Choose", tableName: "Intro", comment: "Title for one of the panels in the First Run tour.")
static let CardTitleSync = NSLocalizedString("Sync your Devices.", tableName: "Intro", comment: "Title for one of the panels in the First Run tour.")
static let CardTextOrganize = NSLocalizedString("Easily switch between open pages with tabs.", tableName: "Intro", comment: "Description for the 'Organize' panel in the First Run tour.")
static let CardTextCustomize = NSLocalizedString("Personalize your default search engine and more in Settings.", tableName: "Intro", comment: "Description for the 'Customize' panel in the First Run tour.")
static let CardTextShare = NSLocalizedString("Use the share sheet to send links from other apps to Firefox.", tableName: "Intro", comment: "Description for the 'Share' panel in the First Run tour.")
static let CardTextChoose = NSLocalizedString("Tap, hold and move the Firefox icon into your dock for easy access.", tableName: "Intro", comment: "Description for the 'Choose' panel in the First Run tour.")
static let Card1ImageLabel = NSLocalizedString("The Show Tabs button is next to the Address and Search text field and displays the current number of open tabs.", tableName: "Intro", comment: "Accessibility label for the UI element used to display the number of open tabs, and open the tab tray.")
static let Card2ImageLabel = NSLocalizedString("The Settings button is at the beginning of the Tabs Tray.", tableName: "Intro", comment: "Accessibility label for the Settings button in the tab tray.")
static let Card3ImageLabel = NSLocalizedString("Firefox and the cloud", tableName: "Intro", comment: "Accessibility label for the image displayed in the 'Sync' panel of the First Run tour.")
static let CardTextSyncOffsetFromCenter = 25
static let Card3ButtonOffsetFromCenter = -10
static let FadeDuration = 0.25
static let BackForwardButtonEdgeInset = 20
static let Card1Color = UIColor(rgb: 0xFFC81E)
static let Card2Color = UIColor(rgb: 0x41B450)
static let Card3Color = UIColor(rgb: 0x0096DD)
}
let IntroViewControllerSeenProfileKey = "IntroViewControllerSeen"
protocol IntroViewControllerDelegate: class {
func introViewControllerDidFinish(introViewController: IntroViewController)
func introViewControllerDidRequestToLogin(introViewController: IntroViewController)
}
class IntroViewController: UIViewController, UIScrollViewDelegate {
weak var delegate: IntroViewControllerDelegate?
var slides = [UIImage]()
var cards = [UIImageView]()
var introViews = [UIView]()
var titleLabels = [UILabel]()
var textLabels = [UILabel]()
var startBrowsingButton: UIButton!
var introView: UIView?
var slideContainer: UIView!
var pageControl: UIPageControl!
var backButton: UIButton!
var forwardButton: UIButton!
var signInButton: UIButton!
private var scrollView: IntroOverlayScrollView!
var slideVerticalScaleFactor: CGFloat = 1.0
override func viewDidLoad() {
view.backgroundColor = UIColor.whiteColor()
// scale the slides down for iPhone 4S
if view.frame.height <= 480 {
slideVerticalScaleFactor = 1.33
}
for slideName in IntroViewControllerUX.CardSlides {
slides.append(UIImage(named: slideName)!)
}
startBrowsingButton = UIButton()
startBrowsingButton.backgroundColor = IntroViewControllerUX.StartBrowsingButtonColor
startBrowsingButton.setTitle(IntroViewControllerUX.StartBrowsingButtonTitle, forState: UIControlState.Normal)
startBrowsingButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
startBrowsingButton.addTarget(self, action: #selector(IntroViewController.SELstartBrowsing), forControlEvents: UIControlEvents.TouchUpInside)
startBrowsingButton.accessibilityIdentifier = "IntroViewController.startBrowsingButton"
view.addSubview(startBrowsingButton)
startBrowsingButton.snp_makeConstraints { (make) -> Void in
make.left.right.bottom.equalTo(self.view)
make.height.equalTo(IntroViewControllerUX.StartBrowsingButtonHeight)
}
scrollView = IntroOverlayScrollView()
scrollView.backgroundColor = UIColor.clearColor()
scrollView.accessibilityLabel = NSLocalizedString("Intro Tour Carousel", comment: "Accessibility label for the introduction tour carousel")
scrollView.delegate = self
scrollView.bounces = false
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.contentSize = CGSize(width: scaledWidthOfSlide * CGFloat(IntroViewControllerUX.NumberOfCards), height: scaledHeightOfSlide)
view.addSubview(scrollView)
slideContainer = UIView()
slideContainer.backgroundColor = IntroViewControllerUX.Card1Color
for i in 0..<IntroViewControllerUX.NumberOfCards {
let imageView = UIImageView(frame: CGRect(x: CGFloat(i)*scaledWidthOfSlide, y: 0, width: scaledWidthOfSlide, height: scaledHeightOfSlide))
imageView.image = slides[i]
slideContainer.addSubview(imageView)
}
scrollView.addSubview(slideContainer)
scrollView.snp_makeConstraints { (make) -> Void in
make.left.right.top.equalTo(self.view)
make.bottom.equalTo(startBrowsingButton.snp_top)
}
pageControl = UIPageControl()
pageControl.pageIndicatorTintColor = UIColor.blackColor().colorWithAlphaComponent(0.3)
pageControl.currentPageIndicatorTintColor = UIColor.blackColor()
pageControl.numberOfPages = IntroViewControllerUX.NumberOfCards
pageControl.accessibilityIdentifier = "pageControl"
pageControl.addTarget(self, action: #selector(IntroViewController.changePage), forControlEvents: UIControlEvents.ValueChanged)
view.addSubview(pageControl)
pageControl.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(self.scrollView)
make.centerY.equalTo(self.startBrowsingButton.snp_top).offset(-IntroViewControllerUX.PagerCenterOffsetFromScrollViewBottom)
}
func addCard(text: String, title: String) {
let introView = UIView()
self.introViews.append(introView)
self.addLabelsToIntroView(introView, text: text, title: title)
}
addCard(IntroViewControllerUX.CardTextOrganize, title: IntroViewControllerUX.CardTitleOrganize)
addCard(IntroViewControllerUX.CardTextCustomize, title: IntroViewControllerUX.CardTitleCustomize)
addCard(IntroViewControllerUX.CardTextShare, title: IntroViewControllerUX.CardTitleShare)
addCard(IntroViewControllerUX.CardTextChoose, title: IntroViewControllerUX.CardTitleChoose)
// Sync card, with sign in to sync button.
signInButton = UIButton()
signInButton.backgroundColor = IntroViewControllerUX.SignInButtonColor
signInButton.setTitle(IntroViewControllerUX.SignInButtonTitle, forState: .Normal)
signInButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
signInButton.layer.cornerRadius = IntroViewControllerUX.SignInButtonCornerRadius
signInButton.clipsToBounds = true
signInButton.addTarget(self, action: #selector(IntroViewController.SELlogin), forControlEvents: UIControlEvents.TouchUpInside)
signInButton.snp_makeConstraints { (make) -> Void in
make.height.equalTo(IntroViewControllerUX.SignInButtonHeight)
}
let syncCardView = UIView()
addViewsToIntroView(syncCardView, view: signInButton, title: IntroViewControllerUX.CardTitleSync)
introViews.append(syncCardView)
// Add all the cards to the view, make them invisible with zero alpha
for introView in introViews {
introView.alpha = 0
self.view.addSubview(introView)
introView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(self.slideContainer.snp_bottom)
make.bottom.equalTo(self.startBrowsingButton.snp_top)
make.left.right.equalTo(self.view)
}
}
// Make whole screen scrollable by bringing the scrollview to the top
view.bringSubviewToFront(scrollView)
view.bringSubviewToFront(pageControl)
// Activate the first card
setActiveIntroView(introViews[0], forPage: 0)
setupDynamicFonts()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(IntroViewController.SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
}
func SELDynamicFontChanged(notification: NSNotification) {
guard notification.name == NotificationDynamicFontChanged else { return }
setupDynamicFonts()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.snp_remakeConstraints { (make) -> Void in
make.left.right.top.equalTo(self.view)
make.bottom.equalTo(self.startBrowsingButton.snp_top)
}
for i in 0..<IntroViewControllerUX.NumberOfCards {
if let imageView = slideContainer.subviews[i] as? UIImageView {
imageView.frame = CGRect(x: CGFloat(i)*scaledWidthOfSlide, y: 0, width: scaledWidthOfSlide, height: scaledHeightOfSlide)
imageView.contentMode = UIViewContentMode.ScaleAspectFit
}
}
slideContainer.frame = CGRect(x: 0, y: 0, width: scaledWidthOfSlide * CGFloat(IntroViewControllerUX.NumberOfCards), height: scaledHeightOfSlide)
scrollView.contentSize = CGSize(width: slideContainer.frame.width, height: slideContainer.frame.height)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
// This actually does the right thing on iPad where the modally
// presented version happily rotates with the iPad orientation.
return UIInterfaceOrientationMask.Portrait
}
func SELstartBrowsing() {
delegate?.introViewControllerDidFinish(self)
}
func SELback() {
if introView == introViews[1] {
setActiveIntroView(introViews[0], forPage: 0)
scrollView.scrollRectToVisible(scrollView.subviews[0].frame, animated: true)
pageControl.currentPage = 0
} else if introView == introViews[2] {
setActiveIntroView(introViews[1], forPage: 1)
scrollView.scrollRectToVisible(scrollView.subviews[1].frame, animated: true)
pageControl.currentPage = 1
}
}
func SELforward() {
if introView == introViews[0] {
setActiveIntroView(introViews[1], forPage: 1)
scrollView.scrollRectToVisible(scrollView.subviews[1].frame, animated: true)
pageControl.currentPage = 1
} else if introView == introViews[1] {
setActiveIntroView(introViews[2], forPage: 2)
scrollView.scrollRectToVisible(scrollView.subviews[2].frame, animated: true)
pageControl.currentPage = 2
}
}
func SELlogin() {
delegate?.introViewControllerDidRequestToLogin(self)
}
private var accessibilityScrollStatus: String {
return String(format: NSLocalizedString("Introductory slide %@ of %@", tableName: "Intro", comment: "String spoken by assistive technology (like VoiceOver) stating on which page of the intro wizard we currently are. E.g. Introductory slide 1 of 3"), NSNumberFormatter.localizedStringFromNumber(pageControl.currentPage+1, numberStyle: .DecimalStyle), NSNumberFormatter.localizedStringFromNumber(IntroViewControllerUX.NumberOfCards, numberStyle: .DecimalStyle))
}
func changePage() {
let swipeCoordinate = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPointMake(swipeCoordinate, 0), animated: true)
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// Need to add this method so that when forcibly dragging, instead of letting deceleration happen, should also calculate what card it's on.
// This especially affects sliding to the last or first slides.
if !decelerate {
scrollViewDidEndDecelerating(scrollView)
}
}
func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
// Need to add this method so that tapping the pageControl will also change the card texts.
// scrollViewDidEndDecelerating waits until the end of the animation to calculate what card it's on.
scrollViewDidEndDecelerating(scrollView)
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
setActiveIntroView(introViews[page], forPage: page)
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let maximumHorizontalOffset = scrollView.contentSize.width - CGRectGetWidth(scrollView.frame)
let currentHorizontalOffset = scrollView.contentOffset.x
var percentage = currentHorizontalOffset / maximumHorizontalOffset
var startColor: UIColor, endColor: UIColor
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = page
if(percentage < 0.5) {
startColor = IntroViewControllerUX.Card1Color
endColor = IntroViewControllerUX.Card2Color
percentage = percentage * 2
} else {
startColor = IntroViewControllerUX.Card2Color
endColor = IntroViewControllerUX.Card3Color
percentage = (percentage - 0.5) * 2
}
slideContainer.backgroundColor = colorForPercentage(percentage, start: startColor, end: endColor)
}
private func colorForPercentage(percentage: CGFloat, start: UIColor, end: UIColor) -> UIColor {
let s = start.components
let e = end.components
let newRed = (1.0 - percentage) * s.red + percentage * e.red
let newGreen = (1.0 - percentage) * s.green + percentage * e.green
let newBlue = (1.0 - percentage) * s.blue + percentage * e.blue
return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
}
private func setActiveIntroView(newIntroView: UIView, forPage page: Int) {
if introView != newIntroView {
UIView.animateWithDuration(IntroViewControllerUX.FadeDuration, animations: { () -> Void in
self.introView?.alpha = 0
self.introView = newIntroView
newIntroView.alpha = 1.0
}, completion: { _ in
if page == (IntroViewControllerUX.NumberOfCards - 1) {
self.scrollView.signinButton = self.signInButton
} else {
self.scrollView.signinButton = nil
}
})
}
}
private var scaledWidthOfSlide: CGFloat {
return view.frame.width
}
private var scaledHeightOfSlide: CGFloat {
return (view.frame.width / slides[0].size.width) * slides[0].size.height / slideVerticalScaleFactor
}
private func attributedStringForLabel(text: String) -> NSMutableAttributedString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = IntroViewControllerUX.CardTextLineHeight
paragraphStyle.alignment = .Center
let string = NSMutableAttributedString(string: text)
string.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, string.length))
return string
}
private func addLabelsToIntroView(introView: UIView, text: String, title: String = "") {
let label = UILabel()
label.numberOfLines = 0
label.attributedText = attributedStringForLabel(text)
textLabels.append(label)
addViewsToIntroView(introView, view: label, title: title)
}
private func addViewsToIntroView(introView: UIView, view: UIView, title: String = "") {
introView.addSubview(view)
view.snp_makeConstraints { (make) -> Void in
make.center.equalTo(introView)
make.width.equalTo(self.view.frame.width <= 320 ? 240 : 280) // TODO Talk to UX about small screen sizes
}
if !title.isEmpty {
let titleLabel = UILabel()
titleLabel.numberOfLines = 0
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.text = title
titleLabels.append(titleLabel)
introView.addSubview(titleLabel)
titleLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(introView)
make.bottom.equalTo(view.snp_top)
make.centerX.equalTo(introView)
make.width.equalTo(self.view.frame.width <= 320 ? 240 : 280) // TODO Talk to UX about small screen sizes
}
}
}
private func setupDynamicFonts() {
startBrowsingButton.titleLabel?.font = UIFont.systemFontOfSize(DynamicFontHelper.defaultHelper.IntroBigFontSize)
signInButton.titleLabel?.font = UIFont.systemFontOfSize(DynamicFontHelper.defaultHelper.IntroStandardFontSize, weight: UIFontWeightMedium)
for titleLabel in titleLabels {
titleLabel.font = UIFont.systemFontOfSize(DynamicFontHelper.defaultHelper.IntroBigFontSize, weight: UIFontWeightBold)
}
for label in textLabels {
label.font = UIFont.systemFontOfSize(DynamicFontHelper.defaultHelper.IntroStandardFontSize)
}
}
}
private class IntroOverlayScrollView: UIScrollView {
weak var signinButton: UIButton?
private override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
if let signinFrame = signinButton?.frame {
let convertedFrame = convertRect(signinFrame, fromView: signinButton?.superview)
if CGRectContainsPoint(convertedFrame, point) {
return false
}
}
return CGRectContainsPoint(CGRect(origin: self.frame.origin, size: CGSize(width: self.contentSize.width, height: self.frame.size.height)), point)
}
}
extension UIColor {
var components:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return (r,g,b,a)
}
}
| mpl-2.0 |
sami4064/UpdatedIOSRTCPlugin | src/PluginRTCPeerConnection.swift | 2 | 16163 | import Foundation
class PluginRTCPeerConnection : NSObject, RTCPeerConnectionDelegate, RTCSessionDescriptionDelegate {
var rtcPeerConnectionFactory: RTCPeerConnectionFactory
var rtcPeerConnection: RTCPeerConnection!
var pluginRTCPeerConnectionConfig: PluginRTCPeerConnectionConfig
var pluginRTCPeerConnectionConstraints: PluginRTCPeerConnectionConstraints
// PluginRTCDataChannel dictionary.
var pluginRTCDataChannels: [Int : PluginRTCDataChannel] = [:]
var eventListener: (data: NSDictionary) -> Void
var eventListenerForAddStream: (pluginMediaStream: PluginMediaStream) -> Void
var eventListenerForRemoveStream: (id: String) -> Void
var onCreateDescriptionSuccessCallback: ((rtcSessionDescription: RTCSessionDescription) -> Void)!
var onCreateDescriptionFailureCallback: ((error: NSError) -> Void)!
var onSetDescriptionSuccessCallback: (() -> Void)!
var onSetDescriptionFailureCallback: ((error: NSError) -> Void)!
init(
rtcPeerConnectionFactory: RTCPeerConnectionFactory,
pcConfig: NSDictionary?,
pcConstraints: NSDictionary?,
eventListener: (data: NSDictionary) -> Void,
eventListenerForAddStream: (pluginMediaStream: PluginMediaStream) -> Void,
eventListenerForRemoveStream: (id: String) -> Void
) {
NSLog("PluginRTCPeerConnection#init()")
self.rtcPeerConnectionFactory = rtcPeerConnectionFactory
self.pluginRTCPeerConnectionConfig = PluginRTCPeerConnectionConfig(pcConfig: pcConfig)
self.pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: pcConstraints)
self.eventListener = eventListener
self.eventListenerForAddStream = eventListenerForAddStream
self.eventListenerForRemoveStream = eventListenerForRemoveStream
}
func run() {
NSLog("PluginRTCPeerConnection#run()")
self.rtcPeerConnection = self.rtcPeerConnectionFactory.peerConnectionWithICEServers(
self.pluginRTCPeerConnectionConfig.getIceServers(),
constraints: self.pluginRTCPeerConnectionConstraints.getConstraints(),
delegate: self
)
}
func createOffer(
options: NSDictionary?,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#createOffer()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: options)
self.onCreateDescriptionSuccessCallback = { (rtcSessionDescription: RTCSessionDescription) -> Void in
NSLog("PluginRTCPeerConnection#createOffer() | success callback [type:\(rtcSessionDescription.type)]")
let data = [
"type": rtcSessionDescription.type,
"sdp": rtcSessionDescription.description
]
callback(data: data)
}
self.onCreateDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#createOffer() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.createOfferWithDelegate(self,
constraints: pluginRTCPeerConnectionConstraints.getConstraints())
}
func createAnswer(
options: NSDictionary?,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#createAnswer()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: options)
self.onCreateDescriptionSuccessCallback = { (rtcSessionDescription: RTCSessionDescription) -> Void in
NSLog("PluginRTCPeerConnection#createAnswer() | success callback [type:\(rtcSessionDescription.type)]")
let data = [
"type": rtcSessionDescription.type,
"sdp": rtcSessionDescription.description
]
callback(data: data)
}
self.onCreateDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#createAnswer() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.createAnswerWithDelegate(self,
constraints: pluginRTCPeerConnectionConstraints.getConstraints())
}
func setLocalDescription(
desc: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#setLocalDescription()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let type = desc.objectForKey("type") as? String ?? ""
let sdp = desc.objectForKey("sdp") as? String ?? ""
let rtcSessionDescription = RTCSessionDescription(type: type, sdp: sdp)
self.onSetDescriptionSuccessCallback = { () -> Void in
NSLog("PluginRTCPeerConnection#setLocalDescription() | success callback")
let data = [
"type": self.rtcPeerConnection.localDescription.type,
"sdp": self.rtcPeerConnection.localDescription.description
]
callback(data: data)
}
self.onSetDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#setLocalDescription() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.setLocalDescriptionWithDelegate(self,
sessionDescription: rtcSessionDescription
)
}
func setRemoteDescription(
desc: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#setRemoteDescription()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let type = desc.objectForKey("type") as? String ?? ""
let sdp = desc.objectForKey("sdp") as? String ?? ""
let rtcSessionDescription = RTCSessionDescription(type: type, sdp: sdp)
self.onSetDescriptionSuccessCallback = { () -> Void in
NSLog("PluginRTCPeerConnection#setRemoteDescription() | success callback")
let data = [
"type": self.rtcPeerConnection.remoteDescription.type,
"sdp": self.rtcPeerConnection.remoteDescription.description
]
callback(data: data)
}
self.onSetDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#setRemoteDescription() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.setRemoteDescriptionWithDelegate(self,
sessionDescription: rtcSessionDescription
)
}
func addIceCandidate(
candidate: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: () -> Void
) {
NSLog("PluginRTCPeerConnection#addIceCandidate()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let sdpMid = candidate.objectForKey("sdpMid") as? String ?? ""
let sdpMLineIndex = candidate.objectForKey("sdpMLineIndex") as? Int ?? 0
let candidate = candidate.objectForKey("candidate") as? String ?? ""
let result: Bool = self.rtcPeerConnection.addICECandidate(RTCICECandidate(
mid: sdpMid,
index: sdpMLineIndex,
sdp: candidate
))
var data: NSDictionary
if result == true {
if self.rtcPeerConnection.remoteDescription != nil {
data = [
"remoteDescription": [
"type": self.rtcPeerConnection.remoteDescription.type,
"sdp": self.rtcPeerConnection.remoteDescription.description
]
]
} else {
data = [
"remoteDescription": false
]
}
callback(data: data)
} else {
errback()
}
}
func addStream(pluginMediaStream: PluginMediaStream) -> Bool {
NSLog("PluginRTCPeerConnection#addStream()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return false
}
return self.rtcPeerConnection.addStream(pluginMediaStream.rtcMediaStream)
}
func removeStream(pluginMediaStream: PluginMediaStream) {
NSLog("PluginRTCPeerConnection#removeStream()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
self.rtcPeerConnection.removeStream(pluginMediaStream.rtcMediaStream)
}
func createDataChannel(
dcId: Int,
label: String,
options: NSDictionary?,
eventListener: (data: NSDictionary) -> Void,
eventListenerForBinaryMessage: (data: NSData) -> Void
) {
NSLog("PluginRTCPeerConnection#createDataChannel()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = PluginRTCDataChannel(
rtcPeerConnection: rtcPeerConnection,
label: label,
options: options,
eventListener: eventListener,
eventListenerForBinaryMessage: eventListenerForBinaryMessage
)
// Store the pluginRTCDataChannel into the dictionary.
self.pluginRTCDataChannels[dcId] = pluginRTCDataChannel
// Run it.
pluginRTCDataChannel.run()
}
func RTCDataChannel_setListener(
dcId: Int,
eventListener: (data: NSDictionary) -> Void,
eventListenerForBinaryMessage: (data: NSData) -> Void
) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_setListener()")
let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
// Set the eventListener.
pluginRTCDataChannel!.setListener(eventListener,
eventListenerForBinaryMessage: eventListenerForBinaryMessage
)
}
func close() {
NSLog("PluginRTCPeerConnection#close()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
self.rtcPeerConnection.close()
}
func RTCDataChannel_sendString(
dcId: Int,
data: String,
callback: (data: NSDictionary) -> Void
) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_sendString()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
pluginRTCDataChannel!.sendString(data, callback: callback)
}
func RTCDataChannel_sendBinary(
dcId: Int,
data: NSData,
callback: (data: NSDictionary) -> Void
) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_sendBinary()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
pluginRTCDataChannel!.sendBinary(data, callback: callback)
}
func RTCDataChannel_close(dcId: Int) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_close()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
pluginRTCDataChannel!.close()
// Remove the pluginRTCDataChannel from the dictionary.
self.pluginRTCDataChannels[dcId] = nil
}
/**
* Methods inherited from RTCPeerConnectionDelegate.
*/
func peerConnection(peerConnection: RTCPeerConnection!,
signalingStateChanged newState: RTCSignalingState) {
let state_str = PluginRTCTypes.signalingStates[newState.rawValue] as String!
NSLog("PluginRTCPeerConnection | onsignalingstatechange [signalingState:\(state_str)]")
self.eventListener(data: [
"type": "signalingstatechange",
"signalingState": state_str
])
}
func peerConnection(peerConnection: RTCPeerConnection!,
iceGatheringChanged newState: RTCICEGatheringState) {
let state_str = PluginRTCTypes.iceGatheringStates[newState.rawValue] as String!
NSLog("PluginRTCPeerConnection | onicegatheringstatechange [iceGatheringState:\(state_str)]")
self.eventListener(data: [
"type": "icegatheringstatechange",
"iceGatheringState": state_str
])
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
// Emit an empty candidate if iceGatheringState is "complete".
if newState.rawValue == RTCICEGatheringComplete.rawValue && self.rtcPeerConnection.localDescription != nil {
self.eventListener(data: [
"type": "icecandidate",
// NOTE: Cannot set null as value.
"candidate": false,
"localDescription": [
"type": self.rtcPeerConnection.localDescription.type,
"sdp": self.rtcPeerConnection.localDescription.description
]
])
}
}
func peerConnection(peerConnection: RTCPeerConnection!,
gotICECandidate candidate: RTCICECandidate!) {
NSLog("PluginRTCPeerConnection | onicecandidate [sdpMid:\(candidate.sdpMid), sdpMLineIndex:\(candidate.sdpMLineIndex), candidate:\(candidate.sdp)]")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
self.eventListener(data: [
"type": "icecandidate",
"candidate": [
"sdpMid": candidate.sdpMid,
"sdpMLineIndex": candidate.sdpMLineIndex,
"candidate": candidate.sdp
],
"localDescription": [
"type": self.rtcPeerConnection.localDescription.type,
"sdp": self.rtcPeerConnection.localDescription.description
]
])
}
func peerConnection(peerConnection: RTCPeerConnection!,
iceConnectionChanged newState: RTCICEConnectionState) {
let state_str = PluginRTCTypes.iceConnectionStates[newState.rawValue] as String!
NSLog("PluginRTCPeerConnection | oniceconnectionstatechange [iceConnectionState:\(state_str)]")
self.eventListener(data: [
"type": "iceconnectionstatechange",
"iceConnectionState": state_str
])
}
func peerConnection(rtcPeerConnection: RTCPeerConnection!,
addedStream rtcMediaStream: RTCMediaStream!) {
NSLog("PluginRTCPeerConnection | onaddstream")
let pluginMediaStream = PluginMediaStream(rtcMediaStream: rtcMediaStream)
pluginMediaStream.run()
// Let the plugin store it in its dictionary.
self.eventListenerForAddStream(pluginMediaStream: pluginMediaStream)
// Fire the 'addstream' event so the JS will create a new MediaStream.
self.eventListener(data: [
"type": "addstream",
"stream": pluginMediaStream.getJSON()
])
}
func peerConnection(rtcPeerConnection: RTCPeerConnection!,
removedStream rtcMediaStream: RTCMediaStream!) {
NSLog("PluginRTCPeerConnection | onremovestream")
// Let the plugin remove it from its dictionary.
self.eventListenerForRemoveStream(id: rtcMediaStream.label)
self.eventListener(data: [
"type": "removestream",
"streamId": rtcMediaStream.label // NOTE: No "id" property yet.
])
}
func peerConnectionOnRenegotiationNeeded(peerConnection: RTCPeerConnection!) {
NSLog("PluginRTCPeerConnection | onnegotiationeeded")
self.eventListener(data: [
"type": "negotiationneeded"
])
}
func peerConnection(peerConnection: RTCPeerConnection!,
didOpenDataChannel rtcDataChannel: RTCDataChannel!) {
NSLog("PluginRTCPeerConnection | ondatachannel")
let dcId = PluginUtils.randomInt(10000, max:99999)
let pluginRTCDataChannel = PluginRTCDataChannel(
rtcDataChannel: rtcDataChannel
)
// Store the pluginRTCDataChannel into the dictionary.
self.pluginRTCDataChannels[dcId] = pluginRTCDataChannel
// Run it.
pluginRTCDataChannel.run()
// Fire the 'datachannel' event so the JS will create a new RTCDataChannel.
self.eventListener(data: [
"type": "datachannel",
"channel": [
"dcId": dcId,
"label": rtcDataChannel.label,
"ordered": rtcDataChannel.isOrdered,
"maxPacketLifeTime": rtcDataChannel.maxRetransmitTime,
"maxRetransmits": rtcDataChannel.maxRetransmits,
"protocol": rtcDataChannel.`protocol`,
"negotiated": rtcDataChannel.isNegotiated,
"id": rtcDataChannel.streamId,
"readyState": PluginRTCTypes.dataChannelStates[rtcDataChannel.state.rawValue] as String!,
"bufferedAmount": rtcDataChannel.bufferedAmount
]
])
}
/**
* Methods inherited from RTCSessionDescriptionDelegate.
*/
func peerConnection(rtcPeerConnection: RTCPeerConnection!,
didCreateSessionDescription rtcSessionDescription: RTCSessionDescription!, error: NSError!) {
if error == nil {
self.onCreateDescriptionSuccessCallback(rtcSessionDescription: rtcSessionDescription)
} else {
self.onCreateDescriptionFailureCallback(error: error)
}
}
func peerConnection(peerConnection: RTCPeerConnection!,
didSetSessionDescriptionWithError error: NSError!) {
if error == nil {
self.onSetDescriptionSuccessCallback()
} else {
self.onSetDescriptionFailureCallback(error: error)
}
}
}
| mit |
TableBooking/ios-client | TableBooking/StartTabBarViewController.swift | 1 | 902 | //
// StartTabBarViewController.swift
// TableBooking
//
// Created by Nikita Kirichek on 11/19/16.
// Copyright © 2016 Nikita Kirichek. All rights reserved.
//
import UIKit
class StartTabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
UITabBar.appearance().tintColor = Color.TBGreen
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
woxtu/NSString-RemoveEmoji | Package.swift | 1 | 471 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "NSString_RemoveEmoji",
platforms: [
.macOS(.v10_10), .iOS(.v8), .tvOS(.v9), .watchOS(.v2),
],
products: [
.library(name: "NSString_RemoveEmoji", targets: ["NSString_RemoveEmoji"]),
],
targets: [
.target(name: "NSString_RemoveEmoji"),
.testTarget(name: "NSString_RemoveEmojiTests", dependencies: ["NSString_RemoveEmoji"]),
]
)
| mit |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Extensions/Colors and Styles/WPStyleGuide+Search.swift | 1 | 3473 | import Foundation
import WordPressShared
import UIKit
extension WPStyleGuide {
fileprivate static let barTintColor: UIColor = .neutral(.shade10)
public class func configureSearchBar(_ searchBar: UISearchBar, backgroundColor: UIColor, returnKeyType: UIReturnKeyType) {
searchBar.accessibilityIdentifier = "Search"
searchBar.autocapitalizationType = .none
searchBar.autocorrectionType = .no
searchBar.isTranslucent = true
searchBar.backgroundImage = UIImage()
searchBar.backgroundColor = backgroundColor
searchBar.layer.borderWidth = 1.0
searchBar.returnKeyType = returnKeyType
}
/// configures a search bar with a default `.appBackground` color and a `.done` return key
@objc public class func configureSearchBar(_ searchBar: UISearchBar) {
configureSearchBar(searchBar, backgroundColor: .appBarBackground, returnKeyType: .done)
}
@objc public class func configureSearchBarAppearance() {
configureSearchBarTextAppearance()
// Cancel button
let barButtonItemAppearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])
barButtonItemAppearance.tintColor = .neutral(.shade70)
let iconSizes = CGSize(width: 20, height: 20)
// We have to manually tint these images, as we want them
// a different color from the search bar's cursor (which uses `tintColor`)
let clearImage = UIImage.gridicon(.crossCircle, size: iconSizes).withTintColor(.searchFieldIcons).withRenderingMode(.alwaysOriginal)
let searchImage = UIImage.gridicon(.search, size: iconSizes).withTintColor(.searchFieldIcons).withRenderingMode(.alwaysOriginal)
UISearchBar.appearance().setImage(clearImage, for: .clear, state: UIControl.State())
UISearchBar.appearance().setImage(searchImage, for: .search, state: UIControl.State())
}
@objc public class func configureSearchBarTextAppearance() {
// Cancel button
let barButtonTitleAttributes: [NSAttributedString.Key: Any] = [.font: WPStyleGuide.fixedFont(for: .headline),
.foregroundColor: UIColor.neutral(.shade70)]
let barButtonItemAppearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])
barButtonItemAppearance.setTitleTextAttributes(barButtonTitleAttributes, for: UIControl.State())
// Text field
let placeholderText = NSLocalizedString("Search", comment: "Placeholder text for the search bar")
let attributedPlaceholderText = NSAttributedString(string: placeholderText,
attributes: WPStyleGuide.defaultSearchBarTextAttributesSwifted(.searchFieldPlaceholderText))
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder =
attributedPlaceholderText
}
}
extension UISearchBar {
// Per Apple's documentation (https://developer.apple.com/documentation/xcode/supporting_dark_mode_in_your_interface),
// `cgColor` objects do not adapt to appearance changes (i.e. toggling light/dark mode).
// `tintColorDidChange` is called when the appearance changes, so re-set the border color when this occurs.
open override func tintColorDidChange() {
super.tintColorDidChange()
layer.borderColor = UIColor.appBarBackground.cgColor
}
}
| gpl-2.0 |
felipebv/AssetsAnalyser | Project/AssetsAnalyser/FileHelper.swift | 1 | 1373 | //
// FileHelper.swift
// AssetsAnalyser
//
// Created by Felipe Braunger Valio on 16/05/17.
// Copyright © 2017 Movile. All rights reserved.
//
import Cocoa
class FileHelper: NSObject {
func exclude(paths: [String], fromPaths: [String]) -> [String] {
return fromPaths.filter {
return !paths.contains($0)
}
}
func sourceCodesAt(projectPath: String) -> [String] {
return filepathsEndingWith(".swift", inPath: projectPath)
}
func interfaceFilesAt(projectPath: String) -> [String] {
return filepathsEndingWith(".swift", inPath: projectPath)
}
func filepathsEndingWith(_ suffix: String, inPath path: String) -> [String] {
guard let enumerator = FileManager().enumerator(atPath: path) else {
return []
}
var filepaths: [String] = []
for item in enumerator {
if let item = item as? String, item.hasSuffix(suffix) {
filepaths.append("\(path)/\(item)")
}
}
return filepaths
}
func openFileAt(_ path: String) -> String? {
let url = URL(fileURLWithPath: path)
guard let data = try? Data(contentsOf: url), let str = String(data: data, encoding: .utf8) else {
return nil
}
return str
}
}
| mit |
slavapestov/swift | validation-test/compiler_crashers_fixed/26927-swift-modulefile-maybereadgenericparams.swift | 4 | 304 | // 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
class d<T where c:e{
var _=f=(h<T func c
class n{
enum b{
struct d
func f:e
var _=f=c<d{
| apache-2.0 |
aschwaighofer/swift | test/IDE/complete_stmt_controlling_expr.swift | 2 | 27603 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_GUARD_1 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_1 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_2 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_2B | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_3 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_4 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_ELSE_IF_1 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_ELSE_IF_2 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_ELSE_IF_3 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_ELSE_IF_4 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_ELSE_IF_5 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_ELSE_IF_6 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_WHILE_1 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_WHILE_2 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_WHILE_2B | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_WHILE_3 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_WHILE_4 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_DO_WHILE_1 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_DO_WHILE_2 | %FileCheck %s -check-prefix=COND-WITH-RELATION1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INIT_1 | %FileCheck %s -check-prefix=COND_NONE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INIT_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INIT_3 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_COND_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_COND_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_COND_3 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_COND_I_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_COND_I_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_COND_I_E_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_I_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_I_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_I_3 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_I_4 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_I_E_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_BODY_I_1 > %t.body.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.body.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_ERROR_LOCAL < %t.body.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_BODY_I_2 > %t.body.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.body.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_ERROR_LOCAL < %t.body.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_BODY_I_3 > %t.body.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.body.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_ERROR_LOCAL < %t.body.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_BODY_I_4 > %t.body.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.body.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_ERROR_LOCAL < %t.body.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_BODY_I_5 > %t.body.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.body.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_ERROR_LOCAL < %t.body.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_BODY_I_6 > %t.body.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.body.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_ERROR_LOCAL < %t.body.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOR_EACH_EXPR_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOR_EACH_EXPR_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_EXPR_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_EXPR_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_CASE_WHERE_EXPR_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_CASE_WHERE_EXPR_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_CASE_WHERE_EXPR_3 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_CASE_WHERE_EXPR_I_1 > %t.where.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.where.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_INT_LOCAL < %t.where.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_CASE_WHERE_EXPR_I_2 > %t.where.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.where.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_INT_LOCAL < %t.where.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_CASE_WHERE_EXPR_I_J_1 > %t.where.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.where.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_INT_LOCAL < %t.where.txt
// RUN: %FileCheck %s -check-prefix=WITH_J_INT < %t.where.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_IF_1 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_IF_2 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_IF_3 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_IF_4 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_WHILE_1 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_WHILE_2 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_WHILE_3 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_WHILE_4 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_1 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_2 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_3 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_4 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_5 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_6 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_7 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IF_LET_BIND_1 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT_BOOL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IF_LET_BIND_2 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT_BOOL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IF_LET_BIND_3 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IF_LET_BIND_4 | %FileCheck %s -check-prefix=FOOSTRUCT_NODOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_1 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT_BOOL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_2 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT_BOOL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_3 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT_BOOL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_4 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT_BOOL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_5 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_6 | %FileCheck %s -check-prefix=FOOSTRUCT_NODOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_7 | %FileCheck %s -check-prefix=FOOSTRUCT_LOCALVAL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_8 | %FileCheck %s -check-prefix=FOOSTRUCT_LOCALVAL
struct FooStruct {
var instanceVar : Int
init(_: Int = 0) { }
func boolGen() -> Bool { return false }
func intGen() -> Int { return 1 }
}
func testGuard1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
guard #^COND_GUARD_1^#
}
func testIf1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if #^COND_IF_1^#
}
func testIf2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if #^COND_IF_2^# {
}
}
func testIf2b(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true, #^COND_IF_2B^# {
}
}
func testIf3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if var z = #^COND_IF_3^# {
}
}
func testIf4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if var z = #^COND_IF_4^# {
}
}
func testIfElseIf1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if #^COND_IF_ELSE_IF_1^#
}
func testIfElseIf2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if #^COND_IF_ELSE_IF_2^# {
}
}
func testIfElseIf3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if true {
} else if #^COND_IF_ELSE_IF_3^#
}
func testIfElseIf4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if true {
} else if #^COND_IF_ELSE_IF_4^# {
}
}
func testIfElseIf5(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if var z = #^COND_IF_ELSE_IF_5^#
}
func testIfElseIf6(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if let z = #^COND_IF_ELSE_IF_6^# {
}
}
func testWhile1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while #^COND_WHILE_1^#
}
func testWhile2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while #^COND_WHILE_2^# {
}
}
func testWhile2b(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while true, #^COND_WHILE_2B^# {
}
}
func testWhile3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while var z = #^COND_WHILE_3^#
}
func testWhile4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while let z = #^COND_WHILE_4^#
}
func testRepeatWhile1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
repeat {
} while #^COND_DO_WHILE_1^#
}
func testRepeatWhile2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
repeat {
} while localFooObject.#^COND_DO_WHILE_2^#
}
func testCStyleForInit1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for #^C_STYLE_FOR_INIT_1^#
}
func testCStyleForInit2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for #^C_STYLE_FOR_INIT_2^#;
}
func testCStyleForInit3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for #^C_STYLE_FOR_INIT_3^# ;
}
func testCStyleForCond1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; #^C_STYLE_FOR_COND_1^#
}
func testCStyleForCond2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; #^C_STYLE_FOR_COND_2^#;
}
func testCStyleForCond3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; #^C_STYLE_FOR_COND_3^# ;
}
func testCStyleForCondI1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; #^C_STYLE_FOR_COND_I_1^#
}
func testCStyleForCondI2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = unknown_var; #^C_STYLE_FOR_COND_I_2^#
}
func testCStyleForCondIE1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0, e = 10; true; #^C_STYLE_FOR_COND_I_E_1^#
}
func testCStyleForIncr1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; ; #^C_STYLE_FOR_INCR_1^#
}
func testCStyleForIncr2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; ; #^C_STYLE_FOR_INCR_2^# {
}
}
func testCStyleForIncrI1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; true; #^C_STYLE_FOR_INCR_I_1^#
}
func testCStyleForIncrI2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; i != 10; #^C_STYLE_FOR_INCR_I_2^#
}
func testCStyleForIncrI3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; unknown_var != 10; #^C_STYLE_FOR_INCR_I_3^#
}
func testCStyleForIncrI4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = unknown_var; unknown_var != 10; #^C_STYLE_FOR_INCR_I_4^#
}
func testCStyleForIncrIE1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0, e = 10; true; #^C_STYLE_FOR_INCR_I_E_1^#
}
func testCStyleForBodyI1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0 {
#^C_STYLE_FOR_BODY_I_1^#
}
}
func testCStyleForBodyI2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; {
#^C_STYLE_FOR_BODY_I_2^#
}
}
func testCStyleForBodyI3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = unknown_var; {
#^C_STYLE_FOR_BODY_I_3^#
}
}
func testCStyleForBodyI4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; ; {
#^C_STYLE_FOR_BODY_I_4^#
}
}
func testCStyleForBodyI5(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; unknown_var != 10; {
#^C_STYLE_FOR_BODY_I_5^#
}
}
func testCStyleForBodyI6(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; ; unknown_var++ {
#^C_STYLE_FOR_BODY_I_6^#
}
}
func testForEachExpr1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for i in #^FOR_EACH_EXPR_1^#
}
func testForEachExpr2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for i in #^FOR_EACH_EXPR_2^# {
}
}
func testSwitchExpr1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch #^SWITCH_EXPR_1^#
}
func testSwitchExpr2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch #^SWITCH_EXPR_2^# {
}
}
func testSwitchCaseWhereExpr1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (0, 0) where #^SWITCH_CASE_WHERE_EXPR_1^#
}
}
func testSwitchCaseWhereExpr2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (0, 0) where #^SWITCH_CASE_WHERE_EXPR_2^#:
}
}
func testSwitchCaseWhereExpr3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (0, 0) where #^SWITCH_CASE_WHERE_EXPR_3^# :
}
}
func testSwitchCaseWhereExprI1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (var i, 0) where #^SWITCH_CASE_WHERE_EXPR_I_1^#
}
}
func testSwitchCaseWhereExprI2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (0, var i) where #^SWITCH_CASE_WHERE_EXPR_I_2^#
}
}
func testSwitchCaseWhereExprIJ1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (var i, var j) where #^SWITCH_CASE_WHERE_EXPR_I_J_1^#
}
}
// COND_NONE-NOT: Begin completions
// COND_NONE-NOT: End completions
// COND_COMMON: Begin completions
// COND_COMMON-DAG: Literal[Boolean]/None: true[#Bool#]{{; name=.+$}}
// COND_COMMON-DAG: Literal[Boolean]/None: false[#Bool#]{{; name=.+$}}
// COND_COMMON-DAG: Decl[LocalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// COND_COMMON-DAG: Decl[LocalVar]/Local: localInt[#Int#]{{; name=.+$}}
// COND_COMMON-DAG: Decl[LocalVar]/Local: localFooObject[#FooStruct#]{{; name=.+$}}
// COND_COMMON-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// COND_COMMON: End completions
// COND-WITH-RELATION: Begin completions
// COND-WITH-RELATION-DAG: Literal[Boolean]/None/TypeRelation[Identical]: true[#Bool#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Literal[Boolean]/None/TypeRelation[Identical]: false[#Bool#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[LocalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[LocalVar]/Local: localInt[#Int#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[LocalVar]/Local: localFooObject[#FooStruct#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: testIf2({#(fooObject): FooStruct#})[#Void#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: testWhile3({#(fooObject): FooStruct#})[#Void#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: testIfElseIf5({#(fooObject): FooStruct#})[#Void#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: testCStyleForIncrIE1({#(fooObject): FooStruct#})[#Void#]{{; name=.+$}}
// COND-WITH-RELATION1: Begin completions
// COND-WITH-RELATION1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// COND-WITH-RELATION1-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: boolGen()[#Bool#]{{; name=.+$}}
// COND-WITH-RELATION1-DAG: Decl[InstanceMethod]/CurrNominal: intGen()[#Int#]{{; name=.+$}}
// COND-WITH-RELATION1: End completions
// WITH_I_INT_LOCAL: Decl[LocalVar]/Local: i[#Int#]{{; name=.+$}}
// WITH_I_ERROR_LOCAL: Decl[LocalVar]/Local: i[#<<error type>>#]{{; name=.+$}}
// WITH_J_INT: Decl[LocalVar]/Local: j[#Int#]{{; name=.+$}}
enum A { case aaa }
enum B { case bbb }
// UNRESOLVED_B-NOT: aaa
// UNRESOLVED_B: Decl[EnumElement]/CurrNominal/TypeRelation[Identical]: bbb[#B#]; name=bbb
// UNRESOLVED_B-NOT: aaa
struct AA {
func takeEnum(_: A) {}
}
struct BB {
func takeEnum(_: B) {}
}
func testUnresolvedIF1(x: BB) {
if x.takeEnum(.#^UNRESOLVED_IF_1^#)
}
func testUnresolvedIF2(x: BB) {
if true, x.takeEnum(.#^UNRESOLVED_IF_2^#)
}
func testUnresolvedIF3(x: BB) {
if true, x.takeEnum(.#^UNRESOLVED_IF_3^#) {}
}
func testUnresolvedIF4(x: BB) {
if let x.takeEnum(.#^UNRESOLVED_IF_4^#)
}
func testUnresolvedWhile1(x: BB) {
while x.takeEnum(.#^UNRESOLVED_WHILE_1^#)
}
func testUnresolvedWhile2(x: BB) {
while true, x.takeEnum(.#^UNRESOLVED_WHILE_2^#)
}
func testUnresolvedWhile3(x: BB) {
while let x.takeEnum(.#^UNRESOLVED_WHILE_3^#)
}
func testUnresolvedWhile4(x: BB) {
while true, x.takeEnum(.#^UNRESOLVED_WHILE_4^#) {}
}
func testUnresolvedGuard1(x: BB) {
guard x.takeEnum(.#^UNRESOLVED_GUARD_1^#)
}
func testUnresolvedGuard2(x: BB) {
guard x.takeEnum(.#^UNRESOLVED_GUARD_2^#) {}
}
func testUnresolvedGuard3(x: BB) {
guard x.takeEnum(.#^UNRESOLVED_GUARD_3^#) else
}
func testUnresolvedGuard4(x: BB) {
guard x.takeEnum(.#^UNRESOLVED_GUARD_4^#) else {}
}
func testUnresolvedGuard5(x: BB) {
guard true, x.takeEnum(.#^UNRESOLVED_GUARD_5^#)
}
func testUnresolvedGuard6(x: BB) {
guard let x.takeEnum(.#^UNRESOLVED_GUARD_6^#)
}
func testUnresolvedGuard7(x: BB) {
guard let x.takeEnum(.#^UNRESOLVED_GUARD_7^#) else {}
}
func testIfLetBinding1(x: FooStruct?) {
if let y = x, y.#^IF_LET_BIND_1^# {}
}
func testIfLetBinding2(x: FooStruct?) {
if let y = x, y.#^IF_LET_BIND_2^#
}
func testIfLetBinding3(x: FooStruct?) {
if let y = x, let z = y.#^IF_LET_BIND_3^# {}
}
func testIfLetBinding3(x: FooStruct?) {
if let y = x, let z = y#^IF_LET_BIND_4^# {}
}
func testGuardLetBinding1(x: FooStruct?) {
guard let y = x, y.#^GUARD_LET_BIND_1^# else {}
}
func testGuardLetBinding2(x: FooStruct?) {
guard let y = x, y.#^GUARD_LET_BIND_2^#
}
func testGuardLetBinding3(x: FooStruct?) {
guard let y = x, y.#^GUARD_LET_BIND_3^# else
}
func testGuardLetBinding4(x: FooStruct?) {
guard let y = x, y.#^GUARD_LET_BIND_4^# {}
}
func testGuardLetBinding5(x: FooStruct?) {
guard let y = x, let z = y.#^GUARD_LET_BIND_5^# else {}
}
func testGuardLetBinding5(x: FooStruct?) {
guard let y = x, z = y#^GUARD_LET_BIND_6^# else {}
}
func testGuardLetBinding7(x: FooStruct?) {
guard let boundVal = x, let other = #^GUARD_LET_BIND_7^# else {}
}
func testGuardLetBinding8(_ x: FooStruct?) {
guard let boundVal = x, let other = testGuardLetBinding8(#^GUARD_LET_BIND_8^#) else {}
}
// FOOSTRUCT_DOT: Begin completions
// FOOSTRUCT_DOT-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#];
// FOOSTRUCT_DOT-DAG: Decl[InstanceMethod]/CurrNominal: boolGen()[#Bool#];
// FOOSTRUCT_DOT-DAG: Decl[InstanceMethod]/CurrNominal: intGen()[#Int#];
// FOOSTRUCT_DOT: End completions
// FOOSTRUCT_DOT_BOOL: Begin completions
// FOOSTRUCT_DOT_BOOL-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#];
// FOOSTRUCT_DOT_BOOL-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: boolGen()[#Bool#];
// FOOSTRUCT_DOT_BOOL-DAG: Decl[InstanceMethod]/CurrNominal: intGen()[#Int#];
// FOOSTRUCT_DOT_BOOL: End completions
// FOOSTRUCT_NODOT: Begin completions
// FOOSTRUCT_NODOT-DAG: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#];
// FOOSTRUCT_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .boolGen()[#Bool#];
// FOOSTRUCT_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .intGen()[#Int#];
// FOOSTRUCT_NODOT: End completions
// FOOSTRUCT_LOCALVAL: Begin completions
// FOOSTRUCT_LOCALVAL-DAG: Decl[LocalVar]/Local{{(/TypeRelation\[Convertible\])?}}: boundVal[#FooStruct#];
// FOOSTRUCT_LOCALVAL: End completions
| apache-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/27019-swift-genericfunctiontype-get.swift | 11 | 456 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
{l{}{let a=((t> {}class a{func fQ{enum A{var f=a{struct c<U:U.R
| apache-2.0 |
Alienson/Bc | source-code/Parketovanie/ParquetDuo.swift | 1 | 1814 | //
// ParquetDuo.swift
// Parketovanie
//
// Created by Adam Turna on 19.4.2016.
// Copyright © 2016 Adam Turna. All rights reserved.
//
import Foundation
import SpriteKit
class ParquetDuo: Parquet {
init(parent: SKSpriteNode, position: CGPoint){
super.init(imageNamed: "2-duo", position: position)
let abstractCell = Cell()
let height = abstractCell.frame.height
// self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height), parent: parent))
// self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height*2), parent: parent))
// self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height*3), parent: parent))
// self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX+height, y: self.frame.maxY-height*3), parent: parent))
self.arrayOfCells.append(Cell(position: CGPoint(x: 0, y: -height/2), parent: parent))
self.arrayOfCells.append(Cell(position: CGPoint(x: 0, y: height/2), parent: parent))
//let cell1 = Cell(row: 1, collumn: 1, isEmpty: true, parent: parent)
for cell in self.arrayOfCells {
//parent.addChild(cell)
self.addChild(cell)
cell.anchorPoint = CGPoint(x: 0.5, y: 0.5)
cell.alpha = CGFloat(1)
cell.barPosition = cell.position
}
super.alpha = CGFloat(0.5)
//self.arrayOfCells = [[Cell(position: CGPoint(self.frame.),parent: parent), nil],[Cell(parent: parent), nil],[Cell(parent: parent), Cell(parent: parent)]]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/27760-swift-inflightdiagnostic.swift | 11 | 564 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
{
struct A{
struct S{class a{
class A{struct c{
struct c{{{
}}
enum b{
class d{
{}struct S<T where g:B
}
struct d
func g{
enum B<T where h:a{class A{
let a{{
{
{
{}}
}}
A{
| apache-2.0 |
mikekavouras/Glowb-iOS | Glowb/Wizard/Commands/Command+ScanAP.swift | 1 | 582 | //
// ScanAP.swift
// ParticleConnect
//
// Created by Michael Kavouras on 10/29/16.
// Copyright © 2016 Mike Kavouras. All rights reserved.
//
extension Command {
struct ScanAP: ParticleCommunicable {
static var command: String = "scan-ap\n0\n\n"
internal static func parse(_ json: JSON) -> [Network]? {
guard let scans = json["scans"] as? [JSON] else {
return nil
}
let networks = scans.map { Network(json: $0) }
return networks.sorted(by: { $0.rssi > $1.rssi })
}
}
}
| mit |
ScoutHarris/WordPress-iOS | WordPress/Classes/Extensions/WPStyleGuide+ApplicationStyles.swift | 2 | 419 | import Foundation
import WordPressShared
extension WPStyleGuide {
public class func navigationBarBackgroundImage() -> UIImage {
return UIImage(color: WPStyleGuide.wordPressBlue())
}
public class func navigationBarBarStyle() -> UIBarStyle {
return .black
}
public class func navigationBarShadowImage() -> UIImage {
return UIImage(color: UIColor(fromHex: 0x007eb1))
}
}
| gpl-2.0 |
GenerallyHelpfulSoftware/Scalar2D | Views/Cocoa/Sources/PathView+Mac.swift | 1 | 2895 | //
// PathView+Mac.swift
// Scalar2D
//
// Created by Glenn Howes on 8/17/16.
// Copyright © 2016-2019 Generally Helpful Software. All rights reserved.
//
//
// The MIT License (MIT)
// Copyright (c) 2016-2019 Generally Helpful Software
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
#if os(OSX)
import Cocoa
import CoreGraphics
import Scalar2D_CoreViews
import Foundation
import Cocoa
@IBDesignable public class PathView: NSView, ShapeView {
public required init?(coder: NSCoder) {
super.init(coder: coder)
self.wantsLayer = true
let myLayer = PathViewLayer()
self.layer = myLayer
}
@IBInspectable public var svgPath: String?
{
didSet
{
self.setPathString(pathString: svgPath)
}
}
@IBInspectable public var lineWidth: CGFloat = 1
{
didSet
{
self.shapeLayer.lineWidth = lineWidth
}
}
@IBInspectable public var fillColor: NSColor?
{
didSet
{
self.shapeLayer.fillColor = fillColor?.cgColor
}
}
@IBInspectable public var strokeColor: NSColor?
{
didSet
{
self.shapeLayer.strokeColor = strokeColor?.cgColor
}
}
@IBInspectable public var strokeStart : CGFloat = 0.0
{
didSet
{
self.shapeLayer.strokeStart = self.strokeStart
}
}
@IBInspectable public var strokeEnd : CGFloat = 1.0
{
didSet
{
self.shapeLayer.strokeEnd = self.strokeEnd
}
}
override public var isFlipped: Bool // to be like the iOS version
{
return true
}
public var shapeLayer: CAShapeLayer
{
return (self.layer as! PathViewLayer).shapeLayer
}
}
#endif
| mit |
wjkohnen/antlr4 | runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloParserATN.swift | 3 | 882 | class HelloParserATN {
let jsonString: String = "{\"version\":3,\"uuid\":\"aadb8d7e-aeef-4415-ad2b-8204d6cf042e\",\"grammarType\":1,\"maxTokenType\":3,\"states\":[{\"stateType\":2,\"ruleIndex\":0},{\"stateType\":7,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0}],\"nonGreedyStates\":[],\"precedenceStates\":[],\"ruleToStartState\":[{\"stateNumber\":0}],\"modeToStartState\":[],\"nsets\":0,\"IntervalSet\":[],\"allTransitionsBuilder\":[[{\"src\":0,\"trg\":2,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":2,\"trg\":3,\"edgeType\":5,\"arg1\":1,\"arg2\":0,\"arg3\":0}],[{\"src\":3,\"trg\":4,\"edgeType\":5,\"arg1\":2,\"arg2\":0,\"arg3\":0}],[{\"src\":4,\"trg\":1,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[]],\"decisionToState\":[],\"lexerActions\":[]}"
} | bsd-3-clause |
ello/ello-ios | Specs/Controllers/Stream/Cells/StreamImageCellSpec.swift | 1 | 2227 | ////
/// StreamImageCellSpec.swift
//
@testable import Ello
import Quick
import Nimble
class StreamImageCellSpec: QuickSpec {
override func spec() {
describe("StreamImageCell") {
let image = UIImage.imageWithColor(.blue, size: CGSize(width: 500, height: 300))!
let expectations: [(listView: Bool, isComment: Bool, isRepost: Bool, buyButton: Bool)] =
[
(listView: true, isComment: false, isRepost: false, buyButton: false),
(listView: true, isComment: false, isRepost: false, buyButton: true),
(listView: true, isComment: false, isRepost: true, buyButton: false),
(listView: true, isComment: false, isRepost: true, buyButton: true),
(listView: true, isComment: true, isRepost: false, buyButton: false),
(listView: false, isComment: false, isRepost: false, buyButton: false),
(listView: false, isComment: false, isRepost: false, buyButton: true),
(listView: false, isComment: false, isRepost: true, buyButton: false),
(listView: false, isComment: false, isRepost: true, buyButton: true),
(listView: false, isComment: true, isRepost: false, buyButton: false),
]
for (listView, isComment, isRepost, buyButton) in expectations {
it(
"\(listView ? "list" : "grid") view \(isComment ? "comment" : (isRepost ? "repost" : "post"))\(buyButton ? " with buy button" : "") should match snapshot"
) {
let subject = StreamImageCell.loadFromNib() as StreamImageCell
subject.frame = CGRect(origin: .zero, size: CGSize(width: 375, height: 225))
subject.isGridView = !listView
subject.marginType = (isComment ? .comment : (isRepost ? .repost : .post))
subject.setImage(image)
if buyButton {
subject.buyButtonURL = URL(string: "http://ello.co")
}
expectValidSnapshot(subject)
}
}
}
}
}
| mit |
sprint84/TabbedCollectionView | TabbedCollectionViewTests/TabbedCollectionViewTests.swift | 1 | 1033 | //
// TabbedCollectionViewTests.swift
// TabbedCollectionViewTests
//
// Created by Guilherme Moura on 12/3/15.
// Copyright © 2015 Reefactor, Inc. All rights reserved.
//
import XCTest
@testable import TabbedCollectionView
class TabbedCollectionViewTests: 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 |
huangboju/Moots | 算法学习/LeetCode/LeetCode/FourSumCount.swift | 1 | 611 | //
// FourSumCount.swift
// LeetCode
//
// Created by xiAo_Ju on 2019/9/29.
// Copyright © 2019 伯驹 黄. All rights reserved.
//
import Foundation
func fourSumCount(_ A: [Int], _ B: [Int], _ C: [Int], _ D: [Int]) -> Int {
var map: [Int: Int] = [:]
for a in A {
for b in B {
let sum = a + b
map[sum, default: 0] += 1
}
}
var count = 0
for c in C {
for d in D {
let sum = c + d
if let negativeOfSum = map[-sum] {
count += negativeOfSum
}
}
}
return count
}
| mit |
tectijuana/patrones | Bloque1SwiftArchivado/PracticasSwift/JuanAlv/programa 11.swift | 1 | 875 | //Title: Problema 11 Filename: programa 11.swift
//Author: Alvarado Rodriguez Juan Manuel Date: 22 - Feb - 2017
//Description: introducir un conjunto de 25 numeros. determinar la cantidad de numeros positivos y negativos del conjunto
//Input: 25 numeros
//Output: cantidad de numeros negativos y positivos
//random
func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
//arreglo
var arreglo=[Int]()
var contNeg : Int = 0
var contPos : Int = 0
//llenado de 25 datos en el arreglo
for i in 0..<24{
arreglo.append(randomInt(min: -100, max:100))
if arreglo[i]>=0{
contPos+=1
}
else{
contNeg+=1
}
}
//impresion de cantidad de numeros negativos y positivos
print("cantidad de numeros positivos: \(contPos)")
print("cantidad de numeros negativos: \(contNeg)")
| gpl-3.0 |
CalebeEmerick/Checkout | Source/Checkout/StoresController.swift | 1 | 3388 | //
// StoresController.swift
// Checkout
//
// Created by Calebe Emerick on 30/11/16.
// Copyright © 2016 CalebeEmerick. All rights reserved.
//
import UIKit
// MARK: - Variables & Outlets -
final class StoresController : UIViewController {
@IBOutlet fileprivate weak var container: UIView!
@IBOutlet fileprivate weak var collectionView: UICollectionView!
@IBOutlet fileprivate weak var activityIndicator: UIActivityIndicatorView!
fileprivate let storeError = StoreError.makeXib()
fileprivate let dataSource = StoreDataSource()
fileprivate let delegate = StoreDelegate()
fileprivate let layout = StoreLayout()
fileprivate var presenter: StorePresenter?
}
// MARK: - Life Cycle -
extension StoresController {
override func viewDidLoad() {
super.viewDidLoad()
changeNavigationBarBackButton()
presenter = StorePresenter(storeView: self)
delegate.selectedStore = { [weak self] store in self?.openTransactionController(with: store) }
layout.setupCollectionView(for: collectionView, dataSource: dataSource, delegate: delegate)
setErrorViewConstraints()
presenter?.getStores()
}
}
// MARK: - Methods -
extension StoresController {
fileprivate func setErrorViewConstraints() {
DispatchQueue.main.async {
self.storeError.alpha = 0
self.storeError.triedAgain = { self.tryLoadStoresAgain() }
self.view.addSubview(self.storeError)
self.storeError.translatesAutoresizingMaskIntoConstraints = false
self.storeError.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true
self.storeError.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8).isActive = true
self.storeError.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8).isActive = true
self.storeError.heightAnchor.constraint(equalToConstant: self.storeError.bounds.height).isActive = true
}
}
fileprivate func changeStoreError(alpha: CGFloat) {
UIView.animate(withDuration: 0.4) {
self.storeError.alpha = alpha
}
}
}
// MARK: - StoresView Protocol -
extension StoresController : StoresView {
func showLoading() {
activityIndicator.startAnimating()
}
func hideLoading() {
activityIndicator.stopAnimating()
}
func showContainer() {
hideLoading()
UIView.animate(withDuration: 0.4) {
self.container.alpha = 1
}
}
func update(stores: [Store]) {
DispatchQueue.main.async {
self.dataSource.stores = stores
self.collectionView.reloadData()
}
}
func showError(message: String) {
storeError.message = message
changeStoreError(alpha: 1)
}
func hideError() {
changeStoreError(alpha: 0)
}
func tryLoadStoresAgain() {
hideError()
showLoading()
presenter?.getStores()
}
func openTransactionController(with store: Store) {
TransactionRouter.openCreditCardTransactionController(from: self, with: store)
}
}
| mit |
atrick/swift | test/SILOptimizer/static_arrays.swift | 5 | 9301 | // RUN: %target-swift-frontend -primary-file %s -O -sil-verify-all -Xllvm -sil-disable-pass=FunctionSignatureOpts -module-name=test -emit-sil | %FileCheck %s
// RUN: %target-swift-frontend -primary-file %s -O -sil-verify-all -Xllvm -sil-disable-pass=FunctionSignatureOpts -module-name=test -emit-ir | %FileCheck %s -check-prefix=CHECK-LLVM
// Also do an end-to-end test to check all components, including IRGen.
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -O -Xllvm -sil-disable-pass=FunctionSignatureOpts -module-name=test %s -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s -check-prefix=CHECK-OUTPUT
// REQUIRES: executable_test,swift_stdlib_no_asserts,optimized_stdlib
// REQUIRES: CPU=arm64 || CPU=x86_64
// Check if the optimizer is able to convert array literals to statically initialized arrays.
// CHECK-LABEL: sil_global @$s4test4FStrV10globalFuncyS2icvpZ : $@callee_guaranteed (Int) -> Int = {
// CHECK: %0 = function_ref @$s4test3fooyS2iF : $@convention(thin) (Int) -> Int
// CHECK-NEXT: %initval = thin_to_thick_function %0
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of arrayLookup(_:)
// CHECK-NEXT: sil_global private @{{.*}}arrayLookup{{.*}} = {
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 10
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 11
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 12
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}}, {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of returnArray()
// CHECK-NEXT: sil_global private @{{.*}}returnArray{{.*}} = {
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 20
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 21
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of returnStaticStringArray()
// CHECK-NEXT: sil_global private @{{.*}}returnStaticStringArray{{.*}} = {
// CHECK-DAG: string_literal utf8 "a"
// CHECK-DAG: string_literal utf8 "b"
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of passArray()
// CHECK-NEXT: sil_global private @{{.*}}passArray{{.*}} = {
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 27
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 28
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #1 of passArray()
// CHECK-NEXT: sil_global private @{{.*}}passArray{{.*}} = {
// CHECK: integer_literal $Builtin.Int{{[0-9]+}}, 29
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of storeArray()
// CHECK-NEXT: sil_global private @{{.*}}storeArray{{.*}} = {
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 227
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 228
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of functionArray()
// CHECK-NEXT: sil_global private @{{.*functionArray.*}} = {
// CHECK: function_ref
// CHECK: thin_to_thick_function
// CHECK: convert_function
// CHECK: function_ref
// CHECK: thin_to_thick_function
// CHECK: convert_function
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems]
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of returnDictionary()
// CHECK-NEXT: sil_global private @{{.*}}returnDictionary{{.*}} = {
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 5
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 4
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 2
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 1
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 6
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 3
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems]
// CHECK-NEXT: }
// CHECK-LABEL: outlined variable #0 of returnStringDictionary()
// CHECK-NEXT: sil_global private @{{.*}}returnStringDictionary{{.*}} = {
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems]
// CHECK-NEXT: }
// CHECK-LABEL: sil_global private @{{.*}}main{{.*}} = {
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 100
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 101
// CHECK-DAG: integer_literal $Builtin.Int{{[0-9]+}}, 102
// CHECK: object {{.*}} ({{[^,]*}}, [tail_elems] {{[^,]*}}, {{[^,]*}}, {{[^,]*}})
// CHECK-NEXT: }
// CHECK-LABEL: sil {{.*}}@main
// CHECK: global_value @{{.*}}main{{.*}}
// CHECK: return
public let globalVariable = [ 100, 101, 102 ]
// CHECK-LABEL: sil [noinline] @$s4test11arrayLookupyS2iF
// CHECK: global_value @$s4test11arrayLookupyS2iFTv_
// CHECK-NOT: retain
// CHECK-NOT: release
// CHECK: } // end sil function '$s4test11arrayLookupyS2iF'
// CHECK-LLVM-LABEL: define {{.*}} @"$s4test11arrayLookupyS2iF"
// CHECK-LLVM-NOT: call
// CHECK-LLVM: [[E:%[0-9]+]] = getelementptr {{.*}} @"$s4test11arrayLookupyS2iFTv_"
// CHECK-LLVM-NEXT: [[L:%[0-9]+]] = load {{.*}} [[E]]
// CHECK-LLVM-NEXT: ret {{.*}} [[L]]
// CHECK-LLVM: }
@inline(never)
public func arrayLookup(_ i: Int) -> Int {
let lookupTable = [10, 11, 12]
return lookupTable[i]
}
// CHECK-LABEL: sil {{.*}}returnArray{{.*}} : $@convention(thin) () -> @owned Array<Int> {
// CHECK: global_value @{{.*}}returnArray{{.*}}
// CHECK: return
@inline(never)
public func returnArray() -> [Int] {
return [20, 21]
}
// CHECK-LABEL: sil {{.*}}returnStaticStringArray{{.*}} : $@convention(thin) () -> @owned Array<StaticString> {
// CHECK: global_value @{{.*}}returnStaticStringArray{{.*}}
// CHECK: return
@inline(never)
public func returnStaticStringArray() -> [StaticString] {
return ["a", "b"]
}
public var gg: [Int]?
@inline(never)
public func receiveArray(_ a: [Int]) {
gg = a
}
// CHECK-LABEL: sil {{.*}}passArray{{.*}} : $@convention(thin) () -> () {
// CHECK: global_value @{{.*}}passArray{{.*}}
// CHECK: global_value @{{.*}}passArray{{.*}}
// CHECK: return
@inline(never)
public func passArray() {
receiveArray([27, 28])
receiveArray([29])
}
// CHECK-LABEL: sil {{.*}}storeArray{{.*}} : $@convention(thin) () -> () {
// CHECK: global_value @{{.*}}storeArray{{.*}}
// CHECK: return
@inline(never)
public func storeArray() {
gg = [227, 228]
}
struct Empty { }
// CHECK-LABEL: sil {{.*}}arrayWithEmptyElements{{.*}} : $@convention(thin) () -> @owned Array<Empty> {
func arrayWithEmptyElements() -> [Empty] {
// CHECK: global_value @{{.*}}arrayWithEmptyElements{{.*}}
// CHECK: return
return [Empty()]
}
// CHECK-LABEL: sil {{.*}}returnDictionary{{.*}} : $@convention(thin) () -> @owned Dictionary<Int, Int> {
// CHECK: global_value @{{.*}}returnDictionary{{.*}}
// CHECK: return
@inline(never)
public func returnDictionary() -> [Int:Int] {
return [1:2, 3:4, 5:6]
}
// CHECK-LABEL: sil {{.*}}returnStringDictionary{{.*}} : $@convention(thin) () -> @owned Dictionary<String, String> {
// CHECK: global_value @{{.*}}returnStringDictionary{{.*}}
// CHECK: return
@inline(never)
public func returnStringDictionary() -> [String:String] {
return ["1":"2", "3":"4", "5":"6"]
}
func foo(_ i: Int) -> Int { return i }
// CHECK-LABEL: sil {{.*functionArray.*}} : $@convention(thin) () -> @owned Array<(Int) -> Int> {
// CHECK: global_value @{{.*functionArray.*}}
// CHECK: } // end sil function '{{.*functionArray.*}}'
@inline(never)
func functionArray() -> [(Int) -> Int] {
func bar(_ i: Int) -> Int { return i + 1 }
return [foo, bar, { $0 + 10 }]
}
public struct FStr {
// Not an array, but also tested here.
public static var globalFunc = foo
}
// CHECK-OUTPUT: [100, 101, 102]
print(globalVariable)
// CHECK-OUTPUT-NEXT: 11
print(arrayLookup(1))
// CHECK-OUTPUT-NEXT: [20, 21]
print(returnArray())
// CHECK-OUTPUT-NEXT: ["a", "b"]
print(returnStaticStringArray())
passArray()
// CHECK-OUTPUT-NEXT: [29]
print(gg!)
storeArray()
// CHECK-OUTPUT-NEXT: [227, 228]
print(gg!)
// CHECK-OUTPUT-NEXT: 311
print(functionArray()[0](100) + functionArray()[1](100) + functionArray()[2](100))
// CHECK-OUTPUT-NEXT: 27
print(FStr.globalFunc(27))
let dict = returnDictionary()
// CHECK-OUTPUT-NEXT: dict 3: 2, 4, 6
print("dict \(dict.count): \(dict[1]!), \(dict[3]!), \(dict[5]!)")
let sdict = returnStringDictionary()
// CHECK-OUTPUT-NEXT: sdict 3: 2, 4, 6
print("sdict \(sdict.count): \(sdict["1"]!), \(sdict["3"]!), \(sdict["5"]!)")
public class SwiftClass {}
@inline(never)
func takeUnsafePointer(ptr : UnsafePointer<SwiftClass>, len: Int) {
print(ptr, len) // Use the arguments somehow so they don't get removed.
}
// This should be a single basic block, and the array should end up being stack
// allocated.
//
// CHECK-LABEL: sil @{{.*}}passArrayOfClasses
// CHECK: bb0(%0 : $SwiftClass, %1 : $SwiftClass, %2 : $SwiftClass):
// CHECK-NOT: bb1(
// CHECK: alloc_ref{{(_dynamic)?}} {{.*}}[tail_elems $SwiftClass *
// CHECK-NOT: bb1(
// CHECK: return
public func passArrayOfClasses(a: SwiftClass, b: SwiftClass, c: SwiftClass) {
let arr = [a, b, c]
takeUnsafePointer(ptr: arr, len: arr.count)
}
| apache-2.0 |
nerdishbynature/octokit.swift | OctoKit/Parameters.swift | 1 | 315 | //
// Created by Marcin on 19/05/2017.
// Copyright (c) 2017 nerdish by nature. All rights reserved.
//
import Foundation
public enum SortDirection: String {
case asc
case desc
}
public enum SortType: String {
case created
case updated
case popularity
case longRunning = "long-running"
}
| mit |
joshkennede/ToDo | TodoTests/TodoTests.swift | 1 | 787 | //
// TodoTests.swift
// TodoTests
//
import UIKit
import XCTest
class TodoTests: 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.
}
}
}
| gpl-3.0 |
auth0/Auth0.swift | Auth0/Requestable.swift | 1 | 197 | import Foundation
protocol Requestable {
associatedtype ResultType
associatedtype ErrorType: Auth0APIError
func start(_ callback: @escaping (Result<ResultType, ErrorType>) -> Void)
}
| mit |
WEIHOME/SearchBarDemo-Swift | SearchBarDemo/AppDelegate.swift | 1 | 2149 | //
// AppDelegate.swift
// SearchBarDemo
//
// Created by Weihong Chen on 30/04/2015.
// Copyright (c) 2015 Weihong. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
jpush/jchat-swift | JChat/Src/UserModule/ViewController/JCSignatureViewController.swift | 1 | 4339 | //
// JCSignatureViewController.swift
// JChat
//
// Created by JIGUANG on 2017/3/29.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import JMessage
class JCSignatureViewController: UIViewController {
var signature: String!
override func viewDidLoad() {
super.viewDidLoad()
_init()
signatureTextView.text = signature
var count = 30 - signature.count
count = count < 0 ? 0 : count
tipLabel.text = "\(count)"
}
private var topOffset: CGFloat {
if isIPhoneX {
return 88
}
return 64
}
private lazy var saveButton: UIButton = {
var saveButton = UIButton()
saveButton.setTitle("提交", for: .normal)
let colorImage = UIImage.createImage(color: UIColor(netHex: 0x2dd0cf), size: CGSize(width: self.view.width - 30, height: 40))
saveButton.setBackgroundImage(colorImage, for: .normal)
saveButton.addTarget(self, action: #selector(_saveSignature), for: .touchUpInside)
return saveButton
}()
private lazy var bgView: UIView = {
let bgView = UIView(frame: CGRect(x: 0, y: self.topOffset, width: self.view.width, height: 120))
bgView.backgroundColor = .white
return bgView
}()
private lazy var signatureTextView: UITextView = {
let signatureTextView = UITextView(frame: CGRect(x: 15, y: 15, width: self.view.width - 30, height: 90))
signatureTextView.delegate = self
signatureTextView.font = UIFont.systemFont(ofSize: 16)
signatureTextView.backgroundColor = .white
return signatureTextView
}()
fileprivate lazy var tipLabel: UILabel = {
let tipLabel = UILabel(frame: CGRect(x: self.bgView.width - 15 - 50, y: self.bgView.height - 24, width: 50, height: 12))
tipLabel.textColor = UIColor(netHex: 0x999999)
tipLabel.font = UIFont.systemFont(ofSize: 12)
tipLabel.textAlignment = .right
return tipLabel
}()
private lazy var navRightButton: UIBarButtonItem = UIBarButtonItem(title: "保存", style: .plain, target: self, action: #selector(_saveSignature))
//MARK: - private func
private func _init() {
self.title = "个性签名"
automaticallyAdjustsScrollViewInsets = false;
view.backgroundColor = UIColor(netHex: 0xe8edf3)
view.addSubview(saveButton)
view.addSubview(bgView)
bgView.addSubview(signatureTextView)
bgView.addSubview(tipLabel)
view.addConstraint(_JCLayoutConstraintMake(saveButton, .left, .equal, view, .left, 15))
view.addConstraint(_JCLayoutConstraintMake(saveButton, .right, .equal, view, .right, -15))
view.addConstraint(_JCLayoutConstraintMake(saveButton, .top, .equal, bgView, .bottom, 15))
view.addConstraint(_JCLayoutConstraintMake(saveButton, .height, .equal, nil, .notAnAttribute, 40))
_setupNavigation()
}
private func _setupNavigation() {
navigationItem.rightBarButtonItem = navRightButton
}
//MARK: - click func
@objc func _saveSignature() {
signatureTextView.resignFirstResponder()
JMSGUser.updateMyInfo(withParameter: signatureTextView.text!, userFieldType: .fieldsSignature) { (resultObject, error) -> Void in
if error == nil {
NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateUserInfo), object: nil)
self.navigationController?.popViewController(animated: true)
} else {
print("error:\(String(describing: error?.localizedDescription))")
}
}
}
}
extension JCSignatureViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
if textView.markedTextRange == nil {
let text = textView.text!
if text.count > 30 {
let range = text.startIndex ..< text.index(text.startIndex, offsetBy: 30)
//let range = Range<String.Index>(text.startIndex ..< text.index(text.startIndex, offsetBy: 30))
let subText = text.substring(with: range)
textView.text = subText
}
let count = 30 - (textView.text?.count)!
tipLabel.text = "\(count)"
}
}
}
| mit |
googleapis/google-auth-library-swift | Sources/OAuth2/ServiceAccountTokenProvider/ServiceAccountTokenProvider.swift | 1 | 4179 | // Copyright 2019 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
struct ServiceAccountCredentials : Codable {
let CredentialType : String
let ProjectId : String
let PrivateKeyId : String
let PrivateKey : String
let ClientEmail : String
let ClientID : String
let AuthURI : String
let TokenURI : String
let AuthProviderX509CertURL : String
let ClientX509CertURL : String
enum CodingKeys: String, CodingKey {
case CredentialType = "type"
case ProjectId = "project_id"
case PrivateKeyId = "private_key_id"
case PrivateKey = "private_key"
case ClientEmail = "client_email"
case ClientID = "client_id"
case AuthURI = "auth_uri"
case TokenURI = "token_uri"
case AuthProviderX509CertURL = "auth_provider_x509_cert_url"
case ClientX509CertURL = "client_x509_cert_url"
}
}
public class ServiceAccountTokenProvider : TokenProvider {
public var token: Token?
var credentials : ServiceAccountCredentials
var scopes : [String]
var rsaKey : RSAKey
public init?(credentialsData:Data, scopes:[String]) {
let decoder = JSONDecoder()
guard let credentials = try? decoder.decode(ServiceAccountCredentials.self,
from: credentialsData)
else {
return nil
}
self.credentials = credentials
self.scopes = scopes
guard let rsaKey = RSAKey(privateKey:credentials.PrivateKey)
else {
return nil
}
self.rsaKey = rsaKey
}
convenience public init?(credentialsURL:URL, scopes:[String]) {
guard let credentialsData = try? Data(contentsOf:credentialsURL, options:[]) else {
return nil
}
self.init(credentialsData:credentialsData, scopes:scopes)
}
public func withToken(_ callback:@escaping (Token?, Error?) -> Void) throws {
// leave spare at least one second :)
if let token = token, token.timeToExpiry() > 1 {
callback(token, nil)
return
}
let iat = Date()
let exp = iat.addingTimeInterval(3600)
let jwtClaimSet = JWTClaimSet(Issuer:credentials.ClientEmail,
Audience:credentials.TokenURI,
Scope: scopes.joined(separator: " "),
IssuedAt: Int(iat.timeIntervalSince1970),
Expiration: Int(exp.timeIntervalSince1970))
let jwtHeader = JWTHeader(Algorithm: "RS256",
Format: "JWT")
let msg = try JWT.encodeWithRS256(jwtHeader:jwtHeader,
jwtClaimSet:jwtClaimSet,
rsaKey:rsaKey)
let json: [String: Any] = ["grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": msg]
let data = try JSONSerialization.data(withJSONObject: json)
var urlRequest = URLRequest(url:URL(string:credentials.TokenURI)!)
urlRequest.httpMethod = "POST"
urlRequest.httpBody = data
urlRequest.setValue("application/json", forHTTPHeaderField:"Content-Type")
let session = URLSession(configuration: URLSessionConfiguration.default)
let task: URLSessionDataTask = session.dataTask(with:urlRequest)
{(data, response, error) -> Void in
if let data = data,
let token = try? JSONDecoder().decode(Token.self, from: data) {
self.token = token
self.token?.CreationTime = Date()
callback(self.token, error)
} else {
callback(nil, error)
}
}
task.resume()
}
}
| apache-2.0 |
fyl00/MonkeyKing | China/AppDelegate.swift | 1 | 665 | //
// AppDelegate.swift
// China
//
// Created by NIX on 15/9/11.
// Copyright © 2015年 nixWork. All rights reserved.
//
import UIKit
import MonkeyKing
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
if MonkeyKing.handleOpenURL(url) {
return true
}
return false
}
}
| mit |
kousun12/RxSwift | RxSwift/Observables/Implementations/Range.swift | 8 | 1557 | //
// Range.swift
// Rx
//
// Created by Krunoslav Zaher on 9/13/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class RangeProducer<_CompilerWorkaround> : Producer<Int> {
private let _start: Int
private let _count: Int
private let _scheduler: ImmediateSchedulerType
init(start: Int, count: Int, scheduler: ImmediateSchedulerType) {
if count < 0 {
rxFatalError("count can't be negative")
}
if start &+ (count - 1) < start {
rxFatalError("overflow of count")
}
_start = start
_count = count
_scheduler = scheduler
}
override func run<O : ObserverType where O.E == Int>(observer: O) -> Disposable {
let sink = RangeSink(parent: self, observer: observer)
sink.disposable = sink.run()
return sink
}
}
class RangeSink<_CompilerWorkaround, O: ObserverType where O.E == Int> : Sink<O> {
typealias Parent = RangeProducer<_CompilerWorkaround>
private let _parent: Parent
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func run() -> Disposable {
return _parent._scheduler.scheduleRecursive(0) { i, recurse in
if i < self._parent._count {
self.forwardOn(.Next(self._parent._start + i))
recurse(i + 1)
}
else {
self.forwardOn(.Completed)
self.dispose()
}
}
}
} | mit |
DevaLee/LYCSwiftDemo | LYCSwiftDemo/Classes/live/ViewModel/LYCGifViewModel.swift | 1 | 1706 | //
// LYCGifViewModel.swift
// LYCSwiftDemo
//
// Created by yuchen.li on 2017/6/13.
// Copyright © 2017年 zsc. All rights reserved.
//
import UIKit
private let urlString = "http://qf.56.com/pay/v4/giftList.ios"
class LYCGifViewModel: NSObject {
static var shareInstance : LYCGifViewModel = LYCGifViewModel()
var gifPackage : [LYCGifModel] = []
override init (){
}
init(array : Array<[String : Any]>) {
for dict in array {
gifPackage.append(LYCGifModel(dict: dict))
}
}
}
extension LYCGifViewModel {
func loadGifData(finishCallBack : @escaping () -> ()){
gifPackage.removeAll()
LYCNetworkTool.loadData(type: .GET, urlString: urlString, parameter: ["type" : 0,"page" : 1 , "rows" : 150]) { (response) in
guard let responseResult = response as? [String : Any] else{
print("数据出错")
return
}
guard let type1Dict = responseResult["message"] as? [String : Any] else{
print("数据出错 message")
return
}
guard let listDict = type1Dict["type1"] as? [String : Any] else{
print("数据出错 list")
return
}
guard let listArray = listDict["list"] as? [[String : Any]] else{
print("数据出错 Array")
return
}
print("获取礼物列表成功")
for gifDict in listArray{
self.gifPackage.append(LYCGifModel(dict : gifDict))
}
finishCallBack()
}
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/DelegatedSelfCustody/Tests/DelegatedSelfCustodyDataTests/BuildTxResponseTests.swift | 1 | 4922 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
@testable import DelegatedSelfCustodyData
import ToolKit
import XCTest
// swiftlint:disable line_length
final class BuildTxResponseTests: XCTestCase {
func testDecodes() throws {
guard let jsonData = json.data(using: .utf8) else {
XCTFail("Failed to read data.")
return
}
let response = try JSONDecoder().decode(BuildTxResponse.self, from: jsonData)
XCTAssertEqual(response.summary.relativeFee, "1")
XCTAssertEqual(response.summary.absoluteFeeMaximum, "2")
XCTAssertEqual(response.summary.absoluteFeeEstimate, "3")
XCTAssertEqual(response.summary.amount, "4")
XCTAssertEqual(response.summary.balance, "5")
XCTAssertEqual(response.preImages.count, 1)
let preImage = response.preImages[0]
XCTAssertEqual(preImage.preImage, "1")
XCTAssertEqual(preImage.signingKey, "2")
XCTAssertEqual(preImage.signatureAlgorithm, .secp256k1)
XCTAssertNil(preImage.descriptor)
let payloadJsonValue: JSONValue = .dictionary([
"version": .number(0),
"auth": .dictionary([
"authType": .number(4),
"spendingCondition": .dictionary([
"hashMode": .number(0),
"signer": .string("71cb17c2d7f5e2ba71fab0aa6172f02d7265ff14"),
"nonce": .string("0"),
"fee": .string("600"),
"keyEncoding": .number(0),
"signature": .dictionary([
"type": .number(9),
"data": .string("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
])
])
]),
"payload": .dictionary([
"type": .number(8),
"payloadType": .number(0),
"recipient": .dictionary([
"type": .number(5),
"address": .dictionary([
"type": .number(0),
"version": .number(22),
"hash160": .string("afc896bb4b998cd40dd885b31d7446ef86b04eb0")
])
]),
"amount": .string("1"),
"memo": .dictionary([
"type": .number(3),
"content": .string("")
])
]),
"chainId": .number(1),
"postConditionMode": .number(2),
"postConditions": .dictionary([
"type": .number(7),
"lengthPrefixBytes": .number(4),
"values": .array([])
]),
"anchorMode": .number(3)
])
let rawTxJsonValue: JSONValue = .dictionary(
[
"version": .number(1),
"payload": payloadJsonValue
]
)
XCTAssertEqual(response.rawTx, rawTxJsonValue)
}
}
private let json = """
{
"summary": {
"relativeFee": "1",
"absoluteFeeMaximum": "2",
"absoluteFeeEstimate": "3",
"amount": "4",
"balance": "5"
},
"rawTx": {
"version": 1,
"payload": {
"version": 0,
"auth": {
"authType": 4,
"spendingCondition": {
"hashMode": 0,
"signer": "71cb17c2d7f5e2ba71fab0aa6172f02d7265ff14",
"nonce": "0",
"fee": "600",
"keyEncoding": 0,
"signature": {
"type": 9,
"data": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
}
}
},
"payload": {
"type": 8,
"payloadType": 0,
"recipient": {
"type": 5,
"address": {
"type": 0,
"version": 22,
"hash160": "afc896bb4b998cd40dd885b31d7446ef86b04eb0"
}
},
"amount": "1",
"memo": {
"type": 3,
"content": ""
}
},
"chainId": 1,
"postConditionMode": 2,
"postConditions": {
"type": 7,
"lengthPrefixBytes": 4,
"values": []
},
"anchorMode": 3
}
},
"preImages": [
{
"preImage": "1",
"signingKey": "2",
"descriptor": null,
"signatureAlgorithm": "secp256k1"
}
]
}
"""
| lgpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/Models/OrderDirection.swift | 1 | 626 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
public enum OrderDirection: String, Codable {
/// From non-custodial to non-custodial
case onChain = "ON_CHAIN"
/// From non-custodial to custodial
case fromUserKey = "FROM_USERKEY"
/// From custodial to non-custodial
case toUserKey = "TO_USERKEY"
/// From custodial to custodial
case `internal` = "INTERNAL"
}
extension OrderDirection {
public var isFromCustodial: Bool {
self == .toUserKey || self == .internal
}
public var isToCustodial: Bool {
self == .fromUserKey || self == .internal
}
}
| lgpl-3.0 |
modocache/swift | test/IRGen/builtins.swift | 2 | 29425 | // RUN: %target-swift-frontend -parse-stdlib -primary-file %s -emit-ir -o - -disable-objc-attr-requires-foundation-module | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
// REQUIRES: executable_test
// REQUIRES: CPU=x86_64
import Swift
// CHECK-DAG: [[REFCOUNT:%swift.refcounted.*]] = type
// CHECK-DAG: [[X:%C8builtins1X]] = type
// CHECK-DAG: [[Y:%C8builtins1Y]] = type
typealias Int = Builtin.Int32
typealias Bool = Builtin.Int1
infix operator * {
associativity left
precedence 200
}
infix operator / {
associativity left
precedence 200
}
infix operator % {
associativity left
precedence 200
}
infix operator + {
associativity left
precedence 190
}
infix operator - {
associativity left
precedence 190
}
infix operator << {
associativity none
precedence 180
}
infix operator >> {
associativity none
precedence 180
}
infix operator ... {
associativity none
precedence 175
}
infix operator < {
associativity none
precedence 170
}
infix operator <= {
associativity none
precedence 170
}
infix operator > {
associativity none
precedence 170
}
infix operator >= {
associativity none
precedence 170
}
infix operator == {
associativity none
precedence 160
}
infix operator != {
associativity none
precedence 160
}
func * (lhs: Int, rhs: Int) -> Int {
return Builtin.mul_Int32(lhs, rhs)
// CHECK: mul i32
}
func / (lhs: Int, rhs: Int) -> Int {
return Builtin.sdiv_Int32(lhs, rhs)
// CHECK: sdiv i32
}
func % (lhs: Int, rhs: Int) -> Int {
return Builtin.srem_Int32(lhs, rhs)
// CHECK: srem i32
}
func + (lhs: Int, rhs: Int) -> Int {
return Builtin.add_Int32(lhs, rhs)
// CHECK: add i32
}
func - (lhs: Int, rhs: Int) -> Int {
return Builtin.sub_Int32(lhs, rhs)
// CHECK: sub i32
}
// In C, 180 is <<, >>
func < (lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_slt_Int32(lhs, rhs)
// CHECK: icmp slt i32
}
func > (lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_sgt_Int32(lhs, rhs)
// CHECK: icmp sgt i32
}
func <=(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_sle_Int32(lhs, rhs)
// CHECK: icmp sle i32
}
func >=(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_sge_Int32(lhs, rhs)
// CHECK: icmp sge i32
}
func ==(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_eq_Int32(lhs, rhs)
// CHECK: icmp eq i32
}
func !=(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_ne_Int32(lhs, rhs)
// CHECK: icmp ne i32
}
func gepRaw_test(_ ptr: Builtin.RawPointer, offset: Builtin.Int64)
-> Builtin.RawPointer {
return Builtin.gepRaw_Int64(ptr, offset)
// CHECK: getelementptr inbounds i8, i8*
}
// CHECK: define hidden i64 @_TF8builtins9load_test
func load_test(_ ptr: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[CASTPTR:%.*]] = bitcast i8* [[PTR:%.*]] to i64*
// CHECK-NEXT: load i64, i64* [[CASTPTR]]
// CHECK: ret
return Builtin.load(ptr)
}
// CHECK: define hidden i64 @_TF8builtins13load_raw_test
func load_raw_test(_ ptr: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[CASTPTR:%.*]] = bitcast i8* [[PTR:%.*]] to i64*
// CHECK-NEXT: load i64, i64* [[CASTPTR]]
// CHECK: ret
return Builtin.loadRaw(ptr)
}
// CHECK: define hidden void @_TF8builtins11assign_test
func assign_test(_ value: Builtin.Int64, ptr: Builtin.RawPointer) {
Builtin.assign(value, ptr)
// CHECK: ret
}
// CHECK: define hidden %swift.refcounted* @_TF8builtins16load_object_test
func load_object_test(_ ptr: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[T0:%.*]] = load [[REFCOUNT]]*, [[REFCOUNT]]**
// CHECK: call void @swift_rt_swift_retain([[REFCOUNT]]* [[T0]])
// CHECK: ret [[REFCOUNT]]* [[T0]]
return Builtin.load(ptr)
}
// CHECK: define hidden %swift.refcounted* @_TF8builtins20load_raw_object_test
func load_raw_object_test(_ ptr: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[T0:%.*]] = load [[REFCOUNT]]*, [[REFCOUNT]]**
// CHECK: call void @swift_rt_swift_retain([[REFCOUNT]]* [[T0]])
// CHECK: ret [[REFCOUNT]]* [[T0]]
return Builtin.loadRaw(ptr)
}
// CHECK: define hidden void @_TF8builtins18assign_object_test
func assign_object_test(_ value: Builtin.NativeObject, ptr: Builtin.RawPointer) {
Builtin.assign(value, ptr)
}
// CHECK: define hidden void @_TF8builtins16init_object_test
func init_object_test(_ value: Builtin.NativeObject, ptr: Builtin.RawPointer) {
// CHECK: [[DEST:%.*]] = bitcast i8* {{%.*}} to %swift.refcounted**
// CHECK-NEXT: store [[REFCOUNT]]* {{%.*}}, [[REFCOUNT]]** [[DEST]]
Builtin.initialize(value, ptr)
}
func cast_test(_ ptr: inout Builtin.RawPointer, i8: inout Builtin.Int8,
i64: inout Builtin.Int64, f: inout Builtin.FPIEEE32,
d: inout Builtin.FPIEEE64
) {
// CHECK: cast_test
i8 = Builtin.trunc_Int64_Int8(i64) // CHECK: trunc
i64 = Builtin.zext_Int8_Int64(i8) // CHECK: zext
i64 = Builtin.sext_Int8_Int64(i8) // CHECK: sext
i64 = Builtin.ptrtoint_Int64(ptr) // CHECK: ptrtoint
ptr = Builtin.inttoptr_Int64(i64) // CHECK: inttoptr
i64 = Builtin.fptoui_FPIEEE64_Int64(d) // CHECK: fptoui
i64 = Builtin.fptosi_FPIEEE64_Int64(d) // CHECK: fptosi
d = Builtin.uitofp_Int64_FPIEEE64(i64) // CHECK: uitofp
d = Builtin.sitofp_Int64_FPIEEE64(i64) // CHECK: sitofp
d = Builtin.fpext_FPIEEE32_FPIEEE64(f) // CHECK: fpext
f = Builtin.fptrunc_FPIEEE64_FPIEEE32(d) // CHECK: fptrunc
i64 = Builtin.bitcast_FPIEEE64_Int64(d) // CHECK: bitcast
d = Builtin.bitcast_Int64_FPIEEE64(i64) // CHECK: bitcast
}
func intrinsic_test(_ i32: inout Builtin.Int32, i16: inout Builtin.Int16) {
i32 = Builtin.int_bswap_Int32(i32) // CHECK: llvm.bswap.i32(
i16 = Builtin.int_bswap_Int16(i16) // CHECK: llvm.bswap.i16(
var x = Builtin.int_sadd_with_overflow_Int16(i16, i16) // CHECK: call { i16, i1 } @llvm.sadd.with.overflow.i16(
Builtin.int_trap() // CHECK: llvm.trap()
}
// CHECK: define hidden void @_TF8builtins19sizeof_alignof_testFT_T_()
func sizeof_alignof_test() {
// CHECK: store i64 4, i64*
var xs = Builtin.sizeof(Int.self)
// CHECK: store i64 4, i64*
var xa = Builtin.alignof(Int.self)
// CHECK: store i64 1, i64*
var ys = Builtin.sizeof(Bool.self)
// CHECK: store i64 1, i64*
var ya = Builtin.alignof(Bool.self)
}
// CHECK: define hidden void @_TF8builtins27generic_sizeof_alignof_testurFxT_(
func generic_sizeof_alignof_test<T>(_: T) {
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 17
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[SIZE:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: store i64 [[SIZE]], i64* [[S:%.*]]
var s = Builtin.sizeof(T.self)
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 18
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[T2:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: [[T3:%.*]] = and i64 [[T2]], 65535
// CHECK-NEXT: [[ALIGN:%.*]] = add i64 [[T3]], 1
// CHECK-NEXT: store i64 [[ALIGN]], i64* [[A:%.*]]
var a = Builtin.alignof(T.self)
}
// CHECK: define hidden void @_TF8builtins21generic_strideof_testurFxT_(
func generic_strideof_test<T>(_: T) {
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 19
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[STRIDE:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: store i64 [[STRIDE]], i64* [[S:%.*]]
var s = Builtin.strideof(T.self)
}
class X {}
class Y {}
func move(_ ptr: Builtin.RawPointer) {
var temp : Y = Builtin.take(ptr)
// CHECK: define hidden void @_TF8builtins4move
// CHECK: [[SRC:%.*]] = bitcast i8* {{%.*}} to [[Y]]**
// CHECK-NEXT: [[VAL:%.*]] = load [[Y]]*, [[Y]]** [[SRC]]
// CHECK-NEXT: store [[Y]]* [[VAL]], [[Y]]** {{%.*}}
}
func allocDealloc(_ size: Builtin.Word, align: Builtin.Word) {
var ptr = Builtin.allocRaw(size, align)
Builtin.deallocRaw(ptr, size, align)
}
func fence_test() {
// CHECK: fence acquire
Builtin.fence_acquire()
// CHECK: fence singlethread acq_rel
Builtin.fence_acqrel_singlethread()
}
func cmpxchg_test(_ ptr: Builtin.RawPointer, a: Builtin.Int32, b: Builtin.Int32) {
// rdar://12939803 - ER: support atomic cmpxchg/xchg with pointers
// CHECK: [[Z_RES:%.*]] = cmpxchg i32* {{.*}}, i32 {{.*}}, i32 {{.*}} acquire acquire
// CHECK: [[Z_VAL:%.*]] = extractvalue { i32, i1 } [[Z_RES]], 0
// CHECK: [[Z_SUCCESS:%.*]] = extractvalue { i32, i1 } [[Z_RES]], 1
// CHECK: store i32 [[Z_VAL]], i32* {{.*}}, align 4
// CHECK: store i1 [[Z_SUCCESS]], i1* {{.*}}, align 1
var (z, zSuccess) = Builtin.cmpxchg_acquire_acquire_Int32(ptr, a, b)
// CHECK: [[Y_RES:%.*]] = cmpxchg volatile i32* {{.*}}, i32 {{.*}}, i32 {{.*}} monotonic monotonic
// CHECK: [[Y_VAL:%.*]] = extractvalue { i32, i1 } [[Y_RES]], 0
// CHECK: [[Y_SUCCESS:%.*]] = extractvalue { i32, i1 } [[Y_RES]], 1
// CHECK: store i32 [[Y_VAL]], i32* {{.*}}, align 4
// CHECK: store i1 [[Y_SUCCESS]], i1* {{.*}}, align 1
var (y, ySuccess) = Builtin.cmpxchg_monotonic_monotonic_volatile_Int32(ptr, a, b)
// CHECK: [[X_RES:%.*]] = cmpxchg volatile i32* {{.*}}, i32 {{.*}}, i32 {{.*}} singlethread acquire monotonic
// CHECK: [[X_VAL:%.*]] = extractvalue { i32, i1 } [[X_RES]], 0
// CHECK: [[X_SUCCESS:%.*]] = extractvalue { i32, i1 } [[X_RES]], 1
// CHECK: store i32 [[X_VAL]], i32* {{.*}}, align 4
// CHECK: store i1 [[X_SUCCESS]], i1* {{.*}}, align 1
var (x, xSuccess) = Builtin.cmpxchg_acquire_monotonic_volatile_singlethread_Int32(ptr, a, b)
// CHECK: [[W_RES:%.*]] = cmpxchg volatile i64* {{.*}}, i64 {{.*}}, i64 {{.*}} seq_cst seq_cst
// CHECK: [[W_VAL:%.*]] = extractvalue { i64, i1 } [[W_RES]], 0
// CHECK: [[W_SUCCESS:%.*]] = extractvalue { i64, i1 } [[W_RES]], 1
// CHECK: [[W_VAL_PTR:%.*]] = inttoptr i64 [[W_VAL]] to i8*
// CHECK: store i8* [[W_VAL_PTR]], i8** {{.*}}, align 8
// CHECK: store i1 [[W_SUCCESS]], i1* {{.*}}, align 1
var (w, wSuccess) = Builtin.cmpxchg_seqcst_seqcst_volatile_singlethread_RawPointer(ptr, ptr, ptr)
// CHECK: [[V_RES:%.*]] = cmpxchg weak volatile i64* {{.*}}, i64 {{.*}}, i64 {{.*}} seq_cst seq_cst
// CHECK: [[V_VAL:%.*]] = extractvalue { i64, i1 } [[V_RES]], 0
// CHECK: [[V_SUCCESS:%.*]] = extractvalue { i64, i1 } [[V_RES]], 1
// CHECK: [[V_VAL_PTR:%.*]] = inttoptr i64 [[V_VAL]] to i8*
// CHECK: store i8* [[V_VAL_PTR]], i8** {{.*}}, align 8
// CHECK: store i1 [[V_SUCCESS]], i1* {{.*}}, align 1
var (v, vSuccess) = Builtin.cmpxchg_seqcst_seqcst_weak_volatile_singlethread_RawPointer(ptr, ptr, ptr)
}
func atomicrmw_test(_ ptr: Builtin.RawPointer, a: Builtin.Int32,
ptr2: Builtin.RawPointer) {
// CHECK: atomicrmw add i32* {{.*}}, i32 {{.*}} acquire
var z = Builtin.atomicrmw_add_acquire_Int32(ptr, a)
// CHECK: atomicrmw volatile max i32* {{.*}}, i32 {{.*}} monotonic
var y = Builtin.atomicrmw_max_monotonic_volatile_Int32(ptr, a)
// CHECK: atomicrmw volatile xchg i32* {{.*}}, i32 {{.*}} singlethread acquire
var x = Builtin.atomicrmw_xchg_acquire_volatile_singlethread_Int32(ptr, a)
// rdar://12939803 - ER: support atomic cmpxchg/xchg with pointers
// CHECK: atomicrmw volatile xchg i64* {{.*}}, i64 {{.*}} singlethread acquire
var w = Builtin.atomicrmw_xchg_acquire_volatile_singlethread_RawPointer(ptr, ptr2)
}
func addressof_test(_ a: inout Int, b: inout Bool) {
// CHECK: bitcast i32* {{.*}} to i8*
var ap : Builtin.RawPointer = Builtin.addressof(&a)
// CHECK: bitcast i1* {{.*}} to i8*
var bp : Builtin.RawPointer = Builtin.addressof(&b)
}
func fneg_test(_ half: Builtin.FPIEEE16,
single: Builtin.FPIEEE32,
double: Builtin.FPIEEE64)
-> (Builtin.FPIEEE16, Builtin.FPIEEE32, Builtin.FPIEEE64)
{
// CHECK: fsub half 0xH8000, {{%.*}}
// CHECK: fsub float -0.000000e+00, {{%.*}}
// CHECK: fsub double -0.000000e+00, {{%.*}}
return (Builtin.fneg_FPIEEE16(half),
Builtin.fneg_FPIEEE32(single),
Builtin.fneg_FPIEEE64(double))
}
// The call to the builtins should get removed before we reach IRGen.
func testStaticReport(_ b: Bool, ptr: Builtin.RawPointer) -> () {
Builtin.staticReport(b, b, ptr);
return Builtin.staticReport(b, b, ptr);
}
// CHECK-LABEL: define hidden void @_TF8builtins12testCondFail{{.*}}(i1, i1)
func testCondFail(_ b: Bool, c: Bool) {
// CHECK: br i1 %0, label %[[FAIL:.*]], label %[[CONT:.*]]
Builtin.condfail(b)
// CHECK: <label>:[[CONT]]
// CHECK: br i1 %1, label %[[FAIL2:.*]], label %[[CONT:.*]]
Builtin.condfail(c)
// CHECK: <label>:[[CONT]]
// CHECK: ret void
// CHECK: <label>:[[FAIL]]
// CHECK: call void @llvm.trap()
// CHECK: unreachable
// CHECK: <label>:[[FAIL2]]
// CHECK: call void @llvm.trap()
// CHECK: unreachable
}
// CHECK-LABEL: define hidden void @_TF8builtins8testOnce{{.*}}(i8*, i8*) {{.*}} {
// CHECK: [[PRED_PTR:%.*]] = bitcast i8* %0 to [[WORD:i64|i32]]*
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: br i1 [[IS_DONE]], label %[[DONE:.*]], label %[[NOT_DONE:.*]]
// CHECK-objc: [[NOT_DONE]]:
// CHECK: call void @swift_once([[WORD]]* [[PRED_PTR]], i8* %1)
// CHECK-objc: br label %[[DONE]]
// CHECK-objc: [[DONE]]:
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: call void @llvm.assume(i1 [[IS_DONE]])
func testOnce(_ p: Builtin.RawPointer, f: @escaping @convention(thin) () -> ()) {
Builtin.once(p, f)
}
class C {}
struct S {}
@objc class O {}
@objc protocol OP1 {}
@objc protocol OP2 {}
protocol P {}
// CHECK-LABEL: define hidden void @_TF8builtins10canBeClass
func canBeClass<T>(_ f: @escaping (Builtin.Int8) -> (), _: T) {
// CHECK: call void {{%.*}}(i8 1
f(Builtin.canBeClass(O.self))
// CHECK: call void {{%.*}}(i8 1
f(Builtin.canBeClass(OP1.self))
typealias ObjCCompo = OP1 & OP2
// CHECK: call void {{%.*}}(i8 1
f(Builtin.canBeClass(ObjCCompo.self))
// CHECK: call void {{%.*}}(i8 0
f(Builtin.canBeClass(S.self))
// CHECK: call void {{%.*}}(i8 1
f(Builtin.canBeClass(C.self))
// CHECK: call void {{%.*}}(i8 0
f(Builtin.canBeClass(P.self))
typealias MixedCompo = OP1 & P
// CHECK: call void {{%.*}}(i8 0
f(Builtin.canBeClass(MixedCompo.self))
// CHECK: call void {{%.*}}(i8 2
f(Builtin.canBeClass(T.self))
}
// CHECK-LABEL: define hidden void @_TF8builtins15destroyPODArray{{.*}}(i8*, i64)
// CHECK-NOT: loop:
// CHECK: ret void
func destroyPODArray(_ array: Builtin.RawPointer, count: Builtin.Word) {
Builtin.destroyArray(Int.self, array, count)
}
// CHECK-LABEL: define hidden void @_TF8builtins18destroyNonPODArray{{.*}}(i8*, i64) {{.*}} {
// CHECK: iter:
// CHECK: loop:
// CHECK: call {{.*}} @swift_rt_swift_release
// CHECK: br label %iter
func destroyNonPODArray(_ array: Builtin.RawPointer, count: Builtin.Word) {
Builtin.destroyArray(C.self, array, count)
}
// CHECK-LABEL: define hidden void @_TF8builtins15destroyGenArrayurFTBp5countBwx_T_(i8*, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
// CHECK-NOT: loop:
// CHECK: call void %destroyArray
func destroyGenArray<T>(_ array: Builtin.RawPointer, count: Builtin.Word, _: T) {
Builtin.destroyArray(T.self, array, count)
}
// CHECK-LABEL: define hidden void @_TF8builtins12copyPODArray{{.*}}(i8*, i8*, i64)
// CHECK: mul nuw i64 4, %2
// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false)
// CHECK: mul nuw i64 4, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false)
// CHECK: mul nuw i64 4, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false)
func copyPODArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) {
Builtin.copyArray(Int.self, dest, src, count)
Builtin.takeArrayFrontToBack(Int.self, dest, src, count)
Builtin.takeArrayBackToFront(Int.self, dest, src, count)
}
// CHECK-LABEL: define hidden void @_TF8builtins11copyBTArray{{.*}}(i8*, i8*, i64) {{.*}} {
// CHECK: iter:
// CHECK: loop:
// CHECK: call {{.*}} @swift_rt_swift_retain
// CHECK: br label %iter
// CHECK: mul nuw i64 8, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 8, i1 false)
// CHECK: mul nuw i64 8, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 8, i1 false)
func copyBTArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) {
Builtin.copyArray(C.self, dest, src, count)
Builtin.takeArrayFrontToBack(C.self, dest, src, count)
Builtin.takeArrayBackToFront(C.self, dest, src, count)
}
struct W { weak var c: C? }
// CHECK-LABEL: define hidden void @_TF8builtins15copyNonPODArray{{.*}}(i8*, i8*, i64) {{.*}} {
// CHECK: iter:
// CHECK: loop:
// CHECK: swift_weakCopyInit
// CHECK: iter{{.*}}:
// CHECK: loop{{.*}}:
// CHECK: swift_weakTakeInit
// CHECK: iter{{.*}}:
// CHECK: loop{{.*}}:
// CHECK: swift_weakTakeInit
func copyNonPODArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) {
Builtin.copyArray(W.self, dest, src, count)
Builtin.takeArrayFrontToBack(W.self, dest, src, count)
Builtin.takeArrayBackToFront(W.self, dest, src, count)
}
// CHECK-LABEL: define hidden void @_TF8builtins12copyGenArray{{.*}}(i8*, i8*, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
// CHECK-NOT: loop:
// CHECK: call %swift.opaque* %initializeArrayWithCopy
// CHECK-NOT: loop:
// CHECK: call %swift.opaque* %initializeArrayWithTakeFrontToBack
// CHECK-NOT: loop:
// CHECK: call %swift.opaque* %initializeArrayWithTakeBackToFront
func copyGenArray<T>(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word, _: T) {
Builtin.copyArray(T.self, dest, src, count)
Builtin.takeArrayFrontToBack(T.self, dest, src, count)
Builtin.takeArrayBackToFront(T.self, dest, src, count)
}
// CHECK-LABEL: define hidden void @_TF8builtins24conditionallyUnreachableFT_T_
// CHECK-NEXT: entry
// CHECK-NEXT: unreachable
func conditionallyUnreachable() {
Builtin.conditionallyUnreachable()
}
struct Abc {
var value : Builtin.Word
}
// CHECK-LABEL define hidden @_TF8builtins22assumeNonNegative_testFRVS_3AbcBw
func assumeNonNegative_test(_ x: inout Abc) -> Builtin.Word {
// CHECK: load {{.*}}, !range ![[R:[0-9]+]]
return Builtin.assumeNonNegative_Word(x.value)
}
@inline(never)
func return_word(_ x: Builtin.Word) -> Builtin.Word {
return x
}
// CHECK-LABEL define hidden @_TF8builtins23assumeNonNegative_test2FRVS_3AbcBw
func assumeNonNegative_test2(_ x: Builtin.Word) -> Builtin.Word {
// CHECK: call {{.*}}, !range ![[R]]
return Builtin.assumeNonNegative_Word(return_word(x))
}
struct Empty {}
struct Pair { var i: Int, b: Bool }
// CHECK-LABEL: define hidden { i32, i1 } @_TF8builtins15zeroInitializerFT_TVS_5EmptyVS_4Pair_() {{.*}} {
// CHECK: ret { i32, i1 } zeroinitializer
func zeroInitializer() -> (Empty, Pair) {
return (Builtin.zeroInitializer(), Builtin.zeroInitializer())
}
// CHECK-LABEL: define hidden { i32, i1 } @_TF8builtins20zeroInitializerTupleFT_TVS_5EmptyVS_4Pair_() {{.*}} {
// CHECK: ret { i32, i1 } zeroinitializer
func zeroInitializerTuple() -> (Empty, Pair) {
return Builtin.zeroInitializer()
}
// CHECK-LABEL: define hidden void @_TF8builtins20zeroInitializerEmptyFT_T_() {{.*}} {
// CHECK: ret void
func zeroInitializerEmpty() {
return Builtin.zeroInitializer()
}
// ----------------------------------------------------------------------------
// isUnique variants
// ----------------------------------------------------------------------------
// CHECK: define hidden void @_TF8builtins26acceptsBuiltinNativeObjectFRGSqBo_T_([[BUILTIN_NATIVE_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} {
func acceptsBuiltinNativeObject(_ ref: inout Builtin.NativeObject?) {}
// native
// CHECK-LABEL: define hidden i1 @_TF8builtins8isUniqueFRGSqBo_Bi1_({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast [[BUILTIN_NATIVE_OBJECT_TY]]* %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool {
return Builtin.isUnique(&ref)
}
// native nonNull
// CHECK-LABEL: define hidden i1 @_TF8builtins8isUniqueFRBoBi1_(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %0
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %1)
// CHECK-NEXT: ret i1 %2
func isUnique(_ ref: inout Builtin.NativeObject) -> Bool {
return Builtin.isUnique(&ref)
}
// native pinned
// CHECK-LABEL: define hidden i1 @_TF8builtins16isUniqueOrPinnedFRGSqBo_Bi1_({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast [[BUILTIN_NATIVE_OBJECT_TY]]* %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUniqueOrPinned(_ ref: inout Builtin.NativeObject?) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// native pinned nonNull
// CHECK-LABEL: define hidden i1 @_TF8builtins16isUniqueOrPinnedFRBoBi1_(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %0
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native(%swift.refcounted* %1)
// CHECK-NEXT: ret i1 %2
func isUniqueOrPinned(_ ref: inout Builtin.NativeObject) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// CHECK: define hidden void @_TF8builtins27acceptsBuiltinUnknownObjectFRGSqBO_T_([[BUILTIN_UNKNOWN_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} {
func acceptsBuiltinUnknownObject(_ ref: inout Builtin.UnknownObject?) {}
// ObjC
// CHECK-LABEL: define hidden i1 @_TF8builtins8isUniqueFRGSqBO_Bi1_({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast [[BUILTIN_UNKNOWN_OBJECT_TY]]* %0 to %objc_object**
// CHECK-NEXT: load %objc_object*, %objc_object** %1
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC(%objc_object* %2)
// CHECK-NEXT: ret i1 %3
func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool {
return Builtin.isUnique(&ref)
}
// ObjC nonNull
// CHECK-LABEL: define hidden i1 @_TF8builtins8isUniqueFRBOBi1_(%objc_object** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %objc_object*, %objc_object** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC_nonNull(%objc_object* %1)
// CHECK-NEXT: ret i1 %2
func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool {
return Builtin.isUnique(&ref)
}
// ObjC pinned nonNull
// CHECK-LABEL: define hidden i1 @_TF8builtins16isUniqueOrPinnedFRBOBi1_(%objc_object** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %objc_object*, %objc_object** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedOrPinnedNonObjC_nonNull(%objc_object* %1)
// CHECK-NEXT: ret i1 %2
func isUniqueOrPinned(_ ref: inout Builtin.UnknownObject) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// BridgeObject nonNull
// CHECK-LABEL: define hidden i1 @_TF8builtins8isUniqueFRBbBi1_(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.bridge*, %swift.bridge** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC_nonNull_bridgeObject(%swift.bridge* %1)
// CHECK-NEXT: ret i1 %2
func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUnique(&ref)
}
// Bridge pinned nonNull
// CHECK-LABEL: define hidden i1 @_TF8builtins16isUniqueOrPinnedFRBbBi1_(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.bridge*, %swift.bridge** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedOrPinnedNonObjC_nonNull_bridgeObject(%swift.bridge* %1)
// CHECK-NEXT: ret i1 %2
func isUniqueOrPinned(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// BridgeObject nonNull
// CHECK-LABEL: define hidden i1 @_TF8builtins15isUnique_nativeFRBbBi1_(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast %swift.bridge** %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUnique_native(&ref)
}
// Bridge pinned nonNull
// CHECK-LABEL: define hidden i1 @_TF8builtins23isUniqueOrPinned_nativeFRBbBi1_(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast %swift.bridge** %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUniqueOrPinned_native(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUniqueOrPinned_native(&ref)
}
// ImplicitlyUnwrappedOptional argument to isUnique.
// CHECK-LABEL: define hidden i1 @_TF8builtins11isUniqueIUOFRGSqBo_Bi1_(%{{.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted*
// CHECK: ret i1
func isUniqueIUO(_ ref: inout Builtin.NativeObject?) -> Bool {
var iuo : Builtin.NativeObject! = ref
return Builtin.isUnique(&iuo)
}
// CHECK-LABEL: define {{.*}} @{{.*}}generic_ispod_test
func generic_ispod_test<T>(_: T) {
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 18
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[FLAGS:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: [[ISNOTPOD:%.*]] = and i64 [[FLAGS]], 65536
// CHECK-NEXT: [[ISPOD:%.*]] = icmp eq i64 [[ISNOTPOD]], 0
// CHECK-NEXT: store i1 [[ISPOD]], i1* [[S:%.*]]
var s = Builtin.ispod(T.self)
}
// CHECK-LABEL: define {{.*}} @{{.*}}ispod_test
func ispod_test() {
// CHECK: store i1 true, i1*
// CHECK: store i1 false, i1*
var t = Builtin.ispod(Int.self)
var f = Builtin.ispod(Builtin.NativeObject)
}
// CHECK-LABEL: define {{.*}} @{{.*}}generic_unsafeGuaranteed_test
// CHECK: call void @{{.*}}swift_{{.*}}etain({{.*}}* %0)
// CHECK: call void @{{.*}}swift_{{.*}}elease({{.*}}* %0)
// CHECK: ret {{.*}}* %0
func generic_unsafeGuaranteed_test<T: AnyObject>(_ t : T) -> T {
let (g, _) = Builtin.unsafeGuaranteed(t)
return g
}
// CHECK-LABEL: define {{.*}} @{{.*}}unsafeGuaranteed_test
// CHECK: [[LOCAL:%.*]] = alloca %swift.refcounted*
// CHECK: call void @swift_rt_swift_retain(%swift.refcounted* %0)
// CHECK: store %swift.refcounted* %0, %swift.refcounted** [[LOCAL]]
// CHECK: call void @swift_rt_swift_release(%swift.refcounted* %0)
// CHECK: ret %swift.refcounted* %0
func unsafeGuaranteed_test(_ x: Builtin.NativeObject) -> Builtin.NativeObject {
var (g,t) = Builtin.unsafeGuaranteed(x)
Builtin.unsafeGuaranteedEnd(t)
return g
}
// CHECK-LABEL: define {{.*}} @{{.*}}unsafeGuaranteedEnd_test
// CHECK-NEXT: {{.*}}:
// CHECK-NEXT: ret void
func unsafeGuaranteedEnd_test(_ x: Builtin.Int8) {
Builtin.unsafeGuaranteedEnd(x)
}
// CHECK-LABEL: define {{.*}} @{{.*}}atomicload
func atomicload(_ p: Builtin.RawPointer) {
// CHECK: [[A:%.*]] = load atomic i8*, i8** {{%.*}} unordered, align 8
let a: Builtin.RawPointer = Builtin.atomicload_unordered_RawPointer(p)
// CHECK: [[B:%.*]] = load atomic i32, i32* {{%.*}} singlethread monotonic, align 4
let b: Builtin.Int32 = Builtin.atomicload_monotonic_singlethread_Int32(p)
// CHECK: [[C:%.*]] = load atomic volatile i64, i64* {{%.*}} singlethread acquire, align 8
let c: Builtin.Int64 =
Builtin.atomicload_acquire_volatile_singlethread_Int64(p)
// CHECK: [[D0:%.*]] = load atomic volatile i32, i32* {{%.*}} seq_cst, align 4
// CHECK: [[D:%.*]] = bitcast i32 [[D0]] to float
let d: Builtin.FPIEEE32 = Builtin.atomicload_seqcst_volatile_FPIEEE32(p)
// CHECK: store atomic i8* [[A]], i8** {{%.*}} unordered, align 8
Builtin.atomicstore_unordered_RawPointer(p, a)
// CHECK: store atomic i32 [[B]], i32* {{%.*}} singlethread monotonic, align 4
Builtin.atomicstore_monotonic_singlethread_Int32(p, b)
// CHECK: store atomic volatile i64 [[C]], i64* {{%.*}} singlethread release, align 8
Builtin.atomicstore_release_volatile_singlethread_Int64(p, c)
// CHECK: [[D1:%.*]] = bitcast float [[D]] to i32
// CHECK: store atomic volatile i32 [[D1]], i32* {{.*}} seq_cst, align 4
Builtin.atomicstore_seqcst_volatile_FPIEEE32(p, d)
}
// CHECK: ![[R]] = !{i64 0, i64 9223372036854775807}
| apache-2.0 |
overtake/TelegramSwift | Telegram-Mac/WidgetController.swift | 1 | 9654 | //
// WidgetController.swift
// Telegram
//
// Created by Mikhail Filimonov on 06.07.2021.
// Copyright © 2021 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SwiftSignalKit
private final class WidgetNavigationButton : Control {
enum Direction {
case left
case right
}
private let textView = TextView()
private let imageView = ImageView()
private let view = View()
private let visualEffect = VisualEffect()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(visualEffect)
addSubview(view)
view.addSubview(textView)
view.addSubview(imageView)
imageView.isEventLess = true
textView.userInteractionEnabled = false
textView.isSelectable = false
self.layer?.cornerRadius = 16
scaleOnClick = true
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
let theme = theme as! TelegramPresentationTheme
self.background = theme.shouldBlurService ? .clear : theme.chatServiceItemColor
self.visualEffect.bgColor = theme.blurServiceColor
self.visualEffect.isHidden = !theme.shouldBlurService
}
private var direction: Direction?
func setup(_ text: String, image: CGImage, direction: Direction) {
self.direction = direction
let layout = TextViewLayout(.initialize(string: text, color: theme.chatServiceItemTextColor, font: .medium(.text)))
layout.measure(width: .greatestFiniteMagnitude)
textView.update(layout)
imageView.image = image
imageView.sizeToFit()
updateLocalizationAndTheme(theme: theme)
}
override func layout() {
super.layout()
visualEffect.frame = bounds
view.setFrameSize(NSMakeSize(textView.frame.width + 4 + imageView.frame.width, frame.height))
view.center()
if let direction = direction {
switch direction {
case .left:
imageView.centerY(x: 0)
textView.centerY(x: imageView.frame.maxX + 4)
case .right:
textView.centerY(x: 0)
imageView.centerY(x: textView.frame.maxX + 4)
}
}
}
func size() -> NSSize {
return NSMakeSize(28 + textView.frame.width + 4 + imageView.frame.width, 32)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
final class WidgetListView: View {
enum PresentMode {
case immidiate
case leftToRight
case rightToLeft
var animated: Bool {
return self != .immidiate
}
}
private let documentView = View()
private var controller: ViewController?
private var prev: WidgetNavigationButton?
private var next: WidgetNavigationButton?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(documentView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var _next:(()->Void)?
var _prev:(()->Void)?
func present(controller: ViewController, hasNext: Bool, hasPrev: Bool, mode: PresentMode) {
let previous = self.controller
self.controller = controller
let duration: Double = 0.5
if let previous = previous {
if mode.animated {
previous.view._change(opacity: 0, duration: duration, timingFunction: .spring, completion: { [weak previous] completed in
if completed {
previous?.removeFromSuperview()
}
})
} else {
previous.removeFromSuperview()
}
}
documentView.addSubview(controller.view)
controller.view.centerX(y: 0)
controller.view._change(opacity: 1, animated: mode.animated, duration: duration, timingFunction: .spring)
if mode.animated {
let to = controller.view.frame.origin
let from: NSPoint
switch mode {
case .leftToRight:
from = NSMakePoint(to.x - 50, to.y)
case .rightToLeft:
from = NSMakePoint(to.x + 50, to.y)
default:
from = to
}
controller.view.layer?.animatePosition(from: from, to: to, duration: duration, timingFunction: .spring)
}
if hasPrev {
if self.prev == nil {
self.prev = .init(frame: .zero)
if let prev = prev {
addSubview(prev)
}
prev?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
self.prev?.set(handler: { [weak self] _ in
self?._prev?()
}, for: .Click)
}
} else if let prev = self.prev {
prev.userInteractionEnabled = false
performSubviewRemoval(prev, animated: mode.animated)
self.prev = nil
}
if hasNext {
if self.next == nil {
self.next = .init(frame: .zero)
if let next = next {
addSubview(next)
}
next?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
self.next?.set(handler: { [weak self] _ in
self?._next?()
}, for: .Click)
}
} else if let next = self.next {
next.userInteractionEnabled = false
performSubviewRemoval(next, animated: mode.animated)
self.next = nil
}
updateLocalizationAndTheme(theme: theme)
needsLayout = true
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
backgroundColor = .clear
documentView.backgroundColor = .clear
let theme = theme as! TelegramPresentationTheme
if let prev = prev {
prev.setup(strings().emptyChatNavigationPrev, image: theme.emptyChatNavigationPrev, direction: .left)
prev.setFrameSize(prev.size())
}
if let next = next {
next.setup(strings().emptyChatNavigationNext, image: theme.emptyChatNavigationNext, direction: .right)
next.setFrameSize(next.size())
}
needsLayout = true
}
override func layout() {
super.layout()
documentView.frame = NSMakeRect(0, 0, frame.width, 320)
guard let controller = controller else {
return
}
controller.view.centerX(y: 0)
if let prev = prev {
prev.setFrameOrigin(NSMakePoint(controller.frame.minX, documentView.frame.maxY + 10))
}
if let next = next {
next.setFrameOrigin(NSMakePoint(controller.frame.maxX - next.frame.width, documentView.frame.maxY + 10))
}
}
}
final class WidgetController : TelegramGenericViewController<WidgetListView> {
private var controllers:[ViewController] = []
private var selected: Int = 0
override init(_ context: AccountContext) {
super.init(context)
self.bar = .init(height: 0)
}
private func loadController(_ controller: ViewController) {
controller._frameRect = NSMakeRect(0, 0, 320, 320)
controller.bar = .init(height: 0)
controller.loadViewIfNeeded()
}
private func presentSelected(_ mode: WidgetListView.PresentMode) {
let controller = controllers[selected]
loadController(controller)
genericView.present(controller: controller, hasNext: controllers.count - 1 > selected, hasPrev: selected > 0, mode: mode)
}
override func backKeyAction() -> KeyHandlerResult {
if prev() {
return .invoked
}
return .rejected
}
override func nextKeyAction() -> KeyHandlerResult {
if next() {
return .invoked
}
return .rejected
}
@discardableResult private func next() -> Bool {
if selected < controllers.count - 1 {
selected += 1
presentSelected(.rightToLeft)
return true
}
return false
}
@discardableResult private func prev() -> Bool {
if selected > 0 {
selected -= 1
presentSelected(.leftToRight)
return true
}
return false
}
override func viewDidLoad() {
super.viewDidLoad()
controllers.append(WidgetAppearanceController(context))
controllers.append(WidgetRecentPeersController(context))
controllers.append(WidgetStorageController(context))
controllers.append(WidgetStickersController(context))
let current = controllers[selected]
loadController(current)
ready.set(current.ready.get())
genericView.present(controller: current, hasNext: controllers.count - 1 > selected, hasPrev: selected > 0, mode: .immidiate)
genericView._next = { [weak self] in
self?.next()
}
genericView._prev = { [weak self] in
self?.prev()
}
}
deinit {
var bp = 0
bp += 1
}
}
| gpl-2.0 |
vishalvshekkar/ArchivingSwiftStructures | ArchivingSwiftStructures3.playground/Contents.swift | 1 | 3900 | //: Playground - noun: a place where people can play
import UIKit
// MARK: - The structure that is to be archived.
struct Movie {
let name: String
let director: String
let releaseYear: Int
}
// MARK: - The protocol, when implemented by a structure makes the structure archive-able
protocol Dictionariable {
func dictionaryRepresentation() -> NSDictionary
init?(dictionaryRepresentation: NSDictionary?)
}
// MARK: - Implementation of the Dictionariable protocol by Movie struct
extension Movie: Dictionariable {
func dictionaryRepresentation() -> NSDictionary {
let representation: [String: AnyObject] = [
"name": name,
"director": director,
"releaseYear": releaseYear
]
return representation
}
init?(dictionaryRepresentation: NSDictionary?) {
guard let values = dictionaryRepresentation else {return nil}
if let name = values["name"] as? String,
director = values["director"] as? String,
releaseYear = values["releaseYear"] as? Int {
self.name = name
self.director = director
self.releaseYear = releaseYear
} else {
return nil
}
}
}
// MARK: - Methods aiding in archiving and unarchiving the structures
//Single Structure Instances
func extractStructureFromArchive<T: Dictionariable>() -> T? {
guard let encodedDict = NSKeyedUnarchiver.unarchiveObjectWithFile(path()) as? NSDictionary else {return nil}
return T(dictionaryRepresentation: encodedDict)
}
func archiveStructure<T: Dictionariable>(structure: T) {
let encodedValue = structure.dictionaryRepresentation()
NSKeyedArchiver.archiveRootObject(encodedValue, toFile: path())
}
//Multiple Structure Instances
func extractStructuresFromArchive<T: Dictionariable>() -> [T] {
guard let encodedArray = NSKeyedUnarchiver.unarchiveObjectWithFile(path()) as? [AnyObject] else {return []}
return encodedArray.map{$0 as? NSDictionary}.flatMap{T(dictionaryRepresentation: $0)}
}
func archiveStructureInstances<T: Dictionariable>(structures: [T]) {
let encodedValues = structures.map{$0.dictionaryRepresentation()}
NSKeyedArchiver.archiveRootObject(encodedValues, toFile: path())
}
//Metjod to get path to encode stuctures to
func path() -> String {
let documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
let path = documentsPath?.stringByAppendingString("/Movie")
return path!
}
// MARK: - Testing Code
//Single Structure Instances
let movie = Movie(name: "Avatar", director: "James Cameron", releaseYear: 2009)
archiveStructure(movie)
let someMovie: Movie? = extractStructureFromArchive()
someMovie?.director
//Multiple Structure Instances
let movies = [
Movie(name: "Avatar", director: "James Cameron", releaseYear: 2009),
Movie(name: "The Dark Knight", director: "Christopher Nolan", releaseYear: 2008)
]
archiveStructureInstances(movies)
let someArray: [Movie] = extractStructuresFromArchive()
someArray[0].director
//Nested Structures
struct Actor {
let name: String
let firstMovie: Movie
}
extension Actor: Dictionariable {
func dictionaryRepresentation() -> NSDictionary {
let representation: [String: AnyObject] = [
"name": name,
"firstMovie": firstMovie.dictionaryRepresentation(),
]
return representation
}
init?(dictionaryRepresentation: NSDictionary?) {
guard let values = dictionaryRepresentation else {return nil}
if let name = values["name"] as? String,
let someMovie: Movie = extractStructureFromDictionary() {
self.name = name
self.firstMovie = someMovie
} else {
return nil
}
}
} | mit |
glennposadas/gpkit-ios | GPKit/Categories/String+GPKit.swift | 1 | 5454 | //
// String+GPKit.swift
// GPKit
//
// Created by Glenn Posadas on 5/10/17.
// Copyright © 2017 Citus Labs. All rights reserved.
//
import UIKit
public extension String {
/** Format the 24 hour string into 12 hour.
*/
public func format24HrStringTo12Hr() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm:ss"
if let inDate = dateFormatter.date(from: self) {
dateFormatter.dateFormat = "h:mm a"
let outTime = dateFormatter.string(from:inDate)
return "\(outTime)"
}
return self
}
/** Identical to the extension of UITextField's hasValue()
*/
public func hasValidValue() -> Bool {
let whitespaceSet = CharacterSet.whitespaces
if self == "" || self == " " {
return false
}
if self.trimmingCharacters(in: whitespaceSet).isEmpty
|| self.trimmingCharacters(in: whitespaceSet).isEmpty {
return false
}
return true
}
/** Clever function to add/append paths as strings just like in Firebase.
*/
public func append(path: String) -> String {
return "\(self)\(path)"
}
/** Checks if the input email is valid or not
*/
public func isValidEmail() -> Bool {
let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
return emailPredicate.evaluate(with: self)
}
/** Handles string conversion into the usual default format of the MySQL Database.
* @params Self = string of date (e.g. 2017-04-11 13:21:05)
* @return Date = 2017-04-11 13:21:05
*/
public func convertToDate() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.date(from: self)
return date
}
/** Handles date formatiing from String to String
* Input: Self. Ex: "2017-01-11 07:10:36"
* Returns: String: "Jan 2017"
*/
public func convertToReadableDateFormat() -> String {
let dateFormatter = DateFormatter()
let geoDriveDateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
geoDriveDateFormatter.dateFormat = "MMM yyyy"
let date = dateFormatter.date(from: self)
return geoDriveDateFormatter.string(from: date!)
}
/** Extract month from a string
*/
public func extractMonth() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let myDate = dateFormatter.date(from: self) {
dateFormatter.dateFormat = "MM"
let finalMonth = dateFormatter.string(from: myDate)
if let monthInt = Int(finalMonth) {
let monthName = dateFormatter.monthSymbols[monthInt - 1]
return monthName
}
}
return ""
}
/** Extract year from a string
*/
public func extractYear() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let myDate = dateFormatter.date(from: self) {
dateFormatter.dateFormat = "yyyy"
let finalDate = dateFormatter.string(from: myDate)
return finalDate
}
return ""
}
/** Extract readable date string from a string
*/
public func extractReableDashDate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let myDate = dateFormatter.date(from: self) {
dateFormatter.dateFormat = "dd/MM/yyyy"
let finalDate = dateFormatter.string(from: myDate)
return finalDate
}
return ""
}
/** Convert a String (month symbol) to Int String
* January --> "1"
*/
public func convertMonthSymbolToInt() -> String {
return "\(DateFormatter().monthSymbols.index(of: self)! + 1)"
}
/** Generates random alphanumeric string for image key
*/
public static func random(length: Int = 20) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.count))
randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
}
return randomString
}
public var removedFirstCharacter: String {
mutating get {
self.remove(at: self.startIndex)
return self
}
}
}
public class GPKitString {
/** Returns the cool format for Date and Time now.
*/
public class func dateTimeNowString() -> String {
let dateformatter = DateFormatter()
dateformatter.dateStyle = DateFormatter.Style.short
dateformatter.timeStyle = DateFormatter.Style.short
let now = dateformatter.string(from: Date())
return now
}
}
| mit |
matsune/YMCalendar | YMCalendar/Month/Enum/YMScrollDirection.swift | 1 | 247 | //
// YMScrollDirection.swift
// YMCalendar
//
// Created by Yuma Matsune on 2017/02/23.
// Copyright © 2017年 Yuma Matsune. All rights reserved.
//
import Foundation
public enum YMScrollDirection {
case horizontal
case vertical
}
| mit |
nalexn/ViewInspector | Sources/ViewInspector/Modifiers/AccessibilityModifiers.swift | 1 | 17501 | import SwiftUI
// MARK: - Accessibility
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {
func accessibilityLabel() throws -> InspectableView<ViewType.Text> {
let text: Text
let call = "accessibilityLabel"
if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) {
text = try v3AccessibilityElement(
path: "some|text", type: Text.self,
call: call, { $0.accessibilityLabel("") })
} else if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
text = try v3AccessibilityElement(
type: Text.self, call: call, { $0.accessibilityLabel("") })
} else {
text = try v2AccessibilityElement("LabelKey", type: Text.self, call: call)
}
let medium = content.medium.resettingViewModifiers()
return try .init(try Inspector.unwrap(content: Content(text, medium: medium)), parent: self)
}
func accessibilityValue() throws -> InspectableView<ViewType.Text> {
let text: Text
let call = "accessibilityValue"
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
text = try v3AccessibilityElement(
path: "some|description|some", type: Text.self,
call: call, { $0.accessibilityValue("") })
} else {
text = try v2AccessibilityElement(
"TypedValueKey", path: "value|some|description|some", type: Text.self, call: call)
}
let medium = content.medium.resettingViewModifiers()
return try .init(try Inspector.unwrap(content: Content(text, medium: medium)), parent: self)
}
func accessibilityHint() throws -> InspectableView<ViewType.Text> {
let text: Text
let call = "accessibilityHint"
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
text = try v3AccessibilityElement(
type: Text.self, call: call, { $0.accessibilityHint("") })
} else {
text = try v2AccessibilityElement("HintKey", type: Text.self, call: call)
}
let medium = content.medium.resettingViewModifiers()
return try .init(try Inspector.unwrap(content: Content(text, medium: medium)), parent: self)
}
func accessibilityHidden() throws -> Bool {
let call = "accessibilityHidden"
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
let value = try v3AccessibilityElement(
path: "value|rawValue", type: UInt32.self,
call: call, { $0.accessibilityHidden(true) })
return value != 0
} else {
let visibility = try v2AccessibilityElement(
"VisibilityKey", path: "value", type: (Any?).self, call: call)
switch visibility {
case let .some(value):
return String(describing: value) == "hidden"
case .none:
return false
}
}
}
func accessibilityIdentifier() throws -> String {
let call = "accessibilityIdentifier"
if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) {
return try v3AccessibilityElement(
path: "some|rawValue", type: String.self,
call: call, { $0.accessibilityIdentifier("") })
} else if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
return try v3AccessibilityElement(
type: String.self, call: call, { $0.accessibilityIdentifier("") })
} else {
return try v2AccessibilityElement("IdentifierKey", type: String.self, call: call)
}
}
func accessibilitySortPriority() throws -> Double {
let call = "accessibilitySortPriority"
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
return try v3AccessibilityElement(
type: Double.self, call: call, { $0.accessibilitySortPriority(0) })
} else {
return try v2AccessibilityElement("SortPriorityKey", type: Double.self, call: call)
}
}
@available(iOS, deprecated, introduced: 13.0)
@available(macOS, deprecated, introduced: 10.15)
@available(tvOS, deprecated, introduced: 13.0)
@available(watchOS, deprecated, introduced: 6)
func accessibilitySelectionIdentifier() throws -> AnyHashable {
return try v2AccessibilityElement(
"SelectionIdentifierKey", type: AnyHashable.self,
call: "accessibility(selectionIdentifier:)")
}
func accessibilityActivationPoint() throws -> UnitPoint {
if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) {
return try v3AccessibilityElement(
path: "some|activate|some|unitPoint", type: UnitPoint.self,
call: "accessibilityIdentifier", { $0.accessibilityActivationPoint(.center) })
} else if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
return try v3AccessibilityElement(
path: "some|unitPoint", type: UnitPoint.self,
call: "accessibilityIdentifier", { $0.accessibilityActivationPoint(.center) })
} else {
return try v2AccessibilityElement(
"ActivationPointKey", path: "value|some|unitPoint",
type: UnitPoint.self, call: "accessibility(activationPoint:)")
}
}
func callAccessibilityAction<S>(_ named: S) throws where S: StringProtocol {
try callAccessibilityAction(AccessibilityActionKind(named: Text(named)))
}
func callAccessibilityAction(_ kind: AccessibilityActionKind) throws {
let shortName: String = {
if let name = try? kind.name().string() {
return "named: \"\(name)\""
}
return "." + String(describing: kind)
.components(separatedBy: CharacterSet(charactersIn: ".)"))
.filter { $0.count > 0 }.last!
}()
let call = "accessibilityAction(\(shortName))"
typealias Callback = (()) -> Void
let callback: Callback
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
callback = try v3AccessibilityAction(kind: kind, type: Callback.self, call: call)
} else {
callback = try v2AccessibilityAction(kind: kind, type: Callback.self, call: call)
}
callback(())
}
func callAccessibilityAdjustableAction(_ direction: AccessibilityAdjustmentDirection = .increment) throws {
typealias Callback = (AccessibilityAdjustmentDirection) -> Void
let callback: Callback
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
callback = try v3AccessibilityAction(
name: "AccessibilityAdjustableAction",
type: Callback.self,
call: "accessibilityAdjustableAction")
} else {
callback = try v2AccessibilityAction(
name: "AccessibilityAdjustableAction()",
type: Callback.self,
call: "accessibilityAdjustableAction")
}
callback(direction)
}
func callAccessibilityScrollAction(_ edge: Edge) throws {
typealias Callback = (Edge) -> Void
let callback: Callback
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
callback = try v3AccessibilityAction(
name: "AccessibilityScrollAction",
type: Callback.self,
call: "accessibilityScrollAction")
} else {
callback = try v2AccessibilityAction(
name: "AccessibilityScrollAction()",
type: Callback.self,
call: "accessibilityScrollAction")
}
callback(edge)
}
}
// MARK: - Private
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private extension AccessibilityActionKind {
func name() throws -> InspectableView<ViewType.Text> {
let view: Any = try {
if let view = try? Inspector.attribute(path: "kind|named", value: self) {
return view
}
return try Inspector.attribute(path: "kind|custom", value: self)
}()
return try .init(Content(view), parent: nil, index: nil)
}
func isEqual(to other: AccessibilityActionKind) -> Bool {
if let lhsName = try? self.name().string(),
let rhsName = try? other.name().string() {
return lhsName == rhsName
}
return self == other
}
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
private struct AccessibilityProperty {
let keyPointerValue: UInt64
let value: Any
init(property: Any) throws {
self.keyPointerValue = try Inspector.attribute(
path: "super|key|rawValue|pointerValue", value: property, type: UInt64.self)
self.value = try Inspector.attribute(path: "super|value", value: property)
}
init(key: UInt64, value: Any) throws {
self.keyPointerValue = key
self.value = try Inspector.attribute(path: "typedValue", value: value)
}
static var noisePointerValues: Set<UInt64> = {
let view1 = EmptyView().accessibility(label: Text(""))
let view2 = EmptyView().accessibility(hint: Text(""))
do {
let props1 = try view1.inspect()
.v3v4AccessibilityProperties(call: "")
.map { $0.keyPointerValue }
let props2 = try view2.inspect()
.v3v4AccessibilityProperties(call: "")
.map { $0.keyPointerValue }
return Set(props1).intersection(Set(props2))
} catch { return .init() }
}()
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
private extension InspectableView {
func v3AccessibilityElement<V, T>(
path: String? = nil, type: T.Type, call: String, _ reference: (EmptyView) -> V
) throws -> T where V: SwiftUI.View {
let noiseValues = AccessibilityProperty.noisePointerValues
guard let referenceValue = try reference(EmptyView()).inspect()
.v3v4AccessibilityProperties(call: call)
.map({ $0.keyPointerValue })
.first(where: { !noiseValues.contains($0) }),
let property = try v3v4AccessibilityProperties(call: call)
.first(where: { $0.keyPointerValue == referenceValue })
else {
throw InspectionError
.modifierNotFound(parent: Inspector.typeName(value: content.view),
modifier: call, index: 0)
}
if let path = path {
return try Inspector.attribute(path: path, value: property.value, type: T.self)
}
return try Inspector.cast(value: property.value, type: T.self)
}
func v3AccessibilityAction<T>(kind: AccessibilityActionKind, type: T.Type, call: String) throws -> T {
return try v3AccessibilityAction(trait: { action in
try Inspector.attribute(
path: "action|kind", value: action, type: AccessibilityActionKind.self)
.isEqual(to: kind)
}, type: type, call: call)
}
func v3AccessibilityAction<T>(name: String, type: T.Type, call: String) throws -> T {
return try v3AccessibilityAction(trait: { action in
Inspector.typeName(value: action).contains(name)
}, type: type, call: call)
}
func v3AccessibilityAction<T>(trait: (Any) throws -> Bool, type: T.Type, call: String) throws -> T {
let actions = try v3AccessibilityActions(call: call)
guard let action = actions.first(where: { (try? trait($0)) == true }) else {
throw InspectionError
.modifierNotFound(parent: Inspector.typeName(value: content.view),
modifier: call, index: 0)
}
if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) {
throw InspectionError.notSupported(
"""
Accessibility actions are currently unavailable for \
inspection on iOS 16. Situation may change with a minor \
OS version update. In the meanwhile, please add XCTSkip \
for iOS 16 and use an earlier OS version for testing.
""")
}
return try Inspector.attribute(label: "handler", value: action, type: T.self)
}
func v3AccessibilityActions(call: String) throws -> [Any] {
let noiseValues = AccessibilityProperty.noisePointerValues
guard let referenceValue = try EmptyView().accessibilityAction(.default, { })
.inspect()
.v3v4AccessibilityProperties(call: call)
.map({ $0.keyPointerValue })
.first(where: { !noiseValues.contains($0) })
else {
throw InspectionError
.modifierNotFound(parent: Inspector.typeName(value: content.view),
modifier: call, index: 0)
}
return try v3v4AccessibilityProperties(call: call)
.filter({ $0.keyPointerValue == referenceValue })
.compactMap { $0.value as? [Any] }
.flatMap { $0 }
.map { try Inspector.attribute(path: "base|base", value: $0) }
}
func v3v4AccessibilityProperties(call: String) throws -> [AccessibilityProperty] {
if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) {
return try modifierAttribute(
modifierName: "AccessibilityAttachmentModifier",
path: "modifier|storage|value|properties|storage",
type: AccessibilityKeyValues.self, call: call)
.accessibilityKeyValues()
.map { try AccessibilityProperty(key: $0.key, value: $0.value) }
} else {
return try modifierAttribute(
modifierName: "AccessibilityAttachmentModifier",
path: "modifier|storage|propertiesComponent",
type: [Any].self, call: call)
.map { try AccessibilityProperty(property: $0) }
}
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
protocol AccessibilityKeyValues {
func accessibilityKeyValues() throws -> [(key: UInt64, value: Any)]
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension Dictionary: AccessibilityKeyValues {
func accessibilityKeyValues() throws -> [(key: UInt64, value: Any)] {
return try self.keys.compactMap { key -> (key: UInt64, value: Any)? in
guard let value = self[key] else { return nil }
let keyPointerValue = try Inspector.attribute(
path: "rawValue|pointerValue", value: key, type: UInt64.self)
return (key: keyPointerValue, value: value as Any)
}
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private extension InspectableView {
func v2AccessibilityElement<T>(_ name: String, path: String = "value|some",
type: T.Type, call: String) throws -> T {
let item = try modifierAttribute(
modifierName: "AccessibilityAttachmentModifier",
path: "modifier|attachment|some|properties|plist|elements|some",
type: Any.self, call: call)
guard let attribute = v2LookupAttributeWithName(name, item: item),
let value = try? Inspector.attribute(path: path, value: attribute) as? T else {
throw InspectionError.modifierNotFound(parent:
Inspector.typeName(value: content.view), modifier: call, index: 0)
}
return value
}
func v2LookupAttributeWithName(_ name: String, item: Any) -> Any? {
if Inspector.typeName(value: item).contains(name) {
return item
}
if let nextItem = try? Inspector.attribute(path: "super|after|some", value: item) {
return v2LookupAttributeWithName(name, item: nextItem)
}
return nil
}
func v2AccessibilityAction<T>(kind: AccessibilityActionKind, type: T.Type, call: String) throws -> T {
return try v2AccessibilityAction(type: type, call: call, trait: { handler in
try Inspector.attribute(path: "box|action|kind", value: handler, type: AccessibilityActionKind.self)
.isEqual(to: kind)
})
}
func v2AccessibilityAction<T>(name: String, type: T.Type, call: String) throws -> T {
return try v2AccessibilityAction(type: type, call: call, trait: { handler in
let actionName = try Inspector.attribute(path: "box|action", value: handler)
return name == String(describing: actionName)
})
}
func v2AccessibilityAction<T>(type: T.Type, call: String, trait: (Any) throws -> Bool) throws -> T {
let actionHandlers = try v2AccessibilityElement(
"ActionsKey", path: "value",
type: [Any].self, call: call)
guard let handler = actionHandlers.first(where: { (try? trait($0)) == true }),
let callback = try? Inspector.attribute(path: "box|handler", value: handler) as? T
else {
throw InspectionError.modifierNotFound(parent:
Inspector.typeName(value: content.view), modifier: call, index: 0)
}
return callback
}
}
| mit |
lxk2000/TestSample | TestSample/TestSample/ViewController.swift | 1 | 502 | //
// ViewController.swift
// TestSample
//
// Created by cst2016 on 2016-03-25.
// Copyright © 2016 cst2016. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 |
TouchInstinct/LeadKit | TISwiftUICore/Sources/Alerts/Protocols/SwiftUIAlertContext.swift | 1 | 1727 | //
// Copyright (c) 2022 Touch Instinct
//
// 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 TISwiftUtils
import TIUIKitCore
import UIKit
/// A SwiftUI context from where the alert can be presented.
public protocol SwiftUIAlertContext: AlertPresentationContext {
/// A view controller that represents a context from which the alert will be shown.
var presentingViewController: UIViewController { get set }
}
public extension SwiftUIAlertContext {
func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: VoidClosure?) {
presentingViewController.present(viewControllerToPresent, animated: flag, completion: completion)
}
}
| apache-2.0 |
Skyricher/DYZB | DYZBTV/DYZBTV/Classes/Tools/Extension/UIColor+Extension.swift | 1 | 336 | //
// UIColor+Extension.swift
// DYZBTV
//
// Created by 鲁俊 on 2016/9/23.
// Copyright © 2016年 amao24.com. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat) {
self.init(red: r / 255.0, green: g / 255.0 , blue: b / 255.0, alpha: 1.0)
}
}
| mit |
tjw/swift | stdlib/public/core/SipHash.swift | 1 | 4886 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// This file implements SipHash-2-4 and SipHash-1-3
/// (https://131002.net/siphash/).
///
/// This file is based on the reference C implementation, which was released
/// to public domain by:
///
/// * Jean-Philippe Aumasson <jeanphilippe.aumasson@gmail.com>
/// * Daniel J. Bernstein <djb@cr.yp.to>
//===----------------------------------------------------------------------===//
private struct _SipHashState {
// "somepseudorandomlygeneratedbytes"
fileprivate var v0: UInt64 = 0x736f6d6570736575
fileprivate var v1: UInt64 = 0x646f72616e646f6d
fileprivate var v2: UInt64 = 0x6c7967656e657261
fileprivate var v3: UInt64 = 0x7465646279746573
@inline(__always)
fileprivate init(seed: (UInt64, UInt64)) {
v3 ^= seed.1
v2 ^= seed.0
v1 ^= seed.1
v0 ^= seed.0
}
@inline(__always)
fileprivate
static func _rotateLeft(_ x: UInt64, by amount: UInt64) -> UInt64 {
return (x &<< amount) | (x &>> (64 - amount))
}
@inline(__always)
fileprivate mutating func _round() {
v0 = v0 &+ v1
v1 = _SipHashState._rotateLeft(v1, by: 13)
v1 ^= v0
v0 = _SipHashState._rotateLeft(v0, by: 32)
v2 = v2 &+ v3
v3 = _SipHashState._rotateLeft(v3, by: 16)
v3 ^= v2
v0 = v0 &+ v3
v3 = _SipHashState._rotateLeft(v3, by: 21)
v3 ^= v0
v2 = v2 &+ v1
v1 = _SipHashState._rotateLeft(v1, by: 17)
v1 ^= v2
v2 = _SipHashState._rotateLeft(v2, by: 32)
}
@inline(__always)
fileprivate func _extract() -> UInt64 {
return v0 ^ v1 ^ v2 ^ v3
}
}
internal struct _SipHash13Core: _HasherCore {
private var _state: _SipHashState
@inline(__always)
internal init(seed: (UInt64, UInt64)) {
_state = _SipHashState(seed: seed)
}
@inline(__always)
internal mutating func compress(_ m: UInt64) {
_state.v3 ^= m
_state._round()
_state.v0 ^= m
}
@inline(__always)
internal mutating func finalize(tailAndByteCount: UInt64) -> UInt64 {
compress(tailAndByteCount)
_state.v2 ^= 0xff
for _ in 0..<3 {
_state._round()
}
return _state._extract()
}
}
internal struct _SipHash24Core: _HasherCore {
private var _state: _SipHashState
@inline(__always)
internal init(seed: (UInt64, UInt64)) {
_state = _SipHashState(seed: seed)
}
@inline(__always)
internal mutating func compress(_ m: UInt64) {
_state.v3 ^= m
_state._round()
_state._round()
_state.v0 ^= m
}
@inline(__always)
internal mutating func finalize(tailAndByteCount: UInt64) -> UInt64 {
compress(tailAndByteCount)
_state.v2 ^= 0xff
for _ in 0..<4 {
_state._round()
}
return _state._extract()
}
}
// FIXME: This type only exists to facilitate testing.
public // @testable
struct _SipHash13 {
internal typealias Core = _BufferingHasher<_SipHash13Core>
internal var _core: Core
public init(seed: (UInt64, UInt64)) { _core = Core(seed: seed) }
public mutating func _combine(_ v: UInt) { _core.combine(v) }
public mutating func _combine(_ v: UInt64) { _core.combine(v) }
public mutating func _combine(_ v: UInt32) { _core.combine(v) }
public mutating func _combine(_ v: UInt16) { _core.combine(v) }
public mutating func _combine(_ v: UInt8) { _core.combine(v) }
public mutating func combine(bytes v: UInt64, count: Int) {
_core.combine(bytes: v, count: count)
}
public mutating func combine(bytes: UnsafeRawBufferPointer) {
_core.combine(bytes: bytes)
}
public mutating func finalize() -> UInt64 { return _core.finalize() }
}
// FIXME: This type only exists to facilitate testing.
public // @testable
struct _SipHash24 {
internal typealias Core = _BufferingHasher<_SipHash24Core>
internal var _core: Core
public init(seed: (UInt64, UInt64)) { _core = Core(seed: seed) }
public mutating func _combine(_ v: UInt) { _core.combine(v) }
public mutating func _combine(_ v: UInt64) { _core.combine(v) }
public mutating func _combine(_ v: UInt32) { _core.combine(v) }
public mutating func _combine(_ v: UInt16) { _core.combine(v) }
public mutating func _combine(_ v: UInt8) { _core.combine(v) }
public mutating func combine(bytes v: UInt64, count: Int) {
_core.combine(bytes: v, count: count)
}
public mutating func combine(bytes: UnsafeRawBufferPointer) {
_core.combine(bytes: bytes)
}
public mutating func finalize() -> UInt64 { return _core.finalize() }
}
| apache-2.0 |
FRA7/FJWeibo | FJWeibo/AppDelegate.swift | 1 | 1831 | //
// AppDelegate.swift
// FJWeibo
//
// Created by Francis on 16/2/26.
// Copyright © 2016年 FRAJ. All rights reserved.
//
import UIKit
import AFNetworking
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var defaultViewController: UIViewController{
let isLogin = UserAccountViewModel.shareInstance.isLogin
return isLogin ? WelcomeViewController() :UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()!
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// // 0.设置AFN属性
// let cache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
// NSURLCache.setSharedURLCache(cache)
// AFNetworkActivityIndicatorManager.sharedManager().enabled = true
//设置导航条和工具条全局属性
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
UITabBar.appearance().tintColor = UIColor.orangeColor()
//1.创建窗口
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
//2.设置窗口根视图
// window?.rootViewController = MainViewController()
window?.rootViewController = defaultViewController
//3.显示窗口
window?.makeKeyAndVisible()
return true
}
}
//MARK: - 自定义Log
func FJLog<T>(message : T, file : String = __FILE__, lineNum : Int = __LINE__) {
#if DEBUG
let filePath = (file as NSString).lastPathComponent
print("\(filePath)-[\(lineNum)]:\(message)")
#endif
}
| mit |
lolgear/JWT | Example/JWTDesktopSwift/JWTDesktopSwift/ViewController+Model.swift | 2 | 2551 | //
// ViewController+Model.swift
// JWTDesktopSwift
//
// Created by Lobanov Dmitry on 30.10.2017.
// Copyright © 2017 JWTIO. All rights reserved.
//
import Foundation
import JWT
import JWTDesktopSwiftToolkit
extension ViewController {
class Model {
var appearance: TokenTextAppearance = .init()
var decoder: TokenDecoder = .init()
var signatureValidation: SignatureValidationType = .unknown
}
enum DataSeedType {
case hs256
case rs256
struct DataSeed {
var algorithmName: String
var secret: String
var token: String
}
var dataSeed: DataSeed {
switch self {
case .hs256:
let algorithmName = JWTAlgorithmNameHS256
let secret = "secret"
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
return .init(algorithmName: algorithmName, secret: secret, token: token)
case .rs256:
let algorithmName = JWTAlgorithmNameRS256
let secret = "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoPryo3IisfK3a028bwgso/CW5kB84mk6Y7rO76FxJRTWnOAla0Uf0OpIID7go4Qck66yT4/uPpiOQIR0oW0plTekkDP75EG3d/2mtzhiCtELV4F1r9b/InCN5dYYK8USNkKXgjbeVyatdUvCtokz10/ibNZ9qikgKf58qXnn2anGvpE6ded5FOUEukOjr7KSAfD0KDNYWgZcG7HZBxn/3N7ND9D0ATu2vxlJsNGOkH6WL1EmObo/QygBXzuZm5o0N0W15EXpWVbl4Ye7xqPnvc1i2DTKxNUcyhXfDbLw1ee2d9T/WU5895Ko2bQ/O/zPwUSobM3m+fPMW8kp5914kwIDAQAB-----END PUBLIC KEY-----"
let token = "eyJraWQiOiJqd3RfdWF0X2tleXMiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI1MDAxIiwiaXNzIjoiQ0xNIiwiZXhwIjoxNTA4MjQ5NTU3LCJqdGkiOiI2MjcyM2E4Yi0zOTZmLTQxYmYtOTljMi02NWRkMzk2MDNiNjQifQ.Cej8RJ6e2HEU27rh_TyHZBoMI1jErmhOfSFY4SRzRoijSP628hM82XxjDX24HsKqIsK1xeeGI1yg1bed4RPhnmDGt4jAY73nqguZ1oqZ2DTcfZ5olxCXyLLaytl2XH7-62M_mFUcGj7I2mwts1DQkHWnFky2i4uJXlksHFkUg2xZoGEjVHo0bxCxgQ5yQiOpxC5VodN5rAPM3A5yMG6EijOp-dvUThjoJ4RFTGKozw_x_Qg6RLGDusNcmLIMbHasTsyZAZle6RFkwO0Sij1k6z6_xssbOl-Q57m7CeYgVHMORdzy4Smkmh-0gzeiLsGbCL4fhgdHydpIFajW-eOXMw"
return .init(algorithmName: algorithmName, secret: secret, token: token)
}
}
}
}
// JWT
extension ViewController.Model {
var availableAlgorithms: [JWTAlgorithm] {
JWTAlgorithmFactory.algorithms
}
var availableAlgorithmsNames: [String] {
self.availableAlgorithms.map(\.name)
}
}
| mit |
pNre/Kingfisher | Sources/ImageDownloader.swift | 11 | 30301 | //
// ImageDownloader.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2018 Wei Wang <onevcat@gmail.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.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
/// Progress update block of downloader.
public typealias ImageDownloaderProgressBlock = DownloadProgressBlock
/// Completion block of downloader.
public typealias ImageDownloaderCompletionHandler = ((_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> Void)
/// Download task.
public struct RetrieveImageDownloadTask {
let internalTask: URLSessionDataTask
/// Downloader by which this task is initialized.
public private(set) weak var ownerDownloader: ImageDownloader?
/// Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error.
/// If you want to cancel all downloading tasks, call `cancelAll()` of `ImageDownloader` instance.
public func cancel() {
ownerDownloader?.cancel(self)
}
/// The original request URL of this download task.
public var url: URL? {
return internalTask.originalRequest?.url
}
/// The relative priority of this download task.
/// It represents the `priority` property of the internal `NSURLSessionTask` of this download task.
/// The value for it is between 0.0~1.0. Default priority is value of 0.5.
/// See documentation on `priority` of `NSURLSessionTask` for more about it.
public var priority: Float {
get {
return internalTask.priority
}
set {
internalTask.priority = newValue
}
}
}
///The code of errors which `ImageDownloader` might encountered.
public enum KingfisherError: Int {
/// badData: The downloaded data is not an image or the data is corrupted.
case badData = 10000
/// notModified: The remote server responded a 304 code. No image data downloaded.
case notModified = 10001
/// The HTTP status code in response is not valid. If an invalid
/// code error received, you could check the value under `KingfisherErrorStatusCodeKey`
/// in `userInfo` to see the code.
case invalidStatusCode = 10002
/// notCached: The image requested is not in cache but .onlyFromCache is activated.
case notCached = 10003
/// The URL is invalid.
case invalidURL = 20000
/// The downloading task is cancelled before started.
case downloadCancelledBeforeStarting = 30000
}
/// Key will be used in the `userInfo` of `.invalidStatusCode`
public let KingfisherErrorStatusCodeKey = "statusCode"
/// Protocol of `ImageDownloader`.
public protocol ImageDownloaderDelegate: AnyObject {
/**
Called when the `ImageDownloader` object will start downloading an image from specified URL.
- parameter downloader: The `ImageDownloader` object finishes the downloading.
- parameter url: URL of the original request URL.
- parameter response: The request object for the download process.
*/
func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?)
/**
Called when the `ImageDownloader` completes a downloading request with success or failure.
- parameter downloader: The `ImageDownloader` object finishes the downloading.
- parameter url: URL of the original request URL.
- parameter response: The response object of the downloading process.
- parameter error: The error in case of failure.
*/
func imageDownloader(_ downloader: ImageDownloader, didFinishDownloadingImageForURL url: URL, with response: URLResponse?, error: Error?)
/**
Called when the `ImageDownloader` object successfully downloaded an image from specified URL.
- parameter downloader: The `ImageDownloader` object finishes the downloading.
- parameter image: Downloaded image.
- parameter url: URL of the original request URL.
- parameter response: The response object of the downloading process.
*/
func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?)
/**
Check if a received HTTP status code is valid or not.
By default, a status code between 200 to 400 (excluded) is considered as valid.
If an invalid code is received, the downloader will raise an .invalidStatusCode error.
It has a `userInfo` which includes this statusCode and localizedString error message.
- parameter code: The received HTTP status code.
- parameter downloader: The `ImageDownloader` object asking for validate status code.
- returns: Whether this HTTP status code is valid or not.
- Note: If the default 200 to 400 valid code does not suit your need,
you can implement this method to change that behavior.
*/
func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool
/**
Called when the `ImageDownloader` object successfully downloaded image data from specified URL.
- parameter downloader: The `ImageDownloader` object finishes data downloading.
- parameter data: Downloaded data.
- parameter url: URL of the original request URL.
- returns: The data from which Kingfisher should use to create an image.
- Note: This callback can be used to preprocess raw image data
before creation of UIImage instance (i.e. decrypting or verification).
*/
func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data?
}
extension ImageDownloaderDelegate {
public func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?) {}
public func imageDownloader(_ downloader: ImageDownloader, didFinishDownloadingImageForURL url: URL, with response: URLResponse?, error: Error?) {}
public func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) {}
public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool {
return (200..<400).contains(code)
}
public func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data? {
return data
}
}
/// Protocol indicates that an authentication challenge could be handled.
public protocol AuthenticationChallengeResponsable: AnyObject {
/**
Called when an session level authentication challenge is received.
This method provide a chance to handle and response to the authentication challenge before downloading could start.
- parameter downloader: The downloader which receives this challenge.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call.
- Note: This method is a forward from `URLSessionDelegate.urlSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `URLSessionDelegate`.
*/
func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
/**
Called when an session level authentication challenge is received.
This method provide a chance to handle and response to the authentication challenge before downloading could start.
- parameter downloader: The downloader which receives this challenge.
- parameter task: The task whose request requires authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call.
- Note: This method is a forward from `URLSessionTaskDelegate.urlSession(:task:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `URLSessionTaskDelegate`.
*/
func downloader(_ downloader: ImageDownloader, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
}
extension AuthenticationChallengeResponsable {
func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) {
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, credential)
return
}
}
completionHandler(.performDefaultHandling, nil)
}
func downloader(_ downloader: ImageDownloader, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(.performDefaultHandling, nil)
}
}
/// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server.
open class ImageDownloader {
class ImageFetchLoad {
var contents = [(callback: CallbackPair, options: KingfisherOptionsInfo)]()
var responseData = NSMutableData()
var downloadTaskCount = 0
var downloadTask: RetrieveImageDownloadTask?
var cancelSemaphore: DispatchSemaphore?
}
// MARK: - Public property
/// The duration before the download is timeout. Default is 15 seconds.
open var downloadTimeout: TimeInterval = 15.0
/// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored.
/// You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`.
/// If `authenticationChallengeResponder` is set, this property will be ignored and the implementation of `authenticationChallengeResponder` will be used instead.
open var trustedHosts: Set<String>?
/// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used.
/// You could change the configuration before a downloading task starts. A configuration without persistent storage for caches is requested for downloader working correctly.
open var sessionConfiguration = URLSessionConfiguration.ephemeral {
didSet {
session?.invalidateAndCancel()
session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: nil)
}
}
/// Whether the download requests should use pipline or not. Default is false.
open var requestsUsePipelining = false
fileprivate let sessionHandler: ImageDownloaderSessionHandler
fileprivate var session: URLSession?
/// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more.
open weak var delegate: ImageDownloaderDelegate?
/// A responder for authentication challenge.
/// Downloader will forward the received authentication challenge for the downloading session to this responder.
open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable?
// MARK: - Internal property
let barrierQueue: DispatchQueue
let processQueue: DispatchQueue
let cancelQueue: DispatchQueue
typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?)
var fetchLoads = [URL: ImageFetchLoad]()
// MARK: - Public method
/// The default downloader.
public static let `default` = ImageDownloader(name: "default")
/**
Init a downloader with name.
- parameter name: The name for the downloader. It should not be empty.
*/
public init(name: String) {
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.")
}
barrierQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Barrier.\(name)", attributes: .concurrent)
processQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process.\(name)", attributes: .concurrent)
cancelQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Cancel.\(name)")
sessionHandler = ImageDownloaderSessionHandler(name: name)
// Provide a default implement for challenge responder.
authenticationChallengeResponder = sessionHandler
session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: .main)
}
deinit {
session?.invalidateAndCancel()
}
func fetchLoad(for url: URL) -> ImageFetchLoad? {
var fetchLoad: ImageFetchLoad?
barrierQueue.sync(flags: .barrier) { fetchLoad = fetchLoads[url] }
return fetchLoad
}
/**
Download an image with a URL and option.
- parameter url: Target URL.
- parameter retrieveImageTask: The task to cooperate with cache. Pass `nil` if you are not trying to use downloader and cache.
- parameter options: The options could control download behavior. See `KingfisherOptionsInfo`.
- parameter progressBlock: Called when the download progress updated.
- parameter completionHandler: Called when the download progress finishes.
- returns: A downloading task. You could call `cancel` on it to stop the downloading process.
*/
@discardableResult
open func downloadImage(with url: URL,
retrieveImageTask: RetrieveImageTask? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: ImageDownloaderProgressBlock? = nil,
completionHandler: ImageDownloaderCompletionHandler? = nil) -> RetrieveImageDownloadTask?
{
if let retrieveImageTask = retrieveImageTask, retrieveImageTask.cancelledBeforeDownloadStarting {
completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil)
return nil
}
let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout
// We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL.
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout)
request.httpShouldUsePipelining = requestsUsePipelining
if let modifier = options?.modifier {
guard let r = modifier.modified(for: request) else {
completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil)
return nil
}
request = r
}
// There is a possibility that request modifier changed the url to `nil` or empty.
guard let url = request.url, !url.absoluteString.isEmpty else {
completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidURL.rawValue, userInfo: nil), nil, nil)
return nil
}
var downloadTask: RetrieveImageDownloadTask?
setup(progressBlock: progressBlock, with: completionHandler, for: url, options: options) {(session, fetchLoad) -> Void in
if fetchLoad.downloadTask == nil {
let dataTask = session.dataTask(with: request)
fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self)
dataTask.priority = options?.downloadPriority ?? URLSessionTask.defaultPriority
self.delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request)
dataTask.resume()
// Hold self while the task is executing.
self.sessionHandler.downloadHolder = self
}
fetchLoad.downloadTaskCount += 1
downloadTask = fetchLoad.downloadTask
retrieveImageTask?.downloadTask = downloadTask
}
return downloadTask
}
}
// MARK: - Download method
extension ImageDownloader {
// A single key may have multiple callbacks. Only download once.
func setup(progressBlock: ImageDownloaderProgressBlock?, with completionHandler: ImageDownloaderCompletionHandler?, for url: URL, options: KingfisherOptionsInfo?, started: @escaping ((URLSession, ImageFetchLoad) -> Void)) {
func prepareFetchLoad() {
barrierQueue.sync(flags: .barrier) {
let loadObjectForURL = fetchLoads[url] ?? ImageFetchLoad()
let callbackPair = (progressBlock: progressBlock, completionHandler: completionHandler)
loadObjectForURL.contents.append((callbackPair, options ?? KingfisherEmptyOptionsInfo))
fetchLoads[url] = loadObjectForURL
if let session = session {
started(session, loadObjectForURL)
}
}
}
if let fetchLoad = fetchLoad(for: url), fetchLoad.downloadTaskCount == 0 {
if fetchLoad.cancelSemaphore == nil {
fetchLoad.cancelSemaphore = DispatchSemaphore(value: 0)
}
cancelQueue.async {
_ = fetchLoad.cancelSemaphore?.wait(timeout: .distantFuture)
fetchLoad.cancelSemaphore = nil
prepareFetchLoad()
}
} else {
prepareFetchLoad()
}
}
private func cancelTaskImpl(_ task: RetrieveImageDownloadTask, fetchLoad: ImageFetchLoad? = nil, ignoreTaskCount: Bool = false) {
func getFetchLoad(from task: RetrieveImageDownloadTask) -> ImageFetchLoad? {
guard let URL = task.internalTask.originalRequest?.url,
let imageFetchLoad = self.fetchLoads[URL] else
{
return nil
}
return imageFetchLoad
}
guard let imageFetchLoad = fetchLoad ?? getFetchLoad(from: task) else {
return
}
imageFetchLoad.downloadTaskCount -= 1
if ignoreTaskCount || imageFetchLoad.downloadTaskCount == 0 {
task.internalTask.cancel()
}
}
func cancel(_ task: RetrieveImageDownloadTask) {
barrierQueue.sync(flags: .barrier) { cancelTaskImpl(task) }
}
/// Cancel all downloading tasks. It will trigger the completion handlers for all not-yet-finished
/// downloading tasks with an NSURLErrorCancelled error.
///
/// If you need to only cancel a certain task, call `cancel()` on the `RetrieveImageDownloadTask`
/// returned by the downloading methods.
public func cancelAll() {
barrierQueue.sync(flags: .barrier) {
fetchLoads.forEach { v in
let fetchLoad = v.value
guard let task = fetchLoad.downloadTask else { return }
cancelTaskImpl(task, fetchLoad: fetchLoad, ignoreTaskCount: true)
}
}
}
}
// MARK: - NSURLSessionDataDelegate
/// Delegate class for `NSURLSessionTaskDelegate`.
/// The session object will hold its delegate until it gets invalidated.
/// If we use `ImageDownloader` as the session delegate, it will not be released.
/// So we need an additional handler to break the retain cycle.
// See https://github.com/onevcat/Kingfisher/issues/235
final class ImageDownloaderSessionHandler: NSObject, URLSessionDataDelegate, AuthenticationChallengeResponsable {
private let downloaderQueue: DispatchQueue
// The holder will keep downloader not released while a data task is being executed.
// It will be set when the task started, and reset when the task finished.
private var _downloadHolder: ImageDownloader?
var downloadHolder: ImageDownloader? {
get {
return downloaderQueue.sync { _downloadHolder }
}
set {
downloaderQueue.sync { _downloadHolder = newValue }
}
}
init(name: String) {
downloaderQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.SessionHandler.\(name)")
super.init()
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
guard let downloader = downloadHolder else {
completionHandler(.cancel)
return
}
var disposition = URLSession.ResponseDisposition.allow
if let statusCode = (response as? HTTPURLResponse)?.statusCode,
let url = dataTask.originalRequest?.url,
!(downloader.delegate ?? downloader).isValidStatusCode(statusCode, for: downloader)
{
let error = NSError(domain: KingfisherErrorDomain,
code: KingfisherError.invalidStatusCode.rawValue,
userInfo: [KingfisherErrorStatusCodeKey: statusCode, NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)])
// Needs to be called before callCompletionHandlerFailure() because it removes downloadHolder
if let downloader = downloadHolder {
downloader.delegate?.imageDownloader(downloader, didFinishDownloadingImageForURL: url, with: response, error: error)
}
callCompletionHandlerFailure(error: error, url: url)
disposition = .cancel
}
completionHandler(disposition)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard let downloader = downloadHolder else {
return
}
if let url = dataTask.originalRequest?.url, let fetchLoad = downloader.fetchLoad(for: url) {
fetchLoad.responseData.append(data)
if let expectedLength = dataTask.response?.expectedContentLength {
for content in fetchLoad.contents {
DispatchQueue.main.async {
content.callback.progressBlock?(Int64(fetchLoad.responseData.length), expectedLength)
}
}
}
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let url = task.originalRequest?.url else {
return
}
if let downloader = downloadHolder {
downloader.delegate?.imageDownloader(downloader, didFinishDownloadingImageForURL: url, with: task.response, error: error)
}
guard error == nil else {
callCompletionHandlerFailure(error: error!, url: url)
return
}
processImage(for: task, url: url)
}
/**
This method is exposed since the compiler requests. Do not call it.
*/
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let downloader = downloadHolder else {
return
}
downloader.authenticationChallengeResponder?.downloader(downloader, didReceive: challenge, completionHandler: completionHandler)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let downloader = downloadHolder else {
return
}
downloader.authenticationChallengeResponder?.downloader(downloader, task: task, didReceive: challenge, completionHandler: completionHandler)
}
private func cleanFetchLoad(for url: URL) {
guard let downloader = downloadHolder else {
return
}
downloader.barrierQueue.sync(flags: .barrier) {
downloader.fetchLoads.removeValue(forKey: url)
if downloader.fetchLoads.isEmpty {
downloadHolder = nil
}
}
}
private func callCompletionHandlerFailure(error: Error, url: URL) {
guard let downloader = downloadHolder, let fetchLoad = downloader.fetchLoad(for: url) else {
return
}
// We need to clean the fetch load first, before actually calling completion handler.
cleanFetchLoad(for: url)
var leftSignal: Int
repeat {
leftSignal = fetchLoad.cancelSemaphore?.signal() ?? 0
} while leftSignal != 0
for content in fetchLoad.contents {
content.options.callbackDispatchQueue.safeAsync {
content.callback.completionHandler?(nil, error as NSError, url, nil)
}
}
}
private func processImage(for task: URLSessionTask, url: URL) {
guard let downloader = downloadHolder else {
return
}
// We are on main queue when receiving this.
downloader.processQueue.async {
guard let fetchLoad = downloader.fetchLoad(for: url) else {
return
}
self.cleanFetchLoad(for: url)
let data: Data?
let fetchedData = fetchLoad.responseData as Data
if let delegate = downloader.delegate {
data = delegate.imageDownloader(downloader, didDownload: fetchedData, for: url)
} else {
data = fetchedData
}
// Cache the processed images. So we do not need to re-process the image if using the same processor.
// Key is the identifier of processor.
var imageCache: [String: Image] = [:]
for content in fetchLoad.contents {
let options = content.options
let completionHandler = content.callback.completionHandler
let callbackQueue = options.callbackDispatchQueue
let processor = options.processor
var image = imageCache[processor.identifier]
if let data = data, image == nil {
image = processor.process(item: .data(data), options: options)
// Add the processed image to cache.
// If `image` is nil, nothing will happen (since the key is not existing before).
imageCache[processor.identifier] = image
}
if let image = image {
downloader.delegate?.imageDownloader(downloader, didDownload: image, for: url, with: task.response)
let imageModifier = options.imageModifier
let finalImage = imageModifier.modify(image)
if options.backgroundDecode {
let decodedImage = finalImage.kf.decoded
callbackQueue.safeAsync { completionHandler?(decodedImage, nil, url, data) }
} else {
callbackQueue.safeAsync { completionHandler?(finalImage, nil, url, data) }
}
} else {
if let res = task.response as? HTTPURLResponse , res.statusCode == 304 {
let notModified = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notModified.rawValue, userInfo: nil)
completionHandler?(nil, notModified, url, nil)
continue
}
let badData = NSError(domain: KingfisherErrorDomain, code: KingfisherError.badData.rawValue, userInfo: nil)
callbackQueue.safeAsync { completionHandler?(nil, badData, url, nil) }
}
}
}
}
}
// Placeholder. For retrieving extension methods of ImageDownloaderDelegate
extension ImageDownloader: ImageDownloaderDelegate {}
| mit |
brianpartridge/Life | Life/Beehive.swift | 1 | 637 | //
// Beehive.swift
// Life
//
// Created by Brian Partridge on 11/1/15.
// Copyright © 2015 PearTreeLabs. All rights reserved.
//
public struct Beehive: Pattern {
// MARK: - Initialization
public init() {}
// MARK: - Pattern
public var size: Size {
return Size(width: 4, height: 3)
}
public var coordinates: [Coordinate] {
return [
Coordinate(x: 1, y: 0),
Coordinate(x: 2, y: 0),
Coordinate(x: 0, y: 1),
Coordinate(x: 3, y: 1),
Coordinate(x: 1, y: 2),
Coordinate(x: 2, y: 2)
]
}
}
| mit |
nicolas-miari/Kanji-Checker | Code/KanjiChecker/View/CheckerViewController.swift | 1 | 1775 | //
// MainViewController.swift
// KanjiChecker
//
// Created by Nicolás Miari on 2020/04/08.
// Copyright © 2020 Nicolás Miari. All rights reserved.
//
import Cocoa
class CheckerViewController: NSViewController {
// MARK: - GUI
@IBOutlet private weak var textView: NSTextView!
@IBOutlet private weak var audiencePopupButton: NSPopUpButton!
@IBOutlet private weak var checkButton: NSButton!
var progressViewController: ProgressViewController?
let checker = Checker()
// MARK: - NSViewController
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// MARK: - Control Actions
@IBAction func check(_ sender: Any) {
guard let storyboard = self.storyboard else {
fatalError("FUCK YOU")
}
guard let progress = storyboard.instantiateController(withIdentifier: "Progress") as? ProgressViewController else {
fatalError("Fuck You")
}
let text = textView.attributedString()
let grade = audiencePopupButton.indexOfSelectedItem
progress.appearHandler = { [unowned self] in
// Begin task...
self.checker.highlightInput(text, grade: grade, progress: { (value) in
progress.setProgress(value)
}, completion: {[unowned self](result) in
self.textView.textStorage?.setAttributedString(result)
self.dismiss(progress)
})
}
progress.cancelHandler = { [unowned self] in
self.dismiss(progress)
}
presentAsSheet(progress)
}
@IBAction func audienceChanged(_ sender: Any) {
textView.string = textView.attributedString().string
}
}
| mit |
attackFromCat/LivingTVDemo | LivingTVDemo/LivingTVDemo/Classes/Home/Controller/AmuseViewController.swift | 1 | 1519 | //
// AmuseViewController.swift
// LivingTVDemo
//
// Created by 李翔 on 2017/1/9.
// Copyright © 2017年 Lee Xiang. All rights reserved.
//
import UIKit
fileprivate let kMenuViewH : CGFloat = 200
class AmuseViewController: BaseAnchorViewController {
// MARK: 懒加载属性
fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel()
fileprivate lazy var menuView : AmuseMenuView = {
let menuView = AmuseMenuView.amuseMenuView()
menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH)
return menuView
}()
}
// MARK:- 设置UI界面
extension AmuseViewController {
override func setupUI() {
super.setupUI()
// 将菜单的View添加到collectionView中
collectionView.addSubview(menuView)
collectionView.contentInset = UIEdgeInsets(top: kMenuViewH, left: 0, bottom: 0, right: 0)
}
}
// MARK:- 请求数据
extension AmuseViewController {
override func loadData() {
// 1.给父类中ViewModel进行赋值
baseVM = amuseVM
// 2.请求数据
amuseVM.loadAmuseData {
// 2.1.刷新表格
self.collectionView.reloadData()
// 2.2.调整数据
var tempGroups = self.amuseVM.anchorGroups
tempGroups.removeFirst()
self.menuView.groups = tempGroups
// 3.数据请求完成
self.loadDataFinished()
}
}
}
| mit |
NGeenLibraries/NGeen | Example/App/Configuration/Constant.swift | 1 | 1498 | //
// Constant.swift
// Copyright (c) 2014 NGeen
//
// 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.
let kDropBoxAppKey: String = "x30coecna5t1osq"
let kDropBoxSecretKey: String = "t5rpdejos1xveik"
let kDropBoxServer: String = "__DropBoxServer"
let kMarvelServer: String = "__MarvelServer"
let kMarvelPrivateKey: String = "ddd8ee63a2f05578b48ae39e7b17bdffdccde476"
let kMarvelPublicKey: String = "71764b1899e4612a9ecf8b59ea727ec7"
let kParseServer: String = "__ParseServer"
| mit |
abring/sample_ios | Abring/ABRLoginViewController.swift | 1 | 21099 | //
// AbLoginViewController.swift
// KhabarVarzeshi
//
// Created by Hosein Abbaspour on 3/22/1396 AP.
// Copyright © 1396 AP Sanjaqak. All rights reserved.
//
import UIKit
@objc public protocol ABRLoginDelegate {
func userDidLogin(_ player : ABRPlayer)
@objc optional func userDismissScreen()
@objc optional func errorOccured(_ errorType : ABRErrorType)
}
public enum ABRLoginViewStyle {
case lightBlur
case extraLightBlur
case darkBlur
case darken
case lighten
}
enum LoginType {
case justPhone
case justUserPass
case both
}
class ABRTimer : Timer {
@discardableResult class func countDownFrom(_ time : Int , actionBlock : @escaping (_ current : Int) -> Void , finished completion : @escaping () -> Void) -> Timer {
var timerCount = time
let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { timer in
timerCount -= 1
actionBlock(timerCount)
if timerCount == 0 {
timer.invalidate()
completion()
}
})
print("d")
return timer
}
}
class ABRLoginViewController: UIViewController {
private var inset : CGFloat = 10
var isFullScreen = false {
didSet {
if isFullScreen == true {
loginView.transform = .identity
loginView.alpha = 1
loginView.backgroundColor = .clear
dismissButton.removeFromSuperview()
view.backgroundColor = UIColor.white
loginView.frame.origin.x = 0
loginView.frame.size.width = view.frame.size.width
inset = 40
refreshLayout()
}
}
}
var style : ABRLoginViewStyle = .darken
private var dismissButton : UIButton!
private var mainScrollView : UIScrollView!
private var innerScrollView : UIScrollView!
private var phoneTf : UITextField!
private var codeTf : UITextField!
private var visualEffectBlurView = UIVisualEffectView()
private var loginView : UIView!
private var confirmPhoneBtn = UIButton()
private var confirmCodeBtn = UIButton()
private var otherWaysBtn = UIButton()
private var backBtn = UIButton()
private var inputPhoneLabel : UILabel!
private var inputCodeLabel : UILabel!
private var timerLabel : UILabel!
var delegate : ABRLoginDelegate?
//MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !isFullScreen {
presentAnimation()
} else {
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
}
convenience init() {
self.init(nibName: nil, bundle: nil)
view.isOpaque = false
view.backgroundColor = UIColor.clear
setupDismissButton()
setupLoginView()
setupScrollView()
setupTextField()
setupButtons()
setupLabels()
}
@objc private func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
mainScrollView.setContentOffset(CGPoint.init(x: 0, y: keyboardHeight/2), animated: true)
}
}
//MARK: Animations
private func presentAnimation() {
switch style {
case .darken:
UIView.animate(withDuration: 0.3, animations: {
self.view.backgroundColor = UIColor(white: 0, alpha: 0.4)
})
case .lighten:
UIView.animate(withDuration: 0.3, animations: {
self.view.backgroundColor = UIColor(white: 1, alpha: 0.4)
})
case .lightBlur:
visualEffectBlurView.frame = view.bounds
view.insertSubview(visualEffectBlurView, at: 0)
visualEffectBlurView.alpha = 1
UIView.animate(withDuration: 0.3 , animations: {
self.visualEffectBlurView.effect = UIBlurEffect(style: .light)
})
case .extraLightBlur:
visualEffectBlurView.frame = view.bounds
view.insertSubview(visualEffectBlurView, at: 0)
visualEffectBlurView.alpha = 1
UIView.animate(withDuration: 0.3 , animations: {
self.visualEffectBlurView.effect = UIBlurEffect(style: .extraLight)
})
case .darkBlur:
visualEffectBlurView.frame = view.bounds
view.insertSubview(visualEffectBlurView, at: 0)
visualEffectBlurView.alpha = 1
UIView.animate(withDuration: 0.3 , animations: {
self.visualEffectBlurView.effect = UIBlurEffect(style: .dark)
})
}
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.7 , initialSpringVelocity: 20 , options: .curveLinear, animations: {
self.loginView.transform = .identity
self.loginView.alpha = 1
}, completion: nil)
}
private func dismissAnimation(completion : @escaping () -> Void) {
switch style {
case .darken , .lighten:
UIView.animate(withDuration: 0.3, animations: {
self.view.backgroundColor = UIColor.clear
})
case .lightBlur , .extraLightBlur , .darkBlur:
UIView.animate(withDuration: 0.2 , animations: {
self.visualEffectBlurView.effect = nil
})
}
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveLinear, animations: {
self.loginView.transform = CGAffineTransform(scaleX: 0.85, y: 0.85)
self.loginView.alpha = 0
}, completion: { finished in
completion()
})
}
//MARK: setup ui
private func setupTextField() {
if ABRAppConfig.textField != nil {
phoneTf = ABRAppConfig.textField
phoneTf.frame = CGRect(x: 30, y: loginView.bounds.size.height / 2 - 25, width: loginView.bounds.size.width - 60, height: 30)
codeTf = ABRAppConfig.textField
codeTf.frame = CGRect(x: loginView.bounds.size.width + 30, y: loginView.bounds.size.height / 2 - 25, width: loginView.bounds.size.width - 60, height: 30)
} else {
phoneTf = ABRUITextField(frame: CGRect(x: 30, y: loginView.bounds.size.height / 2 - 25, width: loginView.bounds.size.width - 60, height: 30))
phoneTf.placeholder = ABRAppConfig.textFieldsPlaceHolders.phoneTextFieldPlaceHolder
phoneTf.keyboardType = .phonePad
codeTf = ABRUITextField(frame: CGRect(x: loginView.bounds.size.width + 30, y: loginView.bounds.size.height / 2 - 25, width: loginView.bounds.size.width - 60, height: 30))
codeTf.placeholder = ABRAppConfig.textFieldsPlaceHolders.codeTextFieldPlaceHolder
codeTf.keyboardType = .numberPad
}
innerScrollView.addSubview(phoneTf)
innerScrollView.addSubview(codeTf)
}
private func setupButtons() {
if ABRAppConfig.mainButton != nil {
confirmPhoneBtn = ABRAppConfig.mainButton
confirmPhoneBtn.frame = CGRect(x: 30, y: loginView.bounds.size.height - 60 , width: loginView.bounds.size.width - 60 , height: 34)
} else {
confirmPhoneBtn = UIButton(type: .system)
confirmPhoneBtn.frame = CGRect(x: 30, y: loginView.bounds.size.height - 60 , width: loginView.bounds.size.width - 60 , height: 34)
confirmPhoneBtn.backgroundColor = ABRAppConfig.tintColor
confirmPhoneBtn.layer.cornerRadius = 4
confirmPhoneBtn.setTitle(ABRAppConfig.buttonsTitles.loginSendCodeToPhoneButtonTitle , for: .normal)
confirmPhoneBtn.tintColor = UIColor.white
confirmPhoneBtn.titleLabel?.font = ABRAppConfig.font
}
confirmPhoneBtn.addTarget(self, action: #selector(sendCodeAction), for: .touchUpInside)
innerScrollView.addSubview(confirmPhoneBtn)
if ABRAppConfig.mainButton != nil {
confirmCodeBtn = ABRAppConfig.mainButton
confirmCodeBtn.frame = CGRect(x: loginView.bounds.size.width + 30, y: loginView.bounds.size.height - 60 , width: loginView.bounds.size.width - 60 , height: 34)
} else {
confirmCodeBtn = UIButton(type: .system)
confirmCodeBtn.frame = CGRect(x: loginView.bounds.size.width + 30, y: loginView.bounds.size.height - 60 , width: loginView.bounds.size.width - 60 , height: 34)
confirmCodeBtn.backgroundColor = ABRAppConfig.tintColor
confirmCodeBtn.layer.cornerRadius = 4
confirmCodeBtn.setTitle(ABRAppConfig.buttonsTitles.loginConfirmCodeButtonTitle , for: .normal)
confirmCodeBtn.tintColor = UIColor.white
confirmCodeBtn.titleLabel?.font = ABRAppConfig.font
}
confirmCodeBtn.addTarget(self, action: #selector(verifyCodeAction), for: .touchUpInside)
innerScrollView.addSubview(confirmCodeBtn)
// if ABAppConfig.secondaryButton != nil {
// otherWaysBtn = ABAppConfig.mainButton
// otherWaysBtn.frame = CGRect(x: 30, y: loginView.bounds.size.height - 80 , width: loginView.bounds.size.width - 60 , height: 34)
// } else {
// otherWaysBtn = UIButton(type: .system)
// otherWaysBtn.frame = CGRect(x: 30, y: loginView.bounds.size.height - 40 , width: loginView.bounds.size.width - 60 , height: 34)
// otherWaysBtn.backgroundColor = UIColor.clear
// otherWaysBtn.setTitle(ABAppConfig.buttonsTitles.loginOtherWaysButtonTitle , for: .normal)
// otherWaysBtn.setTitleColor(ABAppConfig.tintColor, for: .normal)
// otherWaysBtn.titleLabel?.font = ABAppConfig.font
// }
// innerScrollView.addSubview(otherWaysBtn)
backBtn = UIButton(type: .system)
backBtn.frame = CGRect(x: loginView.bounds.width, y: 4, width: 30, height: 30)
let img = UIImage(named: "AbringKit.bundle/images/back", in: Bundle.init(for: ABRApp.self), compatibleWith: nil) ?? UIImage()
img.withRenderingMode(.alwaysTemplate)
backBtn.setImage(img, for: .normal)
backBtn.tintColor = ABRAppConfig.tintColor
backBtn.addTarget(self, action: #selector(backToInputPhone), for: .touchUpInside)
innerScrollView.addSubview(backBtn)
}
private func setupLabels() {
inputPhoneLabel = UILabel(frame: CGRect(x: 10, y: 10, width: loginView.bounds.size.width - 20 , height: 80))
inputPhoneLabel.text = ABRAppConfig.texts.inputPhoneText
innerScrollView.addSubview(inputPhoneLabel)
inputCodeLabel = UILabel(frame: CGRect(x: loginView.bounds.size.width + 10, y: 10, width: loginView.bounds.size.width - 20 , height: 80))
inputCodeLabel.text = ABRAppConfig.texts.inputCodeText
innerScrollView.addSubview(inputCodeLabel)
timerLabel = UILabel(frame: CGRect(x: loginView.bounds.size.width + 10, y: loginView.bounds.size.height - 90, width: loginView.bounds.size.width - 20 , height: 20))
innerScrollView.addSubview(timerLabel)
for label in [inputCodeLabel , inputPhoneLabel , timerLabel] {
if ABRAppConfig.font != nil {
label?.font = UIFont(name: ABRAppConfig.font!.fontName, size: ABRAppConfig.font!.pointSize - 2)
}
label?.numberOfLines = 3
label?.textColor = ABRAppConfig.labelsColor
label?.textAlignment = .center
}
}
private func setupScrollView() {
mainScrollView = UIScrollView(frame: view.frame)
mainScrollView.addSubview(dismissButton)
mainScrollView.addSubview(loginView)
mainScrollView.contentSize = view.frame.size
view.addSubview(mainScrollView)
innerScrollView = UIScrollView(frame: loginView.bounds)
innerScrollView.contentSize = CGSize(width: loginView.bounds.size.width * 2 , height: loginView.bounds.size.height)
innerScrollView.showsVerticalScrollIndicator = false
innerScrollView.showsHorizontalScrollIndicator = false
innerScrollView.isScrollEnabled = false
loginView.addSubview(innerScrollView)
}
private func setupDismissButton() {
dismissButton = UIButton(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: view.bounds.size.height))
dismissButton.setTitle(nil, for: .normal)
dismissButton.addTarget(self, action: #selector(dismissAction), for: .touchDown)
view.addSubview(dismissButton)
view.bringSubview(toFront: dismissButton)
}
private func setupLoginView() {
loginView = UIView(frame: CGRect(x: view.bounds.size.width / 2 - 120 ,
y: view.bounds.size.height / 2 - 120 ,
width: 240,
height: 240))
loginView.backgroundColor = UIColor.white
loginView.clipsToBounds = true
loginView.layer.cornerRadius = 10
view.addSubview(loginView)
view.bringSubview(toFront: loginView)
loginView.alpha = 0
loginView.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}
private func refreshLayout() {
innerScrollView.frame = loginView.bounds
innerScrollView.contentSize = CGSize(width: loginView.bounds.size.width * 2 , height: loginView.bounds.size.height)
inputPhoneLabel.frame = CGRect(x: inset, y: 10, width: loginView.bounds.size.width - (inset * 2) , height: 80)
inputCodeLabel.frame = CGRect(x: loginView.bounds.size.width + inset, y: 10, width: loginView.bounds.size.width - inset * 2 , height: 80)
confirmPhoneBtn.frame = CGRect(x: inset + 20, y: loginView.bounds.size.height - 60 , width: loginView.bounds.size.width - (inset * 2 + 40) , height: 34)
confirmCodeBtn.frame = CGRect(x: loginView.bounds.size.width + inset + 20, y: loginView.bounds.size.height - 60 , width: loginView.bounds.size.width - (inset * 2 + 40) , height: 34)
backBtn.frame = CGRect(x: loginView.bounds.width, y: 4, width: 30, height: 30)
phoneTf.frame = CGRect(x: inset + 20, y: loginView.bounds.size.height / 2 - 25, width: loginView.bounds.size.width - (inset * 2 + 40), height: 30)
codeTf.frame = CGRect(x: loginView.bounds.size.width + inset + 20, y: loginView.bounds.size.height / 2 - 25 , width: loginView.bounds.size.width - (inset * 2 + 40) , height: 30)
}
//MARK: button selectors
@objc private func sendCodeAction() {
if (phoneTf.text?.characters.count)! == 11 {
confirmPhoneBtn.setTitle(nil, for: .normal)
confirmPhoneBtn.isEnabled = false
let activity = UIActivityIndicatorView(activityIndicatorStyle: .white)
loginView.addSubview(activity)
activity.center = confirmPhoneBtn.center
activity.startAnimating()
ABRPlayer.requestRegisterCode(phoneNumber: phoneTf.text!.englishNumbers()! , completion: {[unowned self] (success, errorType) in
activity.stopAnimating()
activity.removeFromSuperview()
self.confirmPhoneBtn.setTitle(ABRAppConfig.buttonsTitles.loginSendCodeToPhoneButtonTitle, for: .normal)
self.confirmPhoneBtn.isEnabled = true
if success {
self.timer()
self.innerScrollView.setContentOffset(CGPoint(x: self.loginView.bounds.size.width , y:0) , animated: true)
self.codeTf.becomeFirstResponder()
} else {
if ABRAppConfig.loginHasBuiltinErrorMessages {
self.loginView.showOverlayError(errorType!)
}
self.delegate?.errorOccured!(errorType!)
}
})
} else {
print("Phone number is empty")
confirmPhoneBtn.shake()
}
}
@objc private func verifyCodeAction() {
if confirmCodeBtn.tag == 0 {
if (codeTf.text?.characters.count)! == 5 {
confirmCodeBtn.setTitle(nil, for: .normal)
confirmCodeBtn.isEnabled = false
let activity = UIActivityIndicatorView(activityIndicatorStyle: .white)
loginView.addSubview(activity)
loginView.bringSubview(toFront: activity)
activity.center = CGPoint(x: confirmCodeBtn.center.x - loginView.frame.size.width, y: confirmCodeBtn.center.y)
activity.startAnimating()
ABRPlayer.verifyRegisterCode(phoneNumber: phoneTf.text!, code: codeTf.text!, completion: { (success, player , errorType) in
activity.stopAnimating()
activity.removeFromSuperview()
self.confirmCodeBtn.setTitle(ABRAppConfig.buttonsTitles.loginConfirmCodeButtonTitle, for: .normal)
self.confirmCodeBtn.isEnabled = true
if success {
self.view.endEditing(true)
if self.isFullScreen {
self.delegate?.userDidLogin(player!)
} else {
self.dismissAnimation {
self.dismiss(animated: false, completion: nil)
self.delegate?.userDidLogin(player!)
}
}
} else {
if ABRAppConfig.loginHasBuiltinErrorMessages {
self.loginView.showOverlayError(errorType!)
}
self.delegate?.errorOccured!(errorType!)
}
})
} else {
print("code field's length is not 5")
confirmCodeBtn.shake()
}
} else {
ABRPlayer.resendRegisterCode(phoneNumber: phoneTf.text!.englishNumbers()!, completion: { (success, errorType) in
if success {
self.confirmCodeBtn.tag = 0
self.confirmCodeBtn.setTitle("ورود به حساب", for: .normal)
self.timer()
} else {
if ABRAppConfig.loginHasBuiltinErrorMessages {
self.loginView.showOverlayError(errorType!)
}
self.delegate?.errorOccured!(errorType!)
}
})
}
}
@objc private func backToInputPhone() {
innerScrollView.setContentOffset(CGPoint(x: 0 , y: 0), animated: true)
codeTf.text = nil
phoneTf.becomeFirstResponder()
}
@objc private func dismissAction() {
view.endEditing(true)
self.delegate?.userDismissScreen!()
dismissAnimation {
self.dismiss(animated: false, completion: nil)
}
}
//MARK: Timer
func timer() {
var timerCounter = 150
let mins = timerCounter / 60 == 0 ? "0" : "0\(timerCounter / 60)"
let secs = timerCounter % 60 < 10 ? "0\(timerCounter % 60)" : "\(timerCounter % 60)"
timerLabel.text = mins + " : " + secs
ABRTimer.countDownFrom(150, actionBlock: {(current) in
timerCounter -= 1
let mins = timerCounter / 60 == 0 ? "0" : "0\(timerCounter / 60)"
let secs = timerCounter % 60 < 10 ? "0\(timerCounter % 60)" : "\(timerCounter % 60)"
self.timerLabel.text = mins + " : " + secs
}, finished: {
self.timerLabel.text = ""
self.confirmCodeBtn.setTitle("ارسال مجدد کد", for: .normal)
self.confirmCodeBtn.tag = 1
})
}
}
fileprivate extension UIView {
func shake() {
let shake = CAKeyframeAnimation(keyPath: "transform.translation.x")
shake.duration = 0.6
shake.keyTimes = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1]
shake.values = [-10 , 10 , -10 , 10 , -7 , 7 , -4 , 0]
self.layer.add(shake, forKey: "shake")
}
}
| mit |
Rehsco/StyledAuthenticationView | StyledAuthenticationView/Model/AuthStateMachine.swift | 1 | 2397 | //
// AuthStateMachine.swift
// StyledAuthenticationView
//
// Created by Martin Rehder on 02.02.2017.
/*
* Copyright 2017-present Martin Jacob Rehder.
* http://www.rehsco.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import Foundation
enum AuthenticationStateType {
case touchID
case pin
case password
}
class AuthStateMachine {
var currentState: AuthenticationStateType = .touchID
var useTouchID: Bool = false
var usePin: Bool = false
var usePassword: Bool = false
func initiate() -> Bool {
if useTouchID {
currentState = .touchID
return true
}
else if usePin {
currentState = .pin
return true
}
else if usePassword {
currentState = .password
return true
}
return false
}
func next() -> Bool {
if currentState == .password {
return false
}
if currentState == .touchID {
currentState = .pin
if !self.usePin {
return self.next()
}
return true
}
if currentState == .pin {
currentState = .password
if !self.usePassword {
return self.next()
}
return true
}
return false
}
}
| mit |
nmdias/FeedKit | Sources/FeedKit/Models/Namespaces/Media/MediaCopyright.swift | 2 | 2848 | //
// MediaCopyright.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/// Copyright information for the media object. It has one optional attribute.
public class MediaCopyright {
/// The element's attributes.
public class Attributes {
/// The URL for a terms of use page or additional copyright information.
/// If the media is operating under a Creative Commons license, the
/// Creative Commons module should be used instead. It is an optional
/// attribute.
public var url: String?
}
/// The element's attributes.
public var attributes: Attributes?
/// The element's value.
public var value: String?
public init() { }
}
// MARK: - Initializers
extension MediaCopyright {
convenience init(attributes attributeDict: [String : String]) {
self.init()
self.attributes = MediaCopyright.Attributes(attributes: attributeDict)
}
}
extension MediaCopyright.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.url = attributeDict["url"]
}
}
// MARK: - Equatable
extension MediaCopyright: Equatable {
public static func ==(lhs: MediaCopyright, rhs: MediaCopyright) -> Bool {
return
lhs.value == rhs.value &&
lhs.attributes == rhs.attributes
}
}
extension MediaCopyright.Attributes: Equatable {
public static func ==(lhs: MediaCopyright.Attributes, rhs: MediaCopyright.Attributes) -> Bool {
return lhs.url == rhs.url
}
}
| mit |
trupin/Beaver | BeaverTestKit/Type/ViewControllerMock.swift | 2 | 853 | import Beaver
public final class ViewControllerStub<StateType: State, ParentStateType: State, AUIActionType: Action>: ViewController<StateType, ParentStateType, AUIActionType> {
public private(set) var stateDidUpdateCallCount = 0
public private(set) var source: ActionEnvelop?
public private(set) var oldState: StateType?
public private(set) var newState: StateType?
public override func stateDidUpdate(oldState: StateType?,
newState: StateType,
completion: @escaping () -> ()) {
self.oldState = oldState
self.newState = newState
stateDidUpdateCallCount += 1
completion()
}
public func clear() {
stateDidUpdateCallCount = 0
source = nil
oldState = nil
newState = nil
}
}
| mit |
kyleweiner/KWStepper | Package.swift | 1 | 455 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "KWStepper",
platforms: [
.iOS(.v8)
],
products: [
.library(name: "KWStepper", targets: ["KWStepper"]),
],
targets: [
.target(name: "KWStepper", path: "Source"),
.testTarget(
name: "KWStepperTests",
dependencies: ["KWStepper"],
path: "KWStepper/KWStepperTests"
),
]
)
| mit |
per-dalsgaard/20-apps-in-20-weeks | App 04 - SwappingScreens/SwappingScreens/MusicListVC.swift | 1 | 954 | //
// MusicListVC.swift
// SwappingScreens
//
// Created by Per Kristensen on 02/04/2017.
// Copyright © 2017 Per Dalsgaard. All rights reserved.
//
import UIKit
class MusicListVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = UIColor.blue
}
@IBAction func backButtonPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func load3rdScreenPressed(_ sender: Any) {
let songTitle = "Quit Playing Games With My Heart"
performSegue(withIdentifier: "PlaySongVC", sender: songTitle)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? PlaySongVC {
if let song = sender as? String {
destination.selectedTitle = song
}
}
}
}
| mit |
1yvT0s/XWebView | XWebView/XWVInvocation.swift | 1 | 12436 | /*
Copyright 2015 XWebView
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import ObjectiveC
private let _NSInvocation: AnyClass = NSClassFromString("NSInvocation")!
private let _NSMethodSignature: AnyClass = NSClassFromString("NSMethodSignature")!
public class XWVInvocation {
public final let target: AnyObject
public init(target: AnyObject) {
self.target = target
}
public func call(selector: Selector, withArguments arguments: [Any!]) -> Any! {
let method = class_getInstanceMethod(target.dynamicType, selector)
if method == nil {
// TODO: supports forwordingTargetForSelector: of NSObject?
(target as? NSObject)?.doesNotRecognizeSelector(selector)
// Not an NSObject, mimic the behavior of NSObject
let reason = "-[\(target.dynamicType) \(selector)]: unrecognized selector sent to instance \(unsafeAddressOf(target))"
withVaList([reason]) { NSLogv("%@", $0) }
NSException(name: NSInvalidArgumentException, reason: reason, userInfo: nil).raise()
}
let sig = _NSMethodSignature.signatureWithObjCTypes(method_getTypeEncoding(method))!
let inv = _NSInvocation.invocationWithMethodSignature(sig)
// Setup arguments
assert(arguments.count + 2 <= Int(sig.numberOfArguments), "Too many arguments for calling -[\(target.dynamicType) \(selector)]")
var args = [[Word]](count: arguments.count, repeatedValue: [])
for var i = 0; i < arguments.count; ++i {
let type = sig.getArgumentTypeAtIndex(i + 2)
let typeChar = Character(UnicodeScalar(UInt8(type[0])))
// Convert argument type to adapte requirement of method.
// Firstly, convert argument to appropriate object type.
var argument: Any! = self.dynamicType.convertToObjectFromAnyValue(arguments[i])
assert(argument != nil || arguments[i] == nil, "Can't convert '\(arguments[i].dynamicType)' to object type")
if typeChar != "@", let obj: AnyObject = argument as? AnyObject {
// Convert back to scalar type as method requires.
argument = self.dynamicType.convertFromObject(obj, toObjCType: type)
}
if typeChar == "f", let float = argument as? Float {
// Float type shouldn't be promoted to double if it is not variadic.
args[i] = [ Word(unsafeBitCast(float, UInt32.self)) ]
} else if let val = argument as? CVarArgType {
// Scalar(except float), pointer and Objective-C object types
args[i] = val.encode()
} else if let obj: AnyObject = argument as? AnyObject {
// Pure swift object type
args[i] = [ unsafeBitCast(unsafeAddressOf(obj), Word.self) ]
} else {
// Nil or unsupported type
assert(argument == nil, "Unsupported argument type '\(String(UTF8String: type))'")
var align: Int = 0
NSGetSizeAndAlignment(sig.getArgumentTypeAtIndex(i), nil, &align)
args[i] = [Word](count: align / sizeof(Word.self), repeatedValue: 0)
}
args[i].withUnsafeBufferPointer() {
inv.setArgument(UnsafeMutablePointer($0.baseAddress), atIndex: i + 2)
}
}
inv.selector = selector
inv.invokeWithTarget(target)
if sig.methodReturnLength == 0 { return Void() }
// Fetch the return value
// TODO: Methods with 'ns_returns_retained' attribute cause leak of returned object.
let count = (sig.methodReturnLength + sizeof(Word.self) - 1) / sizeof(Word.self)
var words = [Word](count: count, repeatedValue: 0)
words.withUnsafeMutableBufferPointer() {
(inout buf: UnsafeMutableBufferPointer<Word>)->Void in
inv.getReturnValue(buf.baseAddress)
}
if sig.methodReturnLength <= sizeof(Word) {
// TODO: handle 64 bit type on 32-bit OS
return bitCastWord(words[0], toObjCType: sig.methodReturnType)
}
assertionFailure("Unsupported return type '\(String(UTF8String: sig.methodReturnType))'");
return Void()
}
public func call(selector: Selector, withArguments arguments: Any!...) -> Any! {
return call(selector, withArguments: arguments)
}
// Helper for Objective-C, accept ObjC 'id' instead of Swift 'Any' type for in/out parameters .
@objc public func call(selector: Selector, withObjects objects: [AnyObject]?) -> AnyObject! {
let args: [Any!] = objects?.map() { $0 !== NSNull() ? ($0 as Any) : nil } ?? []
let result = call(selector, withArguments: args)
return self.dynamicType.convertToObjectFromAnyValue(result)
}
// Syntactic sugar for calling method
public subscript (selector: Selector) -> (Any!...)->Any! {
return {
(args: Any!...)->Any! in
self.call(selector, withArguments: args)
}
}
}
extension XWVInvocation {
// Property accessor
public func getProperty(name: String) -> Any! {
let getter = getterOfName(name)
assert(getter != Selector(), "Property '\(name)' does not exist")
return getter != Selector() ? call(getter) : Void()
}
public func setValue(value: Any!, forProperty name: String) {
let setter = setterOfName(name)
assert(setter != Selector(), "Property '\(name)' " +
(getterOfName(name) == nil ? "does not exist" : "is readonly"))
assert(!(value is Void))
if setter != Selector() {
call(setter, withArguments: value)
}
}
// Syntactic sugar for accessing property
public subscript (name: String) -> Any! {
get {
return getProperty(name)
}
set {
setValue(newValue, forProperty: name)
}
}
private func getterOfName(name: String) -> Selector {
var getter = Selector()
let property = class_getProperty(self.target.dynamicType, name)
if property != nil {
let attr = property_copyAttributeValue(property, "G")
getter = Selector(attr == nil ? name : String(UTF8String: attr)!)
free(attr)
}
return getter
}
private func setterOfName(name: String) -> Selector {
var setter = Selector()
let property = class_getProperty(self.target.dynamicType, name)
if property != nil {
var attr = property_copyAttributeValue(property, "R")
if attr == nil {
attr = property_copyAttributeValue(property, "S")
if attr == nil {
setter = Selector("set\(String(first(name)!).uppercaseString)\(dropFirst(name)):")
} else {
setter = Selector(String(UTF8String: attr)!)
}
}
free(attr)
}
return setter
}
}
extension XWVInvocation {
// Type casting and conversion, reference:
// https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
// Cast Word value to specified Objective-C type (not support 32-bit)
private func bitCastWord(word: Word, toObjCType type: UnsafePointer<Int8>) -> Any? {
switch Character(UnicodeScalar(UInt8(type[0]))) {
case "c": return CChar(truncatingBitPattern: word)
case "i": return CInt(truncatingBitPattern: word)
case "s": return CShort(truncatingBitPattern: word)
case "l": return Int32(truncatingBitPattern: word)
case "q": return CLongLong(word)
case "C": return CUnsignedChar(truncatingBitPattern: word)
case "I": return CUnsignedInt(truncatingBitPattern: word)
case "S": return CUnsignedShort(truncatingBitPattern: word)
case "L": return UInt32(truncatingBitPattern: word)
case "Q": return unsafeBitCast(word, CUnsignedLongLong.self)
case "f": return unsafeBitCast(UInt32(truncatingBitPattern: word), CFloat.self)
case "d": return unsafeBitCast(word, CDouble.self)
case "B": return unsafeBitCast(UInt8(truncatingBitPattern: word), CBool.self)
case "v": return unsafeBitCast(word, Void.self)
case "*": return unsafeBitCast(word, UnsafePointer<CChar>.self)
case "@": return word != 0 ? unsafeBitCast(word, AnyObject.self) : nil
case "#": return unsafeBitCast(word, AnyClass.self)
case ":": return unsafeBitCast(word, Selector.self)
case "^", "?": return unsafeBitCast(word, COpaquePointer.self)
default: assertionFailure("Unknown Objective-C type encoding '\(String(UTF8String: type))'")
}
return Void()
}
// Convert AnyObject to appropriate Objective-C type
private class func convertFromObject(object: AnyObject, toObjCType type: UnsafePointer<Int8>) -> Any! {
let num = object as? NSNumber
switch Character(UnicodeScalar(UInt8(type[0]))) {
case "c": return num?.charValue
case "i": return num?.intValue
case "s": return num?.shortValue
case "l": return num?.intValue
case "q": return num?.longLongValue
case "C": return num?.unsignedCharValue
case "I": return num?.unsignedIntValue
case "S": return num?.unsignedShortValue
case "L": return num?.unsignedIntValue
case "Q": return num?.unsignedLongLongValue
case "f": return num?.floatValue
case "d": return num?.doubleValue
case "B": return num?.boolValue
case "v": return Void()
case "*": return (object as? String)?.nulTerminatedUTF8.withUnsafeBufferPointer({ COpaquePointer($0.baseAddress) })
case ":": return object is String ? Selector(object as! String) : Selector()
case "@": return object
case "#": return object
case "^", "?": return (object as? NSValue)?.pointerValue()
default: assertionFailure("Unknown Objective-C type encoding '\(String(UTF8String: type))'")
}
return nil
}
// Convert Any value to appropriate Objective-C object
public class func convertToObjectFromAnyValue(value: Any!) -> AnyObject! {
if value == nil || value is AnyObject {
// Some scalar types (Int, UInt, Bool, Float and Double) can be converted automatically by runtime.
return value as? AnyObject
}
if let i8 = value as? Int8 { return NSNumber(char: i8) } else
if let i16 = value as? Int16 { return NSNumber(short: i16) } else
if let i32 = value as? Int32 { return NSNumber(int: i32) } else
if let i64 = value as? Int64 { return NSNumber(longLong: i64) } else
if let u8 = value as? UInt8 { return NSNumber(unsignedChar: u8) } else
if let u16 = value as? UInt16 { return NSNumber(unsignedShort: u16) } else
if let u32 = value as? UInt32 { return NSNumber(unsignedInt: u32) } else
if let u64 = value as? UInt64 { return NSNumber(unsignedLongLong: u64) } else
if let us = value as? UnicodeScalar { return NSNumber(unsignedInt: us.value) } else
if let sel = value as? Selector { return sel.description } else
if let ptr = value as? COpaquePointer { return NSValue(pointer: UnsafePointer<Void>(ptr)) }
//assertionFailure("Can't convert '\(value.dynamicType)' to AnyObject")
return nil
}
}
// Additional Swift types which can be represented in C type.
extension Bool: CVarArgType {
public func encode() -> [Word] {
return [ Word(self) ]
}
}
extension UnicodeScalar: CVarArgType {
public func encode() -> [Word] {
return [ Word(self.value) ]
}
}
extension Selector: CVarArgType {
public func encode() -> [Word] {
return [ unsafeBitCast(self, Word.self) ]
}
}
| apache-2.0 |
thoughtbot/Argo | Tests/ArgoTests/Models/Booleans.swift | 1 | 262 | import Argo
import Curry
import Runes
struct Booleans: Argo.Decodable {
let bool: Bool
let number: Bool
static func decode(_ json: JSON) -> Decoded<Booleans> {
return curry(Booleans.init)
<^> json["realBool"]
<*> json["numberBool"]
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.