repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
milseman/swift | test/type/self.swift | 12 | 870 | // RUN: %target-typecheck-verify-swift
struct S0<T> {
func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'S0'?}}{{21-25=S0}}
}
class C0<T> {
func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{21-25=C0}}
}
enum E0<T> {
func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'E0'?}}{{21-25=E0}}
}
// rdar://problem/21745221
struct X {
typealias T = Int
}
extension X {
struct Inner {
}
}
extension X.Inner {
func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'X.Inner'?}}{{21-25=X.Inner}}
}
| apache-2.0 | 69510caa4dadcd7a893dd0c7e5642712 | 31.222222 | 171 | 0.648276 | 3.085106 | false | false | false | false |
TCA-Team/iOS | TUM Campus App/LectureDetailsManager.swift | 1 | 1434 | //
// LectureDetailsManager.swift
// TUM Campus App
//
// Created by Mathias Quintero on 1/17/16.
// Copyright © 2016 LS1 TUM. All rights reserved.
//
import SWXMLHash
import Sweeft
final class LectureDetailsManager: DetailsManager {
typealias DataType = Lecture
var config: Config
init(config: Config) {
self.config = config
}
func fetch(for data: Lecture) -> Promise<Lecture, APIError> {
guard !data.detailsLoaded else {
return .successful(with: data)
}
return config.tumOnline.doXMLObjectsRequest(to: .lectureDetails,
queries: ["pLVNr" : data.id],
at: "rowset", "row").map { (xml: [XMLIndexer]) in
data.detailsLoaded = true
guard let lecture = xml.first else {
return data
}
let details = [
("Methods", lecture["lehrmethode"].element?.text),
("Content", lecture["lehrinhalt"].element?.text),
("Goal", lecture["lehrziel"].element?.text),
("Language", lecture["haupt_unterrichtssprache"].element?.text),
("First Appointment", lecture["ersttermin"].element?.text)
] ==> iff
data.details.append(contentsOf: details)
return data
}
}
}
| gpl-3.0 | 49b8c73c42d254eb51fbf4baa296004d | 30.152174 | 101 | 0.526867 | 4.478125 | false | true | false | false |
EaglesoftZJ/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Dialogs List/Cells/AADialogSearchCell.swift | 1 | 1732 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import UIKit
open class AADialogSearchCell: AATableViewCell, AABindedSearchCell {
public typealias BindData = ACSearchResult
public static func bindedCellHeight(_ item: BindData) -> CGFloat {
return 76
}
fileprivate let avatarView: AAAvatarView = AAAvatarView()
fileprivate let titleView: UILabel = UILabel()
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: UITableViewCellStyle.default, reuseIdentifier: reuseIdentifier)
titleView.font = UIFont.mediumSystemFontOfSize(19)
titleView.textColor = ActorSDK.sharedActor().style.dialogTextColor
contentView.addSubview(avatarView)
contentView.addSubview(titleView)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func bind(_ item: ACSearchResult, search: String?) {
avatarView.bind(item.title, id: Int(item.peer.peerId), avatar: item.avatar)
titleView.text = item.title
}
open override func prepareForReuse() {
super.prepareForReuse()
avatarView.unbind()
}
open override func layoutSubviews() {
super.layoutSubviews()
let width = self.contentView.frame.width
let leftPadding = CGFloat(76)
let padding = CGFloat(14)
avatarView.frame = CGRect(x: padding, y: padding, width: 52, height: 52)
titleView.frame = CGRect(x: leftPadding, y: 0, width: width - leftPadding - (padding + 50), height: contentView.bounds.size.height)
}
}
| agpl-3.0 | 08c67249ad29f0363256c8b57aed63b3 | 31.074074 | 139 | 0.650115 | 4.824513 | false | false | false | false |
fluidsonic/JetPack | Sources/UI/z_ImageView+PHAssetSource.swift | 1 | 3433 | // File name prefixed with z_ to avoid compiler crash related to type extensions, nested types and order of Swift source files.
// TODO
// - allow passing PHImageRequestOptions, copy it and set .synchronous to false
// - allow using a custom PHImageManager, e.g. PHCachingImageManager
import Photos
import UIKit
public extension ImageView {
struct PHAssetSource: Source, Equatable {
public var asset: PHAsset
public init(asset: PHAsset) {
self.asset = asset
}
public func createSession() -> Session? {
return PHAssetSourceSession(source: self)
}
}
}
public func == (a: ImageView.PHAssetSource, b: ImageView.PHAssetSource) -> Bool {
return a.asset == b.asset
}
private final class PHAssetSourceSession: ImageView.Session {
fileprivate var lastRequestedContentMode: PHImageContentMode?
fileprivate var lastRequestedSize = CGSize()
fileprivate var listener: ImageView.SessionListener?
fileprivate var requestId: PHImageRequestID?
fileprivate let source: ImageView.PHAssetSource
fileprivate init(source: ImageView.PHAssetSource) {
self.source = source
}
fileprivate func imageViewDidChangeConfiguration(_ imageView: ImageView) {
startOrRestartRequestForImageView(imageView)
}
fileprivate func startOrRestartRequestForImageView(_ imageView: ImageView) {
let optimalSize = imageView.optimalImageSize.scale(by: imageView.optimalImageScale)
var size = self.lastRequestedSize
size.width = max(size.width, optimalSize.width)
size.height = max(size.height, optimalSize.height)
let contentMode: PHImageContentMode
switch imageView.scaling {
case .fitInside, .none:
contentMode = .aspectFit
case .fitHorizontally, .fitHorizontallyIgnoringAspectRatio, .fitIgnoringAspectRatio, .fitOutside, .fitVertically, .fitVerticallyIgnoringAspectRatio:
contentMode = .aspectFill
}
guard contentMode != lastRequestedContentMode || size != lastRequestedSize else {
return
}
stopRequest()
startRequestWithSize(size, contentMode: contentMode)
}
fileprivate func startRequestWithSize(_ size: CGSize, contentMode: PHImageContentMode) {
precondition(self.requestId == nil)
self.lastRequestedContentMode = contentMode
self.lastRequestedSize = size
let manager = PHImageManager.default()
let options = PHImageRequestOptions()
options.deliveryMode = .opportunistic
options.isNetworkAccessAllowed = true
options.resizeMode = .exact
options.isSynchronous = false
options.version = .current
requestId = manager.requestImage(for: source.asset, targetSize: size, contentMode: contentMode, options: options) { image, _ in
guard let image = image else {
return
}
let imageSize = image.size.scale(by: image.scale)
self.lastRequestedSize.width = max(self.lastRequestedSize.width, imageSize.width)
self.lastRequestedSize.height = max(self.lastRequestedSize.height, imageSize.height)
self.listener?.sessionDidRetrieveImage(image)
}
}
fileprivate func startRetrievingImageForImageView(_ imageView: ImageView, listener: ImageView.SessionListener) {
precondition(self.listener == nil)
self.listener = listener
self.startOrRestartRequestForImageView(imageView)
}
fileprivate func stopRetrievingImage() {
listener = nil
stopRequest()
}
fileprivate func stopRequest() {
guard let requestId = requestId else {
return
}
PHImageManager.default().cancelImageRequest(requestId)
self.requestId = nil
}
}
| mit | a9ad3f32618486ce9a71a4e48439da35 | 25.007576 | 150 | 0.767259 | 4.248762 | false | false | false | false |
mindz-eye/MYTableViewIndex | MYTableViewIndex/Private/IndexView.swift | 1 | 2646 | //
// IndexView.swift
// TableViewIndex
//
// Created by Makarov Yury on 02/05/16.
// Copyright © 2016 Makarov Yury. All rights reserved.
//
import UIKit
class IndexView : UIView {
private(set) var items: [UIView]?
private(set) var layout: ItemLayout<UIView>?
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
isUserInteractionEnabled = false
backgroundColor = UIColor.clear
}
// MARK: - Updates
public func reload(with items: [UIView], layout: ItemLayout<UIView>) {
let oldItems: [UIView] = self.items ?? []
self.items = items
self.layout = layout
for item in oldItems where !items.contains(item) {
removeItem(item)
}
for (index, item) in items.enumerated() where !oldItems.contains(item) {
addItem(item, withFrame: layout.frames[index])
}
setNeedsLayout()
}
private func removeItem(_ item: UIView) {
// A little trickery to make item removal look nice when performed inside an animation block
// (e.g. when the keyboard shows up)
CATransaction.setCompletionBlock {
item.alpha = 1
if let items = self.items, !items.contains(item) {
item.removeFromSuperview()
}
}
item.alpha = 0
}
private func addItem(_ item: UIView, withFrame frame: CGRect) {
addSubview(item)
// Make the item appear with a nice fade in animation when performed inside an animation block
// (e.g. when the keyboard shows up)
UIView.performWithoutAnimation {
item.frame = frame
item.alpha = 0
}
item.alpha = 1
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
guard let items = items, let layout = layout else {
return
}
for (index, item) in items.enumerated() {
item.frame = layout.frames[index]
}
}
override open var intrinsicContentSize: CGSize {
if let layout = layout {
return layout.size
} else {
return CGSize()
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: intrinsicContentSize.width, height: intrinsicContentSize.height)
}
}
| mit | 6938a76ac8e00ad338c6f086739921d8 | 25.717172 | 102 | 0.562571 | 4.765766 | false | false | false | false |
barteljan/RocketChatAdapter | Pod/Classes/RocketChatAdapter.swift | 1 | 8008 | //
// RocketChatAdapter.swift
// Pods
//
// Created by Jan Bartel on 12.03.16.
//
//
import VISPER_CommandBus
import SwiftDDP
import XCGLogger
public enum RocketChatAdapterError : ErrorType {
case ServerDidResponseWithEmptyResult(fileName:String,function: String,line: Int,column: Int)
case RequiredResponseFieldWasEmpty(field:String,fileName:String,function: String,line: Int,column: Int)
}
public struct RocketChatAdapter : RocketChatAdapterProtocol{
let commandBus : CommandBusProtocol
let endPoint : String
/**
* initialiser
**/
public init(endPoint:String){
self.init(endPoint:endPoint,commandBus: nil)
}
public init(endPoint:String,commandBus: CommandBusProtocol?){
self.endPoint = endPoint
if(commandBus != nil){
self.commandBus = commandBus!
}else{
self.commandBus = CommandBus()
}
}
/**
* Connect to server
**/
public func connect(endpoint:String,callback:(() -> ())?){
Meteor.client.logLevel = .Info
Meteor.connect(endpoint,callback: callback)
}
/**
* Register user
**/
public func register(email: String,name: String,password: String,completion: ((userId: String?, error: ErrorType?) -> Void)?){
let command = RegisterCommand(email: email, name: name, password: password)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(RegisterCommandHandler())
}
try! self.commandBus.process(command) { (result: String?, error: ErrorType?) -> Void in
completion?(userId: result,error: error)
}
}
/**
* Get username suggestion
**/
public func usernameSuggestion(completion:((username: String?,error:ErrorType?)->Void)?){
let command = GetUserNameSuggestionCommand()
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(GetUserNameSuggestionCommandHandler())
}
try! self.commandBus.process(command) { (result: String?, error: ErrorType?) -> Void in
completion?(username: result,error: error)
}
}
/**
* Set username
**/
public func setUsername(username:String,completion:((username: String?,error:ErrorType?)->Void)?){
let command = SetUserNameCommand(username:username)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(SetUsernameCommandHandler())
}
try! self.commandBus.process(command) { (result: String?, error: ErrorType?) -> Void in
completion?(username: result,error: error)
}
}
/**
* Send Forgot password email
**/
public func sendForgotPasswordEmail(usernameOrMail: String, completion:((result: Int?,error: ErrorType?)->Void)?){
let command = SendForgotPasswordEMailCommand(userNameOrMail: usernameOrMail)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(SendForgotPasswordEMailCommandHandler())
}
try! self.commandBus.process(command) { (result: Int?, error: ErrorType?) -> Void in
completion?(result: result,error: error)
}
}
/**
* Logon
**/
public func login(userNameOrEmail: String, password: String, completion:((result: AuthorizationResultProtocol?,error:ErrorType?)->Void)?){
let command = LogonCommand(userNameOrEmail:userNameOrEmail,password: password)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(LogonCommandHandler())
}
try! self.commandBus.process(command) { (result: AuthorizationResultProtocol?, error: ErrorType?) -> Void in
completion?(result:result,error: error)
}
}
/**
* get all public channels
**/
public func channelList(completion:((result: [ChannelProtocol]?,error: ErrorType?)->Void)?){
let command = GetChannelsCommand()
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(GetChannelsCommandHandler())
}
try! self.commandBus.process(command) { (result: [ChannelProtocol]?, error: ErrorType?) -> Void in
completion?(result: result, error: error)
}
}
/**
* get a channels id by its name
*/
public func getChannelId(name:String, completion:((roomId:String?, error: ErrorType?)->Void)?){
let command = GetRoomIdCommand(roomName: name)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(GetRoomIdCommandHandler())
}
try! self.commandBus.process(command) { (result: String?, error: ErrorType?) -> Void in
completion?(roomId: result, error: error)
}
}
/**
* Join a channel
**/
public func joinChannel(channelId: String,completion:((error:ErrorType?)->Void)?){
let command = JoinChannelCommand(channelId: channelId)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(JoinChannelCommandHandler())
}
try! self.commandBus.process(command) { (result: Any?, error: ErrorType?) -> Void in
completion?(error: error)
}
}
/**
* Leave a channel
**/
public func leaveChannel(channelId: String,completion:((error:ErrorType?)->Void)?){
let command = LeaveChannelCommand(channelId: channelId)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(LeaveChannelCommandHandler())
}
try! self.commandBus.process(command) { (result: Any?, error: ErrorType?) -> Void in
completion?(error: error)
}
}
/**
* Get messages of a channel
**/
public func channelMessages(channelId : String, numberOfMessages:Int, start: NSDate?, end: NSDate?, completion: ((result: MessageHistoryResultProtocol?, error: ErrorType?)->Void)?){
let command = GetChannelHistoryCommand(channelId: channelId,numberOfMessages: numberOfMessages,start: start, end: end)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(GetChannelHistoryCommandHandler(parser: MessageParser()))
}
try! self.commandBus.process(command) { (result: MessageHistoryResult?, error: ErrorType?) -> Void in
completion?(result: result,error: error)
}
}
/**
* Send a message in a channel
**/
public func sendMessage(channelId : String,message: String, completion: ((result: Message?, error: ErrorType?) -> Void)?){
let command = SendMessageCommand(channelId: channelId, message: message)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(SendMessageCommandHandler(parser:MessageParser()))
}
try! self.commandBus.process(command) { (result: Message?, error: ErrorType?) -> Void in
completion?(result: result,error: error)
}
}
/**
* Set user status
**/
public func setUserStatus(userStatus: UserStatus,completion: ((error:ErrorType?)->Void)?){
let command = SetUserStatusCommand(userStatus: userStatus)
if(!self.commandBus.isResponsible(command)){
self.commandBus.addHandler(UserStatusCommandHandler())
}
try! self.commandBus.process(command) { (result: Any?, error: ErrorType?) -> Void in
completion?(error: error)
}
}
}
| mit | 6c1674cdc76232562f8f082070200230 | 29.681992 | 185 | 0.600899 | 4.786611 | false | false | false | false |
keyOfVv/KEYExtension | KEYExtension/sources/UIFontExtension.swift | 1 | 2487 | //
// UIFontExtension.swift
// alpha
//
// Created by keyOfVv on 1/11/16.
// Copyright © 2016 com.keyofvv. All rights reserved.
//
import UIKit
// MARK: - UIFont扩展
public extension UIFont {
/**
字体名称枚举
- Noteworthy: Noteworthy字体
- NoteworthyBold: Noteworthy-Bold字体
- HelveticaNeueLight: HelveticaNeue-Light字体
- HelveticaNeueThin: HelveticaNeue-Thin字体
*/
public enum Name: String {
case Noteworthy = "Noteworthy"
case NoteworthyBold = "Noteworthy-Bold"
case HelveticaNeue = "HelveticaNeue"
case HelveticaNeueBold = "HelveticaNeue-Bold"
case HelveticaNeueMedium = "HelveticaNeue-Medium"
case HelveticaNeueLight = "HelveticaNeue-Light"
case HelveticaNeueThin = "HelveticaNeue-Thin"
case HelveticaNeueUltraLight = "HelveticaNeue-UltraLight"
case Papyrus = "Papyrus"
}
/**
快速构造方法
- parameter fontName: 字体名称
- parameter size: 字体大小
- returns: UIFont对象
*/
public convenience init?(fontName: Name, size: Double) {
self.init(name: fontName.rawValue, size: size.cgFloat)
}
/**
创建指定大小的Noteworthy字体对象
- parameter size: 字体大小
- returns: 返回一个指定大小的Noteworthy字体对象
*/
public class func noteworthy(_ size: Double) -> UIFont {
return UIFont(fontName: Name.Noteworthy, size: size)!
}
/**
创建指定大小的Noteworthy-Bold字体对象
- parameter size: 字体大小
- returns: 返回一个指定大小的Noteworthy-Bold字体对象
*/
public class func noteworthyBold(_ size: Double) -> UIFont {
return UIFont(fontName: Name.NoteworthyBold, size: size)!
}
/**
创建指定大小的HelveticaNeue-Light字体对象
- parameter size: 字体大小
- returns: 返回一个指定大小的HelveticaNeue-Light字体对象
*/
public class func helveticaNeueLight(_ size: Double) -> UIFont {
return UIFont(fontName: Name.HelveticaNeueLight, size: size)!
}
/**
创建指定大小的HelveticaNeue-Thin字体对象
- parameter size: 字体大小
- returns: 返回一个指定大小的HelveticaNeue-Thin字体对象
*/
public class func helveticaNeueThin(_ size: Double) -> UIFont {
return UIFont(fontName: Name.HelveticaNeueThin, size: size)!
}
public class func helveticaNeue(_ size: Double) -> UIFont {
return UIFont(fontName: Name.HelveticaNeue, size: size)!
}
public class func papyrus(_ size: Double) -> UIFont {
return UIFont(fontName: Name.Papyrus, size: size)!
}
}
| mit | cc04f0da34f98e2fd0d8a388b9dce42e | 20.762376 | 65 | 0.72202 | 3.381538 | false | false | false | false |
MingLoan/PageTabBarController | sources/PageTabBarItem.swift | 1 | 9360 | //
// PageTabBarItem.swift
// PageTabBarController
//
// Created by Keith Chan on 4/9/2017.
// Copyright © 2017 com.mingloan. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
protocol PageTabBarItemDelegate: NSObjectProtocol {
func pageTabBarItemDidTap(_ item: PageTabBarItem)
}
internal enum PageTabBarItemType {
case text
case icon
}
private class PageTabBarButton: UIButton {
fileprivate var pageTabBarItemType = PageTabBarItemType.text
override var intrinsicContentSize: CGSize {
// use natural size
if designatedContentSize.equalTo(.zero) {
return super.intrinsicContentSize
}
switch pageTabBarItemType {
case .text:
return CGSize(width: super.intrinsicContentSize.width, height: designatedContentSize.height)
case .icon:
return designatedContentSize
}
}
fileprivate var designatedContentSize: CGSize = .zero {
didSet {
invalidateIntrinsicContentSize()
}
}
fileprivate var color: UIColor? = UIColor.lightGray
fileprivate var selectedColor: UIColor? = UIColor.blue
override var isHighlighted: Bool {
didSet {
switch pageTabBarItemType {
case .text:
alpha = isHighlighted ? 0.5 : 1.0
break
case .icon:
if isHighlighted {
tintColor = isSelected ? selectedColor?.withAlphaComponent(0.5) : color?.withAlphaComponent(0.5)
}
else {
tintColor = isSelected ? selectedColor : color
}
break
}
}
}
override var isSelected: Bool {
didSet {
switch pageTabBarItemType {
case .text:
break
case .icon:
tintColor = isSelected ? selectedColor : color
break
}
}
}
}
@objcMembers
open class PageTabBarItem: UIView {
public struct AppearanceSettings {
public var font: UIFont
public var unselectedColor: UIColor?
public var selectedColor: UIColor?
public var contentHeight: CGFloat
public var offset: CGSize
public static let automaticDimemsion = CGFloat(0)
}
public static var defaultAppearanceSettings = AppearanceSettings(font: UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium),
unselectedColor: UIColor.lightGray,
selectedColor: UIApplication.shared.delegate?.window??.tintColor,
contentHeight: AppearanceSettings.automaticDimemsion,
offset: .zero)
open var appearance: AppearanceSettings = PageTabBarItem.defaultAppearanceSettings {
didSet {
tabBarButton.titleLabel?.font = appearance.font
tabBarButton.color = appearance.unselectedColor
tabBarButton.selectedColor = appearance.selectedColor
tabBarButton.setTitleColor(appearance.unselectedColor, for: .normal)
tabBarButton.setTitleColor(appearance.selectedColor, for: .selected)
switch type {
case .text:
tabBarButton.designatedContentSize = CGSize(width: AppearanceSettings.automaticDimemsion, height: appearance.contentHeight)
break
case .icon:
tabBarButton.designatedContentSize = CGSize(width: appearance.contentHeight, height: appearance.contentHeight)
break
}
tabBarButtonHorizontalOffsetConstraint?.constant = appearance.offset.width
tabBarButtonVerticalOffsetConstraint?.constant = appearance.offset.height
layoutIfNeeded()
}
}
internal var isSelected = false {
didSet {
tabBarButton.isSelected = isSelected
}
}
internal var tabBarButtonContentWidth: CGFloat {
return tabBarButton.bounds.width
}
internal var badgeCount = 0 {
didSet {
badgeView.badgeValue = badgeCount
}
}
internal var delegate: PageTabBarItemDelegate?
private let tabBarButton: PageTabBarButton = {
let button = PageTabBarButton(type: .custom)
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.contentEdgeInsets = .zero
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
public let badgeView: Badge = {
let badgeView = Badge(type: .number)
badgeView.translatesAutoresizingMaskIntoConstraints = false
return badgeView
}()
private var type = PageTabBarItemType.text
// MARK: Layout Constraints
private var tabBarButtonVerticalOffsetConstraint: NSLayoutConstraint?
private var tabBarButtonHorizontalOffsetConstraint: NSLayoutConstraint?
public convenience init(title: String?) {
self.init(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
type = .text
tabBarButton.pageTabBarItemType = .text
tabBarButton.setTitle(title, for: .normal)
tabBarButton.titleLabel?.font = appearance.font
tabBarButton.setTitleColor(appearance.unselectedColor, for: .normal)
tabBarButton.setTitleColor(appearance.selectedColor, for: .selected)
tabBarButton.designatedContentSize = CGSize(width: AppearanceSettings.automaticDimemsion, height: appearance.contentHeight)
commonInit()
}
public convenience init(unselectedImage: UIImage?, selectedImage: UIImage?) {
self.init(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
type = .icon
tabBarButton.pageTabBarItemType = .icon
tabBarButton.setTitle("", for: .normal)
tabBarButton.setImage(unselectedImage?.withRenderingMode(.alwaysTemplate), for: .normal)
tabBarButton.setImage(selectedImage?.withRenderingMode(.alwaysTemplate), for: .selected)
tabBarButton.imageView?.contentMode = .scaleAspectFit
tabBarButton.designatedContentSize = CGSize(width: appearance.contentHeight, height: appearance.contentHeight)
tabBarButton.tintColor = appearance.unselectedColor
commonInit()
}
private func commonInit() {
backgroundColor = .clear
tabBarButton.color = appearance.unselectedColor
tabBarButton.selectedColor = appearance.selectedColor
tabBarButton.addTarget(self, action: #selector(press(_:)), for: .touchUpInside)
addSubview(tabBarButton)
tabBarButtonHorizontalOffsetConstraint = tabBarButton.centerXAnchor.constraint(equalTo: centerXAnchor, constant: appearance.offset.width)
tabBarButtonHorizontalOffsetConstraint?.isActive = true
tabBarButtonVerticalOffsetConstraint = tabBarButton.centerYAnchor.constraint(equalTo: centerYAnchor, constant: appearance.offset.height)
tabBarButtonVerticalOffsetConstraint?.isActive = true
addSubview(badgeView)
if case .icon = type {
badgeView.topAnchor.constraint(equalTo: topAnchor, constant: 4).isActive = true
badgeView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -4).isActive = true
} else {
badgeView.centerYAnchor.constraint(equalTo: tabBarButton.centerYAnchor).isActive = true
badgeView.leadingAnchor.constraint(equalTo: tabBarButton.trailingAnchor, constant: 6).isActive = true
}
}
@objc private func press(_ sender: UIButton) {
delegate?.pageTabBarItemDidTap(self)
}
override open func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let hitTestView = super.hitTest(point, with: event), hitTestView == self {
return tabBarButton
}
return super.hitTest(point, with: event)
}
}
| mit | dc15d76becb103c01099761ff379205e | 36.890688 | 145 | 0.640667 | 5.524793 | false | false | false | false |
roelspruit/RSMetronome | Sources/RSMetronome/Metronome.swift | 1 | 1669 | //
// Metronome.swift
//
// Created by Roel Spruit on 16/10/15.
// Copyright © 2015 DinkyWonder. All rights reserved.
//
import Foundation
public class Metronome {
public var settings: Settings = Settings() {
didSet{
patternPlayer?.settings = settings
}
}
var beatListener: ((_ beatType: BeatType, _ index: Int) -> ())?
var stateListener: ((_ playing: Bool) -> ())?
private var patternPlayer: PatternPlayer?
private var soundSet = SoundSet.cowbell
public init(stateListener: ((_ playing: Bool) -> ())? = nil, beatListener: ((_ beatType: BeatType, _ index: Int) -> ())? = nil){
self.beatListener = beatListener
self.stateListener = stateListener
}
/// Start the metronome
public func start(){
// Make sure it's stopped first
stop()
patternPlayer = PatternPlayer(settings: settings, soundSet: soundSet)
patternPlayer?.stateListener = stateListener
patternPlayer?.beatListener = beatListener
patternPlayer?.play()
}
/// Stop the metronome
public func stop(){
if let player = patternPlayer {
player.stop()
}
}
/// Toggle the playing of the metronome
public func toggle(){
if isPlaying {
stop()
}else{
start()
}
}
/// Returns a boolean indicating if the metronome is currently playing
public var isPlaying: Bool {
if let player = patternPlayer {
return player.isPlaying
}
return false
}
}
| mit | 900222f2b708367d700962012af97db0 | 23.173913 | 132 | 0.559952 | 4.820809 | false | false | false | false |
Journey321/xiaorizi | Pods/Kingfisher/Sources/String+MD5.swift | 8 | 9688 | //
// String+MD5.swift
// Kingfisher
//
// This file is stolen from HanekeSwift: https://github.com/Haneke/HanekeSwift/blob/master/Haneke/CryptoSwiftMD5.swift
// which is a modified version of CryptoSwift:
//
// To date, adding CommonCrypto to a Swift framework is problematic. See:
// http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework
// We're using a subset of CryptoSwift as a (temporary?) alternative.
// The following is an altered source version that only includes MD5. The original software can be found at:
// https://github.com/krzyzanowskim/CryptoSwift
// This is the original copyright notice:
/*
Copyright (C) 2014 Marcin Krzyżanowski <[email protected]>
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
- This notice may not be removed or altered from any source or binary distribution.
*/
import Foundation
extension String {
var kf_MD5: String {
if let data = dataUsingEncoding(NSUTF8StringEncoding) {
let MD5Calculator = MD5(Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length)))
let MD5Data = MD5Calculator.calculate()
let MD5String = NSMutableString()
for c in MD5Data {
MD5String.appendFormat("%02x", c)
}
return MD5String as String
} else {
return self
}
}
}
/** array of bytes, little-endian representation */
func arrayOfBytes<T>(value: T, length: Int? = nil) -> [UInt8] {
let totalBytes = length ?? (sizeofValue(value) * 8)
let valuePointer = UnsafeMutablePointer<T>.alloc(1)
valuePointer.memory = value
let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer)
var bytes = [UInt8](count: totalBytes, repeatedValue: 0)
for j in 0..<min(sizeof(T), totalBytes) {
bytes[totalBytes - 1 - j] = (bytesPointer + j).memory
}
valuePointer.destroy()
valuePointer.dealloc(1)
return bytes
}
extension Int {
/** Array of bytes with optional padding (little-endian) */
func bytes(totalBytes: Int = sizeof(Int)) -> [UInt8] {
return arrayOfBytes(self, length: totalBytes)
}
}
extension NSMutableData {
/** Convenient way to append bytes */
func appendBytes(arrayOfBytes: [UInt8]) {
appendBytes(arrayOfBytes, length: arrayOfBytes.count)
}
}
protocol HashProtocol {
var message: Array<UInt8> { get }
/** Common part for hash calculation. Prepare header data. */
func prepare(len: Int) -> Array<UInt8>
}
extension HashProtocol {
func prepare(len: Int) -> Array<UInt8> {
var tmpMessage = message
// Step 1. Append Padding Bits
tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
var msgLength = tmpMessage.count
var counter = 0
while msgLength % len != (len - 8) {
counter += 1
msgLength += 1
}
tmpMessage += Array<UInt8>(count: counter, repeatedValue: 0)
return tmpMessage
}
}
func toUInt32Array(slice: ArraySlice<UInt8>) -> Array<UInt32> {
var result = Array<UInt32>()
result.reserveCapacity(16)
for idx in slice.startIndex.stride(to: slice.endIndex, by: sizeof(UInt32)) {
let d0 = UInt32(slice[idx.advancedBy(3)]) << 24
let d1 = UInt32(slice[idx.advancedBy(2)]) << 16
let d2 = UInt32(slice[idx.advancedBy(1)]) << 8
let d3 = UInt32(slice[idx])
let val: UInt32 = d0 | d1 | d2 | d3
result.append(val)
}
return result
}
struct BytesGenerator: GeneratorType {
let chunkSize: Int
let data: [UInt8]
init(chunkSize: Int, data: [UInt8]) {
self.chunkSize = chunkSize
self.data = data
}
var offset = 0
mutating func next() -> ArraySlice<UInt8>? {
let end = min(chunkSize, data.count - offset)
let result = data[offset..<offset + end]
offset += result.count
return result.count > 0 ? result : nil
}
}
struct BytesSequence: SequenceType {
let chunkSize: Int
let data: [UInt8]
func generate() -> BytesGenerator {
return BytesGenerator(chunkSize: chunkSize, data: data)
}
}
func rotateLeft(value: UInt32, bits: UInt32) -> UInt32 {
return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits))
}
class MD5: HashProtocol {
static let size = 16 // 128 / 8
let message: [UInt8]
init (_ message: [UInt8]) {
self.message = message
}
/** specifies the per-round shift amounts */
private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391]
private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
func calculate() -> [UInt8] {
var tmpMessage = prepare(64)
tmpMessage.reserveCapacity(tmpMessage.count + 4)
// hash values
var hh = hashes
// Step 2. Append Length a 64-bit representation of lengthInBits
let lengthInBits = (message.count * 8)
let lengthBytes = lengthInBits.bytes(64 / 8)
tmpMessage += lengthBytes.reverse()
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
var M = toUInt32Array(chunk)
assert(M.count == 16, "Invalid array")
// Initialize hash value for this chunk:
var A: UInt32 = hh[0]
var B: UInt32 = hh[1]
var C: UInt32 = hh[2]
var D: UInt32 = hh[3]
var dTemp: UInt32 = 0
// Main loop
for j in 0 ..< sines.count {
var g = 0
var F: UInt32 = 0
switch j {
case 0...15:
F = (B & C) | ((~B) & D)
g = j
break
case 16...31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32...47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48...63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j])
A = dTemp
}
hh[0] = hh[0] &+ A
hh[1] = hh[1] &+ B
hh[2] = hh[2] &+ C
hh[3] = hh[3] &+ D
}
var result = [UInt8]()
result.reserveCapacity(hh.count / 4)
hh.forEach {
let itemLE = $0.littleEndian
result += [UInt8(itemLE & 0xff), UInt8((itemLE >> 8) & 0xff), UInt8((itemLE >> 16) & 0xff), UInt8((itemLE >> 24) & 0xff)]
}
return result
}
}
| mit | f3e2d952797d75e0b35648eb9ea93530 | 34.988848 | 213 | 0.54922 | 3.831025 | false | false | false | false |
necrowman/CRLAlamofireFuture | Examples/SimpleTvOSCarthage/Carthage/Checkouts/Future/Future/TaskChain.swift | 111 | 1725 | //===--- TaskChain.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
import Boilerplate
import ExecutionContext
internal let admin = ExecutionContext(kind: .serial)
internal class TaskChain {
typealias ContextTask = (ExecutionContextType)->Void
private let head:ContextTask
private var nextTail:MutableAnyContainer<ContextTask?>
init() {
let tail = MutableAnyContainer<ContextTask?>(nil)
head = { context in
tail.content?(context)
}
nextTail = tail
}
func perform(context:ExecutionContextType) {
admin.execute {
context.execute {
self.head(context)
}
}
}
/// you have to handle calling next yourself
func append(f:(AnyContainer<ContextTask?>)->ContextTask) {
let tail = MutableAnyContainer<ContextTask?>(nil)
let task = f(tail)
admin.execute {
self.nextTail.content = task
self.nextTail = tail
}
}
} | mit | 2d15d2187d709b5349e1a2f08c2c913f | 30.381818 | 84 | 0.607536 | 4.831933 | false | false | false | false |
citysite102/kapi-kaffeine | kapi-kaffeine/kapi-kaffeine/KPEditCommentController.swift | 1 | 10227 | //
// KPEditCommentController.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/8/16.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import UIKit
class KPEditCommentController: KPViewController {
static let commentMaximumTextLength: Int = 200
var containerView: UIView!
var dismissButton: KPBounceButton!
var sendButton: UIButton!
var textFieldContainerView: UIView!
var defaultCommentModel: KPCommentModel!
var inputTextView: UITextView!
var placeholderLabel: UILabel!
var paragraphStyle: NSMutableParagraphStyle!
var tapGesture: UITapGestureRecognizer!
lazy var textFieldHeaderLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12.0)
label.textColor = KPColorPalette.KPTextColor.mainColor
label.text = "請留下你的評論"
return label
}()
lazy var remainingTextLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12.0)
label.textColor = KPColorPalette.KPTextColor.mainColor
label.text = "0/\(commentMaximumTextLength)"
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
navigationItem.title = "修改評論"
navigationItem.hidesBackButton = true
dismissButton = KPBounceButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30),
image: R.image.icon_back()!)
dismissButton.contentEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3)
dismissButton.tintColor = KPColorPalette.KPTextColor.whiteColor;
dismissButton.addTarget(self,
action: #selector(KPNewCommentController.handleDismissButtonOnTapped),
for: .touchUpInside)
let barItem = UIBarButtonItem(customView: dismissButton);
sendButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 24));
sendButton.setTitle("修改", for: .normal)
sendButton.isEnabled = false
sendButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
sendButton.tintColor = KPColorPalette.KPTextColor.mainColor;
sendButton.addTarget(self,
action: #selector(KPNewCommentController.handleSendButtonOnTapped),
for: .touchUpInside)
let rightbarItem = UIBarButtonItem(customView: sendButton);
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace,
target: nil,
action: nil)
let rightNegativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace,
target: nil,
action: nil)
rightbarItem.isEnabled = false
negativeSpacer.width = -5
rightNegativeSpacer.width = -8
navigationItem.leftBarButtonItems = [negativeSpacer, barItem]
navigationItem.rightBarButtonItems = [rightNegativeSpacer, rightbarItem]
containerView = UIView()
containerView.backgroundColor = KPColorPalette.KPBackgroundColor.grayColor_level7
view.addSubview(containerView)
containerView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
textFieldContainerView = UIView()
textFieldContainerView.backgroundColor = UIColor.white
containerView.addSubview(textFieldContainerView)
textFieldContainerView.addConstraints(fromStringArray: ["V:|[$self(240)]",
"H:|[$self]|"])
textFieldContainerView.addConstraintForHavingSameWidth(with: view)
tapGesture = UITapGestureRecognizer(target: self,
action: #selector(handleTapGesture(tapGesture:)))
textFieldContainerView.addGestureRecognizer(tapGesture)
textFieldContainerView.addSubview(textFieldHeaderLabel)
textFieldHeaderLabel.addConstraints(fromStringArray: ["V:|-16-[$self]",
"H:|-16-[$self]"])
paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4.0
inputTextView = UITextView()
inputTextView.delegate = self
inputTextView.returnKeyType = .done
inputTextView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
inputTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0)
inputTextView.typingAttributes = [NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: UIFont.systemFont(ofSize: 17),
NSForegroundColorAttributeName: KPColorPalette.KPTextColor.grayColor_level2!]
inputTextView.text = defaultCommentModel?.content ?? ""
textFieldContainerView.addSubview(inputTextView)
inputTextView.addConstraints(fromStringArray: ["V:[$view0]-8-[$self]-40-|",
"H:|-12-[$self]-16-|"],
views: [textFieldHeaderLabel])
placeholderLabel = UILabel()
placeholderLabel.isHidden = (defaultCommentModel != nil)
placeholderLabel.font = UIFont.systemFont(ofSize: 17)
placeholderLabel.textColor = KPColorPalette.KPTextColor.grayColor_level4
placeholderLabel.text = "Ex:東西很好吃,環境也很舒適..."
textFieldContainerView.addSubview(placeholderLabel)
placeholderLabel.addConstraints(fromStringArray: ["V:[$view0]-8-[$self]",
"H:|-16-[$self]-16-|"],
views: [textFieldHeaderLabel])
textFieldContainerView.addSubview(remainingTextLabel)
remainingTextLabel.addConstraints(fromStringArray: ["V:[$self]-16-|",
"H:[$self]-16-|"])
remainingTextLabel.setText(text: "\(defaultCommentModel?.content?.count ?? 0)/\(KPEditCommentController.commentMaximumTextLength)")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
sendButton.alpha = (inputTextView.text.count > 0 &&
inputTextView.text != defaultCommentModel?.content) ?
1.0 : 0.6
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
inputTextView.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func handleResignTapGesture(_ tapGesture: UITapGestureRecognizer) {
if inputTextView.isFirstResponder {
inputTextView.resignFirstResponder()
}
}
func handleDismissButtonOnTapped() {
navigationController?.popViewController(animated: true)
}
func handleSendButtonOnTapped() {
inputTextView.resignFirstResponder()
// KPPopoverView.popoverUnsupportedView()
KPServiceHandler.sharedHandler.modifyComment(inputTextView.text, defaultCommentModel.commentID, { (successed) in
if successed {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0,
execute: {
self.navigationController?.popViewController(animated: true)
})
}
})
}
func handleTapGesture(tapGesture: UITapGestureRecognizer) {
if inputTextView.isFirstResponder {
inputTextView.resignFirstResponder()
} else {
inputTextView.becomeFirstResponder()
}
}
func textViewDidChange(_ textView: UITextView) {
placeholderLabel.isHidden = textView.text.count > 0 ? true : false
remainingTextLabel.text = "\((textView.text! as NSString).length)/200"
}
func textViewDidBeginEditing(_ textView: UITextView) {
UIView.animate(withDuration: 0.1,
animations: {
self.placeholderLabel.alpha = 0
}) { (_) in
self.placeholderLabel.isHidden = true
self.placeholderLabel.alpha = 1.0
}
}
func textViewDidEndEditing(_ textView: UITextView) {
placeholderLabel.isHidden = textView.text.count > 0 ? true : false
}
/*
// 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.
}
*/
}
extension KPEditCommentController: UITextViewDelegate {
func textView(_ textView: UITextView,
shouldChangeTextIn range: NSRange,
replacementText text: String) -> Bool {
let textContent = textView.text! as NSString
let oldLength = textContent.length
let replacementLength = (text as NSString).length
let rangeLength = range.length
let newLength = oldLength - rangeLength + replacementLength
let returnKey = (text as NSString).range(of: "\n").location == NSNotFound
sendButton.isEnabled = newLength > 0
sendButton.alpha = (newLength > 0 &&
inputTextView.text != defaultCommentModel?.content) ?
1.0 : 0.6
if !returnKey {
textView.resignFirstResponder()
return false
}
return newLength <= KPEditCommentController.commentMaximumTextLength && returnKey
}
}
| mit | 6e95427b373c4d431ec9089e436711d4 | 40.190283 | 139 | 0.599961 | 5.922002 | false | false | false | false |
practicalswift/swift | test/Generics/conditional_conformances_literals.swift | 1 | 5458 | // RUN: %target-typecheck-verify-swift -typecheck -verify
// rdar://problem/38461036 , https://bugs.swift.org/browse/SR-7192 and highlights the real problem in https://bugs.swift.org/browse/SR-6941
protocol SameType {}
protocol Conforms {}
struct Works: Hashable, Conforms {}
struct Fails: Hashable {}
extension Array: SameType where Element == Works {}
// expected-note@-1 2 {{requirement from conditional conformance of '[Fails]' to 'SameType'}}
extension Dictionary: SameType where Value == Works {}
// expected-note@-1 2 {{requirement from conditional conformance of '[Int : Fails]' to 'SameType'}}
extension Array: Conforms where Element: Conforms {}
// expected-note@-1 5 {{requirement from conditional conformance of '[Fails]' to 'Conforms'}}
extension Dictionary: Conforms where Value: Conforms {}
// expected-note@-1 3 {{requirement from conditional conformance of '[Int : Fails]' to 'Conforms'}}
let works = Works()
let fails = Fails()
func arraySameType() {
let arrayWorks = [works]
let arrayFails = [fails]
let _: SameType = [works]
let _: SameType = [fails]
// expected-error@-1 {{value of type '[Fails]' does not conform to specified type 'SameType'}}
let _: SameType = arrayWorks
let _: SameType = arrayFails
// expected-error@-1 {{protocol 'SameType' requires the types 'Fails' and 'Works' be equivalent}}
let _: SameType = [works] as [Works]
let _: SameType = [fails] as [Fails]
// expected-error@-1 {{protocol 'SameType' requires the types 'Fails' and 'Works' be equivalent}}
let _: SameType = [works] as SameType
let _: SameType = [fails] as SameType
// expected-error@-1 {{'[Fails]' is not convertible to 'SameType'}}
let _: SameType = arrayWorks as SameType
let _: SameType = arrayFails as SameType
// expected-error@-1 {{'[Fails]' is not convertible to 'SameType'}}
}
func dictionarySameType() {
let dictWorks: [Int : Works] = [0 : works]
let dictFails: [Int : Fails] = [0 : fails]
let _: SameType = [0 : works]
let _: SameType = [0 : fails]
// expected-error@-1 {{contextual type 'SameType' cannot be used with dictionary literal}}
let _: SameType = dictWorks
let _: SameType = dictFails
// expected-error@-1 {{protocol 'SameType' requires the types 'Fails' and 'Works' be equivalent}}
let _: SameType = [0 : works] as [Int : Works]
let _: SameType = [0 : fails] as [Int : Fails]
// expected-error@-1 {{protocol 'SameType' requires the types 'Fails' and 'Works' be equivalent}}
let _: SameType = [0 : works] as SameType
let _: SameType = [0 : fails] as SameType
// expected-error@-1 {{'[Int : Fails]' is not convertible to 'SameType'}}
let _: SameType = dictWorks as SameType
let _: SameType = dictFails as SameType
// expected-error@-1 {{'[Int : Fails]' is not convertible to 'SameType'}}
}
func arrayConforms() {
let arrayWorks = [works]
let arrayFails = [fails]
let _: Conforms = [works]
let _: Conforms = [fails]
// expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}}
let _: Conforms = arrayWorks
let _: Conforms = arrayFails
// expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}}
let _: Conforms = [works] as [Works]
let _: Conforms = [fails] as [Fails]
// expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}}
let _: Conforms = [works] as Conforms
let _: Conforms = [fails] as Conforms
// expected-error@-1 {{'[Fails]' is not convertible to 'Conforms'}}
let _: Conforms = arrayWorks as Conforms
let _: Conforms = arrayFails as Conforms
// expected-error@-1 {{'[Fails]' is not convertible to 'Conforms'}}
}
func dictionaryConforms() {
let dictWorks: [Int : Works] = [0 : works]
let dictFails: [Int : Fails] = [0 : fails]
let _: Conforms = [0 : works]
let _: Conforms = [0 : fails]
// expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}}
let _: Conforms = dictWorks
let _: Conforms = dictFails
// expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}}
let _: Conforms = [0 : works] as [Int : Works]
let _: Conforms = [0 : fails] as [Int : Fails]
// expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}}
let _: Conforms = [0 : works] as Conforms
let _: Conforms = [0 : fails] as Conforms
// expected-error@-1 {{'[Int : Fails]' is not convertible to 'Conforms'}}
let _: Conforms = dictWorks as Conforms
let _: Conforms = dictFails as Conforms
// expected-error@-1 {{'[Int : Fails]' is not convertible to 'Conforms'}}
}
func combined() {
let _: Conforms = [[0: [1 : [works]]]]
let _: Conforms = [[0: [1 : [fails]]]]
// expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}}
// Needs self conforming protocols:
let _: Conforms = [[0: [1 : [works]] as Conforms]]
// expected-error@-1 {{protocol type 'Conforms' cannot conform to 'Conforms' because only concrete types can conform to protocols}}
let _: Conforms = [[0: [1 : [fails]] as Conforms]]
// expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}}
// expected-error@-2 {{protocol type 'Conforms' cannot conform to 'Conforms' because only concrete types can conform to protocols}}
}
| apache-2.0 | d5a73a6fd15481f2d5f084ca9c60a095 | 39.42963 | 139 | 0.649689 | 3.937951 | false | false | false | false |
Gilbertat/SYKanZhiHu | SYKanZhihu/SYKanZhihu/Class/User/Controller/SYUserViewController.swift | 1 | 3891 | //
// SYUserViewController.swift
// SYKanZhihu
//
// Created by shiyue on 16/2/25.
// Copyright © 2016年 shiyue. All rights reserved.
//
import UIKit
class SYUserViewController: UIViewController {
var userHash = "" //请求数据需要
var infoModel:userModel!
var dataSource:Array<ConsentModel> = Array()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.infoModel = userModel()
tableView.estimatedRowHeight = 170
tableView.rowHeight = UITableViewAutomaticDimension
tableView.isUserInteractionEnabled = true
requestData(userHash)
}
func requestData(_ userHash:String) {
let url = "\(ApiConfig.API_User_Url)\(userHash)"
SYHttp.get(url, params:nil, success: { (json) -> Void in
let data = try? JSONSerialization.jsonObject(with: json as! Data, options: [])
let infoDict:NSDictionary = data as! NSDictionary
let extraModel:NSDictionary = infoDict["detail"] as! NSDictionary
let consentArray:NSArray = infoDict["topanswers"] as! NSArray
for dict in consentArray {
let consentModel:ConsentModel = ConsentModel(dict: dict as! NSDictionary)
self.dataSource.append(consentModel)
}
self.infoModel = userModel(info: infoDict, extra: extraModel)
DispatchQueue.main.async { () -> Void in
self.tableView.reloadData()
}
}) { (error) -> Void in
print(error)
}
}
//跳转到用户主页
@IBAction func homePage(_ sender: AnyObject) {
let url = "\(ApiConfig.API_ZhPersonal_Url)/\(self.userHash)"
UIApplication.shared.openURL(URL(string: url)!)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "consent" {
let destinationViewController = segue.destination as! SYConsentViewController
destinationViewController.dataSource = self.dataSource
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension SYUserViewController:UITableViewDataSource,UITableViewDelegate
{
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if 1 == (indexPath as NSIndexPath).section {
return 44
}
else {
return UITableViewAutomaticDimension
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath as NSIndexPath).section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "userState", for: indexPath) as! SYUserTableViewCell
if self.infoModel.name == nil {
} else {
cell.receiveUserModel(self.infoModel)
}
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "userTict", for: indexPath) as! SYHighAnswerTableViewCell
return cell
}
}
}
| mit | 2f32608021e1f71927f9079129318715 | 28.937984 | 126 | 0.598136 | 5.326897 | false | false | false | false |
apple/swift-driver | Tests/IncrementalTestFramework/Source.swift | 1 | 1968 | //===----------- PhasedSources.swift - Swift Testing --------------===//
//
// 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 XCTest
import TSCBasic
@_spi(Testing) import SwiftDriver
import SwiftOptions
import TestUtilities
/// A source file to be used in an incremental test.
/// User edits can be simulated by using `AddOn`s.
public struct Source: Hashable, Comparable {
/// E.g. "main" for "main.swift"
public let name: String
/// The code in the file, including any `AddOn` markers.
let contents: String
public init(named name: String, containing contents: String) {
self.name = name
self.contents = contents
}
/// Produce a Source from a Fixture
/// - Parameters:
/// - named: E.g. "foo" for "foo.swift"
/// - relativePath: The relative path of the subdirectory under
/// `<package-root>/TestInputs`
/// - fileSystem: The filesystem on which to search.
/// - Returns: A Source with the given name and contents from the file
public init?(named name: String,
at relativePath: RelativePath,
on fileSystem: FileSystem = localFileSystem) throws {
guard let absPath = Fixture.fixturePath(at: relativePath,
for: "\(name).swift",
on: fileSystem)
else {
return nil
}
let contents = try fileSystem.readFileContents(absPath).cString
self.init(named: name, containing: contents)
}
public static func < (lhs: Source, rhs: Source) -> Bool {
lhs.name < rhs.name
}
}
| apache-2.0 | 553d8d0c056863a9480d655bc210b566 | 32.931034 | 80 | 0.613313 | 4.503432 | false | true | false | false |
Alex-ZHOU/XYQSwift | XYQSwiftTests/Learn-from-Imooc/Play-with-Swift-2/02-Basics/01-Constants-and-Variables.playground/Contents.swift | 1 | 679 | //
// 2-1 Swift 2.0基本类型之常量、变量和声明
// 01-Constants-and-Variables.playground
//
// Created by AlexZHOU on 16/05/2017.
// Copyright © 2016年 AlexZHOU. All rights reserved.
//
import UIKit
var str = "01-Constants-and-Variables"
print(str)
let maxNum = 1000
// 常量不可以被改变
//maxNum = 0
var index = 2
// 变量可以被改变
index = 3
// 可以一次声明多个变量(或常量)
var x = 1 , y = 2 , z = 3
// Swift语言是强类型语言
//x = "Hello"
// 显式的声明变量类型
var websiteName: String = "www.imooc.com"
websiteName = "www.liuyubobobo.com"
// 一次为多个变量显式声明类型
var a , b , c: Double
| apache-2.0 | 25e431e4191662d6f5df3bd152a54655 | 14.588235 | 52 | 0.664151 | 2.465116 | false | false | false | false |
DuckDeck/GrandMenu | GrandMenuDemo/ViewControllers/Controller3.swift | 1 | 1128 | //
// Controller3.swift
// Demo
//
// Created by Tyrant on 1/14/16.
//
//
import UIKit
class Controller3: UIViewController,UITableViewDataSource {
var tb:UITableView?
var arrData:[String]?
override func viewDidLoad() {
super.viewDidLoad()
tb = UITableView()
tb?.dataSource = self
arrData = [String]()
for _ in 0...40
{
arrData?.append("Controller3")
}
view.addSubview(tb!)
}
override func viewWillLayoutSubviews() {
tb?.frame = self.view.bounds
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrData!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentity = "vc1"
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentity)
if cell == nil{
cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentity)
}
cell?.textLabel?.text = arrData![(indexPath as NSIndexPath).row]
return cell!
}
}
| mit | fc14d61de62b64abb5678450b101bee9 | 25.857143 | 100 | 0.611702 | 4.7 | false | false | false | false |
JaSpa/swift | stdlib/public/SDK/Intents/INGetCarLockStatusIntentResponse.swift | 1 | 898 | //===----------------------------------------------------------------------===//
//
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Intents
import Foundation
#if os(iOS) || os(watchOS)
@available(iOS 10.3, watchOS 3.2, *)
extension INGetCarLockStatusIntentResponse {
@nonobjc
public final var locked: Bool? {
get {
return __locked?.boolValue
}
set(newLocked) {
__locked = newLocked.map { NSNumber(value: $0) }
}
}
}
#endif
| apache-2.0 | 9f899ca06e4d3a7afabad8c7e08779ff | 29.965517 | 80 | 0.54343 | 4.628866 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/RenderLayers/ShapeContainerLayer.swift | 1 | 1603 | //
// ShapeContainerLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import Foundation
import QuartzCore
/**
The base layer that holds Shapes and Shape Renderers
*/
class ShapeContainerLayer: CALayer {
private(set) var renderLayers: [ShapeContainerLayer] = []
override init() {
super.init()
self.actions = [
"position" : NSNull(),
"bounds" : NSNull(),
"anchorPoint" : NSNull(),
"transform" : NSNull(),
"opacity" : NSNull(),
"hidden" : NSNull(),
]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(layer: Any) {
guard let layer = layer as? ShapeContainerLayer else {
fatalError("init(layer:) wrong class.")
}
super.init(layer: layer)
}
var renderScale: CGFloat = 1 {
didSet {
updateRenderScale()
}
}
func insertRenderLayer(_ layer: ShapeContainerLayer) {
renderLayers.append(layer)
insertSublayer(layer, at: 0)
}
func markRenderUpdates(forFrame: CGFloat) {
if self.hasRenderUpdate(forFrame: forFrame) {
self.rebuildContents(forFrame: forFrame)
}
guard self.isHidden == false else { return }
renderLayers.forEach { $0.markRenderUpdates(forFrame: forFrame) }
}
func hasRenderUpdate(forFrame: CGFloat) -> Bool {
return false
}
func rebuildContents(forFrame: CGFloat) {
/// Override
}
func updateRenderScale() {
self.contentsScale = self.renderScale
renderLayers.forEach( { $0.renderScale = renderScale } )
}
}
| mit | 4da514cf0250591f59a7cdd1caa1ed04 | 20.958904 | 69 | 0.641298 | 3.881356 | false | false | false | false |
JaSpa/swift | validation-test/compiler_crashers/28667-result-case-not-implemented.swift | 2 | 517 | // 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
// REQUIRES: deterministic-behavior
// RUN: not --crash %target-swift-frontend %s -emit-ir
{extension{{}func b(UInt=_=1 + 1 as?Int){(==S
class d
func b(=_{$0=a(ol a=a(
| apache-2.0 | 3086ce0f56de0451bf159d311b605fbe | 42.083333 | 79 | 0.725338 | 3.541096 | false | false | false | false |
mac-cain13/Xcode.swift | Example/Example/main.swift | 1 | 1445 | //
// main.swift
// Example
//
// Created by Tom Lokhorst on 2015-08-14.
// Copyright (c) 2015 nonstrict. All rights reserved.
//
import Foundation
let args = Process.arguments
if args.count < 2 {
print("Call with a .xcodeproj, e.g.: \"$SRCROOT/../Test projects/HelloCpp.xcodeproj\"")
}
// The xcodeproj file to load, test this with your own project!
let xcodeproj = NSURL(fileURLWithPath: args[1])
// Load from a xcodeproj
let proj = try! XCProjectFile(xcodeprojURL: xcodeproj)
// Write out a new pbxproj file
try! proj.writeToXcodeproj(xcodeprojURL: xcodeproj, format: NSPropertyListFormat.OpenStepFormat)
// Print paths for all files in Resources build phases
for target in proj.project.targets {
for resourcesBuildPhase in target.buildPhases.ofType(PBXResourcesBuildPhase.self) {
for file in resourcesBuildPhase.files {
if let fileReference = file.fileRef as? PBXFileReference {
print(fileReference.fullPath)
}
// Variant groups are localizable
else if let variantGroup = file.fileRef as? PBXVariantGroup {
for variantFileReference in variantGroup.fileRefs {
print(variantFileReference.fullPath)
}
}
}
}
}
// Print shells
for target in proj.project.targets {
for buildPhase in target.buildPhases {
print(buildPhase)
if let shellScriptPhase = buildPhase as? PBXShellScriptBuildPhase {
print(shellScriptPhase.shellScript)
}
}
}
| mit | 0f3c7a97ae85b65b985cbc54cdb41e40 | 26.788462 | 96 | 0.714879 | 4.070423 | false | false | false | false |
Jnosh/swift | test/stdlib/MathConstants.swift | 23 | 432 | // RUN: %target-typecheck-verify-swift
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
import Glibc
#endif
_ = M_PI // expected-warning {{is deprecated}}
_ = M_PI_2 // expected-warning {{is deprecated}}
_ = M_PI_4 // expected-warning {{is deprecated}}
_ = M_SQRT2 // expected-warning {{is deprecated}}
_ = M_SQRT1_2 // expected-warning {{is deprecated}}
| apache-2.0 | ccf441f76ced7f619b8e59b2932879d3 | 29.857143 | 58 | 0.645833 | 2.899329 | false | false | false | false |
buscarini/Collectionist | Collectionist/Classes/List/List+Utils.swift | 1 | 5196 | //
// List+Utils.swift
// Pods
//
// Created by José Manuel Sánchez Peñarroja on 19/5/16.
//
//
import Foundation
import Miscel
public extension List {
typealias ListType = List<T, HeaderT, FooterT>
public static func listFrom<T: Equatable>(
_ items: [T],
nibName: String,
configuration: ListConfiguration? = nil,
scrollInfo: ListScrollInfo? = nil,
itemConfiguration: ListItemConfiguration? = nil,
onSelect: ((ListItem<T>)->())? = nil,
onFocus: ((ListItem<T>)->())? = nil
) -> List<T,HeaderT,FooterT> {
let listItems = items.map {
ListItem(nibName: nibName, reusableId: nil,value: $0, configuration: itemConfiguration, onSelect: onSelect, onFocus: onFocus)
}
let section = ListSection<T,HeaderT,FooterT>(items : listItems, header: nil, footer: nil)
return List<T,HeaderT,FooterT>(sections: [section], header: nil, footer: nil, scrollInfo: scrollInfo, configuration: configuration)
}
// public static func listFrom<T>(items: [T],
// nibName: String,
// scrollInfo: ListScrollInfo? = nil,
// configuration: ListConfiguration? = nil,
// itemConfiguration: ListItemConfiguration? = nil,
// onSelect: ((ListItem<T>)->())? = nil,
// onFocus: ((ListItem<T>)->())? = nil) -> List<T> {
// let listItems = items.map {
// ListItem(nibName: nibName, cellId: nil,value: $0, configuration: itemConfiguration, swipeActions: [], onSelect: onSelect, onFocus: onFocus)
// }
//
// let section = ListSection(items: listItems)
// return List<T>(sections: [section], scrollInfo: scrollInfo, configuration: configuration)
// }
public static func isEmpty<T: Equatable>(_ list: List<T,HeaderT,FooterT>) -> Bool {
return list.sections.map { $0.items.count }.reduce(0, +)==0
}
public static func itemIndexPath(_ list: ListType, item: T) -> IndexPath? {
for (sectionIndex, section) in list.sections.enumerated() {
for (itemIndex, listItem) in section.items.enumerated() {
if listItem.value == item {
return IndexPath(row: itemIndex, section: sectionIndex)
}
}
}
return nil
}
public static func itemAt<T: Equatable>(_ list: List<T,HeaderT,FooterT>, indexPath: IndexPath) -> ListItem<T>? {
guard List<T,HeaderT,FooterT>.indexPathInsideBounds(list, indexPath: indexPath) else { return nil }
return list.sections[indexPath.section].items[indexPath.row]
}
public static func indexPathInsideBounds(_ list: List,indexPath: IndexPath) -> Bool {
switch (indexPath.section,indexPath.row) {
case (let section, _) where section>=list.sections.count:
return false
case (let section,_) where section<0:
return false
case (let section, let row) where row>=list.sections[section].items.count || row<0:
return false
default:
return true
}
}
public static func sectionInsideBounds(_ list: List,section : Int) -> Bool {
return list.sections.count>section && section>=0
}
public static func sameItemsCount<T : Equatable, HeaderT : Equatable, FooterT: Equatable>(_ list1: List<T,HeaderT,FooterT>, _ list2: List<T,HeaderT,FooterT>) -> Bool {
guard (list1.sections.count == list2.sections.count) else { return false }
return Zip2Sequence(_sequence1: list1.sections,_sequence2: list2.sections).filter {
(section1, section2) in
return section1.items.count != section2.items.count
}.count==0
}
public static func headersChanged(_ list1: List, _ list2: List) -> Bool {
let headers1 = list1.sections.map {
return $0.header
}.flatMap { $0 }
let headers2 = list2.sections.map {
return $0.header
}.flatMap { $0 }
let footers1 = list1.sections.map {
return $0.footer
}.flatMap { $0 }
let footers2 = list2.sections.map {
return $0.footer
}.flatMap { $0 }
return headers1 != headers2 || footers1 != footers2
}
public static func itemsChangedPaths<T : Equatable, HeaderT : Equatable, FooterT: Equatable>(_ list1: List<T,HeaderT,FooterT>, _ list2: List<T,HeaderT,FooterT>) -> [IndexPath] {
assert(sameItemsCount(list1, list2))
let processed = Zip2Sequence(_sequence1: list1.sections,_sequence2: list2.sections).map {
(section1, section2) in
return Zip2Sequence(_sequence1: section1.items,_sequence2: section2.items).map(compareItems)
}
return Zip2Sequence(_sequence1: processed,_sequence2: Array(0..<processed.count)).map {
(items, sectionIndex) -> [IndexPath] in
let numItems = items.count
let indexes = Zip2Sequence(_sequence1: items,_sequence2: Array(0..<numItems))
.map { // Convert non nil items to their indexes
(item, index) in
item.map { _ in index }
}
.flatMap{$0} // Removed nil items
return indexes.map { IndexPath(row: $0, section: sectionIndex) } // Convert indexes to indexPath
}.flatMap{$0} // Flatten [[IndexPath]]
}
public static func compareItems<T>(_ item1: ListItem<T>,item2: ListItem<T>) -> ListItem<T>? {
return item1 == item2 ? nil : item2
}
public static func allReusableIds(_ list: List) -> [String] {
return removingDuplicates(list.sections.flatMap {
section in
return section.items.map {
$0.cellId
}
})
}
}
| mit | f8f1ecb766b2b21075f479ec98842f56 | 32.941176 | 178 | 0.669363 | 3.372078 | false | true | false | false |
thisfin/FolderSync | FolderSync/FolderCompareViewController.swift | 1 | 16987 | //
// FolderCompareViewController.swift
// FolderSync
//
// Created by wenyou on 2017/9/12.
// Copyright © 2017年 wenyou. All rights reserved.
//
import Cocoa
class FolderCompareViewController: NSViewController {
private let viewSize = NSMakeSize(800, 600)
var sourceOutlineView: SingleOutlineView!
var targetOutlineView: SingleOutlineView!
private var isShowHiddenFile: Bool = FolderCompareViewController.getShowHiddenFileFromUserDefaults() {
didSet {
if oldValue != isShowHiddenFile {
UserDefaults.standard.set(isShowHiddenFile, forKey: Constants.showHiddenFileKey)
reload()
}
}
}
private var fileCompareCondition: FileCompareCondition = FolderCompareViewController.getFileCompareConditionFromUserDefaults() {
didSet {
if oldValue != fileCompareCondition {
UserDefaults.standard.set(fileCompareCondition.rawValue, forKey: Constants.fileCompareConditionKey)
reload()
}
}
}
private var panel: NSPanel?
private var progressIndicator: NSProgressIndicator?
private var panelTextField: NSTextField?
override func loadView() {
view = NSView()
}
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
view.frame = NSRect(origin: .zero, size: viewSize)
let attributedString = NSMutableAttributedString.init(string: "不同 版本较新 版本较老 独有")
attributedString.addAttribute(.foregroundColor, value: NSColor.systemOrange, range: NSRange.init(location: 0, length: 2))
attributedString.addAttribute(.foregroundColor, value: NSColor.systemGreen, range: NSRange.init(location: 3, length: 4))
attributedString.addAttribute(.foregroundColor, value: NSColor.systemRed, range: NSRange.init(location: 8, length: 4))
attributedString.addAttribute(.foregroundColor, value: NSColor.systemBlue, range: NSRange.init(location: 13, length: 2))
let contentTextField = NSTextField.init(labelWithAttributedString: attributedString)
view.addSubview(contentTextField)
contentTextField.snp.makeConstraints { (maker) in
maker.top.equalToSuperview().offset(10)
maker.left.equalToSuperview().offset(10)
}
let hiddenFildButton = NSButton.init(checkboxWithTitle: "显示隐藏文件", target: self, action: #selector(hiddenFileButtonClicked(_:)))
hiddenFildButton.state = isShowHiddenFile ? .on : .off
view.addSubview(hiddenFildButton)
let compareFileField = NSTextField.init(string: "文件相等判断条件:")
compareFileField.isEditable = false
compareFileField.isSelectable = false
compareFileField.isBordered = false
compareFileField.backgroundColor = .clear
view.addSubview(compareFileField)
let compareFileButton = NSPopUpButton.init(frame: .zero)
compareFileButton.menu = {
let menu = NSMenu.init()
menu.addItem({
let item = NSMenuItem.init()
item.title = "文件名"
item.tag = FileCompareCondition.name.rawValue
return item
}())
menu.addItem({
let item = NSMenuItem.init()
item.title = "文件大小"
item.tag = FileCompareCondition.size.rawValue
return item
}())
menu.addItem({
let item = NSMenuItem.init()
item.title = "md5"
item.tag = FileCompareCondition.md5.rawValue
return item
}())
return menu
}()
compareFileButton.action = #selector(compareFileButtonClicked(_:))
compareFileButton.selectItem(at: fileCompareCondition.rawValue)
view.addSubview(compareFileButton)
compareFileButton.snp.makeConstraints { (maker) in
maker.top.equalToSuperview().offset(10)
maker.right.equalToSuperview().offset(-10)
}
compareFileField.snp.makeConstraints { (maker) in
maker.centerY.equalTo(compareFileButton)
maker.right.equalTo(compareFileButton.snp.left).offset(-5)
}
hiddenFildButton.snp.makeConstraints { (maker) in
maker.top.equalTo(compareFileButton.snp.bottom).offset(10)
maker.right.equalToSuperview().offset(-10)
}
sourceOutlineView = SingleOutlineView.init(frame: NSRect(x: 0, y: 0, width: 0, height: 0))
targetOutlineView = SingleOutlineView.init(frame: NSRect(x: 0, y: 0, width: 0, height: 0))
view.addSubview(sourceOutlineView)
view.addSubview(targetOutlineView)
sourceOutlineView.copyFileAction = { (files) in
self.copyFile(files: files, isSource: true)
}
targetOutlineView.copyFileAction = { (files) in
self.copyFile(files: files, isSource: false)
}
sourceOutlineView.snp.makeConstraints { (maker) in
maker.left.equalToSuperview().offset(10)
maker.top.equalTo(hiddenFildButton.snp.bottom).offset(10)
maker.bottom.equalToSuperview().offset(-10)
}
targetOutlineView.snp.makeConstraints { (maker) in
maker.left.equalTo(sourceOutlineView.snp.right).offset(10)
maker.right.equalToSuperview().offset(-10)
maker.top.equalTo(hiddenFildButton.snp.bottom).offset(10)
maker.bottom.equalToSuperview().offset(-10)
maker.width.equalTo(sourceOutlineView.snp.width).multipliedBy(1)
}
let expandButton = NSButton.init(title: "展开", target: self, action: #selector(expandButtonClicked(_:)))
let collapseButton = NSButton.init(title: "收起", target: self, action: #selector(collapseButtonClicked(_:)))
let flushButton = NSButton.init(title: "刷新", target: self, action: #selector(flushButtonClicked(_:)))
let button = NSButton.init(title: "button", target: self, action: #selector(buttonClicked(_:)))
view.addSubview(expandButton)
view.addSubview(collapseButton)
view.addSubview(flushButton)
view.addSubview(button)
expandButton.snp.makeConstraints { (maker) in
maker.left.equalToSuperview().offset(10)
maker.bottom.equalTo(sourceOutlineView.snp.top).offset(-10)
}
collapseButton.snp.makeConstraints { (maker) in
maker.left.equalTo(expandButton.snp.right).offset(10)
maker.bottom.equalTo(expandButton)
}
flushButton.snp.makeConstraints { (maker) in
maker.left.equalTo(collapseButton.snp.right).offset(10)
maker.bottom.equalTo(expandButton)
}
button.snp.makeConstraints { (maker) in
maker.left.equalTo(flushButton.snp.right).offset(10)
maker.bottom.equalTo(expandButton)
}
}
@objc func buttonClicked(_ sender: NSButton) {
}
override func viewWillAppear() {
super.viewWillAppear()
NotificationCenter.default.addObserver(self, selector: #selector(notificationReceive(_:)), name: .reloadEnd, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(notificationReceive(_:)), name: .updateState, object: nil)
if sourceOutlineView.rootFile == nil { // 第一次初始化
reload()
}
}
override func viewDidAppear() {
super.viewDidAppear()
}
override func viewDidDisappear() {
super.viewDidDisappear()
NotificationCenter.default.removeObserver(self, name: .reloadEnd, object: nil)
NotificationCenter.default.removeObserver(self, name: .updateState, object: nil)
}
@available(OSX 10.12.2, *)
override func makeTouchBar() -> NSTouchBar? {
let touchBar = NSTouchBar()
touchBar.delegate = self
touchBar.customizationIdentifier = NSTouchBar.CustomizationIdentifier.create(type: FolderCompareViewController.self)
touchBar.defaultItemIdentifiers = [.expand, .collapse, .flush]
return touchBar
}
private func reload() {
openPanel()
DispatchQueue.global().async { // 如果不放在别的线程, 则菊花的动画不会运行...
self.reloadSlice()
}
}
private func reloadSlice() {
NotificationCenter.default.post(name: .updateState, object: nil, userInfo: ["value" : "检索文件..."])
if let sourcePath = UserDefaults.standard.string(forKey: Constants.sourceFolderPathKey), let targetPath = UserDefaults.standard.string(forKey: Constants.targetFolderPathKey) {
FilePermissions.sharedInstance.handle {
var sourceFile = FileObject.init(path: sourcePath)
var targetFile = FileObject.init(path: targetPath)
NotificationCenter.default.post(name: .updateState, object: nil, userInfo: ["value" : "文件对比..."])
_ = FileService().compareFolder(sourceFile: &sourceFile, targetFile: &targetFile)
sourceOutlineView.rootFile = sourceFile
targetOutlineView.rootFile = targetFile
}
}
NotificationCenter.default.post(name: .reloadEnd, object: nil)
}
private func openPanel() {
let panel = NSPanel(contentRect: NSMakeRect(0, 0, 240, 120), styleMask: [.borderless, .hudWindow], backing: .buffered, defer: true)
let progressIndicator = NSProgressIndicator.init()
progressIndicator.style = .spinning
progressIndicator.controlSize = .regular
progressIndicator.usesThreadedAnimation = true
if let filter = CIFilter.init(name: "CIColorControls") { // 颜色
filter.setDefaults()
filter.setValue(1, forKey: "inputBrightness")
progressIndicator.contentFilters = [filter]
}
let textField = NSTextField.init()
textField.isEditable = false
textField.isSelectable = false
textField.isBordered = false
textField.backgroundColor = .clear
textField.alignment = .center
textField.textColor = .white
if let contentView = panel.contentView {
contentView.addSubview(progressIndicator)
progressIndicator.snp.makeConstraints({ (maker) in
maker.centerY.equalToSuperview().offset(-10)
maker.centerX.equalToSuperview()
})
contentView.addSubview(textField)
textField.snp.makeConstraints({ (maker) in
maker.left.equalToSuperview()
maker.right.equalToSuperview()
maker.bottom.equalToSuperview().offset(-10 * 2)
})
contentView.wantsLayer = true
contentView.layer?.cornerRadius = 5
contentView.layer?.backgroundColor = panel.backgroundColor.cgColor
panel.backgroundColor = .clear
}
progressIndicator.startAnimation(self)
view.window?.beginSheet(panel, completionHandler: nil)
self.panel = panel
self.progressIndicator = progressIndicator
self.panelTextField = textField
}
private func closePanel() {
sourceOutlineView.reload()
targetOutlineView.reload()
if let progressIndicator = self.progressIndicator {
progressIndicator.stopAnimation(self)
}
if let panelTextField = self.panelTextField {
panelTextField.stringValue = ""
}
if let panel = self.panel {
view.window?.endSheet(panel)
}
}
static func getShowHiddenFileFromUserDefaults() -> Bool {
guard let _ = UserDefaults.standard.object(forKey: Constants.showHiddenFileKey) else { // 默认值
return false
}
return UserDefaults.standard.bool(forKey: Constants.showHiddenFileKey)
}
static func getFileCompareConditionFromUserDefaults() -> FileCompareCondition {
guard let _ = UserDefaults.standard.object(forKey: Constants.fileCompareConditionKey) else { // 默认值
return .name
}
return FileCompareCondition(rawValue: UserDefaults.standard.integer(forKey: Constants.fileCompareConditionKey))!
}
private func copyFile(files: [FileObject], isSource: Bool) {
openPanel()
DispatchQueue.global().async {
self.copySlice(files: files, isSource: isSource)
self.reloadSlice()
}
}
private func copySlice(files: [FileObject], isSource: Bool) {
let fileManager = FileManager.default
NotificationCenter.default.post(name: .updateState, object: nil, userInfo: ["value" : "拷贝文件..."])
if let sourcePath = UserDefaults.standard.string(forKey: Constants.sourceFolderPathKey), let targetPath = UserDefaults.standard.string(forKey: Constants.targetFolderPathKey) {
files.forEach { (fileObject) in
let source = (isSource ? sourcePath : targetPath) + "/" + fileObject.relativePath
let target = (isSource ? targetPath : sourcePath) + "/" + fileObject.relativePath
if fileManager.fileExists(atPath: target) { // 目标存在则删除
FilePermissions.sharedInstance.handle {
try? fileManager.removeItem(atPath: target)
}
}
let url = URL.init(fileURLWithPath: target).deletingLastPathComponent()
if !fileManager.fileExists(atPath: url.path) { // 创建目标父文件夹
FilePermissions.sharedInstance.handle {
try? fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
}
}
FilePermissions.sharedInstance.handle {
try? fileManager.copyItem(atPath: source, toPath: target) // cp
}
}
}
}
}
@available(OSX 10.12.2, *)
extension FolderCompareViewController: NSTouchBarDelegate {
public func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
let touchBarItem = NSCustomTouchBarItem(identifier: identifier)
switch identifier {
case .expand:
touchBarItem.view = NSButton(title: "展开", target: self, action: #selector(expandButtonClicked(_:)))
case .collapse:
touchBarItem.view = NSButton(title: "收起", target: self, action: #selector(collapseButtonClicked(_:)))
case .flush:
touchBarItem.view = NSButton(title: "刷新", target: self, action: #selector(flushButtonClicked(_:)))
default:
()
}
return touchBarItem
}
}
@available(OSX 10.12.2, *)
private extension NSTouchBarItem.Identifier {
static let expand = create(type: FolderCompareViewController.self, suffix: "expand")
static let collapse = create(type: FolderCompareViewController.self, suffix: "collapse")
static let flush = create(type: FolderCompareViewController.self, suffix: "flush")
}
@objc extension FolderCompareViewController {
private func hiddenFileButtonClicked(_ sender: NSButton) {
switch sender.state {
case .on:
isShowHiddenFile = true
case .off:
isShowHiddenFile = false
default:
()
}
}
private func compareFileButtonClicked(_ sender: NSPopUpButton) {
if let fileCompareCondition = FileCompareCondition.init(rawValue: sender.selectedTag()) {
self.fileCompareCondition = fileCompareCondition
}
}
private func expandButtonClicked(_ sender: NSButton) {
sourceOutlineView.outlineView.expandItem(nil, expandChildren: true)
targetOutlineView.outlineView.expandItem(nil, expandChildren: true)
}
private func collapseButtonClicked(_ sender: NSButton) {
sourceOutlineView.outlineView.collapseItem(nil, collapseChildren: true)
targetOutlineView.outlineView.collapseItem(nil, collapseChildren: true)
}
private func flushButtonClicked(_ sender: NSButton) {
reload()
}
private func notificationReceive(_ notification: Notification) {
DispatchQueue.main.async { // ui 修改必须放在主线程
switch notification.name {
case .reloadEnd:
self.closePanel()
case .updateState:
if let value = notification.userInfo?["value"] as? String {
self.panelTextField?.stringValue = value
}
default:
()
}
}
}
}
private extension Notification.Name {
static let reloadEnd = Notification.Name("notificationNameEnd")
static let updateState = Notification.Name("notificationNameState")
}
| mit | 736f6ed812684d68729aae2cd55798bd | 40.270936 | 183 | 0.641084 | 4.935493 | false | false | false | false |
Antondomashnev/Sourcery | Sourcery/Utils/Path+Extensions.swift | 1 | 2005 | //
// Path+Extensions.swift
// Sourcery
//
// Created by Krunoslav Zaher on 1/6/17.
// Copyright © 2017 Pixle. All rights reserved.
//
import Foundation
import PathKit
typealias Path = PathKit.Path
extension Path {
static func cleanTemporaryDir(name: String) -> Path {
guard let tempDirURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("Sourcery.\(name)") else { fatalError("Unable to get temporary path") }
_ = try? FileManager.default.removeItem(at: tempDirURL)
// swiftlint:disable:next force_try
try! FileManager.default.createDirectory(at: tempDirURL, withIntermediateDirectories: true, attributes: nil)
return Path(tempDirURL.path)
}
static func cachesDir(sourcePath: Path) -> Path {
var paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]
let path = Path(paths[0]) + "Sourcery" + sourcePath.lastComponent
if !path.exists {
// swiftlint:disable:next force_try
try! FileManager.default.createDirectory(at: path.url, withIntermediateDirectories: true, attributes: nil)
}
return path
}
var isTemplateFile: Bool {
return self.extension == "stencil" ||
self.extension == "swifttemplate" ||
self.extension == "ejs"
}
var isSwiftSourceFile: Bool {
return !self.isDirectory && self.extension == "swift"
}
func hasExtension(as string: String) -> Bool {
let extensionString = ".\(string)."
return self.string.contains(extensionString)
}
init(_ string: String, relativeTo relativePath: Path) {
var path = Path(string)
if !path.isAbsolute {
path = (relativePath + path).absolute()
}
self.init(path.string)
}
var allPaths: [Path] {
if isDirectory {
return (try? recursiveChildren()) ?? []
} else {
return [self]
}
}
}
| mit | 1e59c216766cc35982e9e47c7b4d6c68 | 30.3125 | 172 | 0.629242 | 4.473214 | false | false | false | false |
sachinvas/Swifter | Source/Extensions/DictionaryExtensions.swift | 2 | 2109 | //
// DictionaryExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/24/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
import Foundation
// MARK: - Methods
public extension Dictionary {
/// SwifterSwift: Check if key exists in dictionary.
///
/// - Parameter key: key to search for
/// - Returns: true if key exists in dictionary.
func has(key: Key) -> Bool {
return index(forKey: key) != nil
}
/// SwifterSwift: JSON Data from dictionary.
///
/// - Parameter prettify: set true to prettify data (default is false).
/// - Returns: optional JSON Data (if applicable).
public func jsonData(prettify: Bool = false) -> Data? {
guard JSONSerialization.isValidJSONObject(self) else {
return nil
}
let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions()
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: options)
return jsonData
} catch {
return nil
}
}
/// SwifterSwift: JSON String from dictionary.
///
/// - Parameter prettify: set true to prettify string (default is false).
/// - Returns: optional JSON String (if applicable).
public func jsonString(prettify: Bool = false) -> String? {
guard JSONSerialization.isValidJSONObject(self) else {
return nil
}
let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions()
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: options)
return String(data: jsonData, encoding: .utf8)
} catch {
return nil
}
}
}
// MARK: - Methods (ExpressibleByStringLiteral)
public extension Dictionary where Key: ExpressibleByStringLiteral {
/// SwifterSwift: Lowercase all keys in dictionary.
public mutating func lowercaseAllKeys() {
// http://stackoverflow.com/questions/33180028/extend-dictionary-where-key-is-of-type-string
for key in self.keys {
if let lowercaseKey = String(describing: key).lowercased() as? Key {
self[lowercaseKey] = self.removeValue(forKey: key)
}
}
}
}
| mit | 1275ca338aa516aa4d63ff450a1848ff | 27.876712 | 120 | 0.711101 | 3.889299 | false | false | false | false |
cwaffles/Soulcast | Soulcast/ImproveVC.swift | 1 | 1709 | //
// FeedbackVC.swift
// Soulcast
//
// Created by June Kim on 2016-09-16.
// Copyright © 2016 Soulcast-team. All rights reserved.
//
import Foundation
import UIKit
protocol ImproveVCDelegate: class {
func didFinishGettingImprove()
}
class ImproveVC: UIViewController {
weak var delegate:ImproveVCDelegate?
var outgoingVC = OutgoingVC()
let descriptionText = "Help us improve Soulcast. \nWe're listening!"
override func viewDidLoad() {
super.viewDidLoad()
layoutStuff()
view.backgroundColor = UIColor.white
}
func layoutStuff() {
addDescriptionLabel()
addOutgoingVC()
}
func addOutgoingVC() {
outgoingVC.delegate = self
outgoingVC.soulType = .Improve
outgoingVC.maxRecordingDuration = 10
addChildVC(outgoingVC)
view.addSubview(outgoingVC.view)
outgoingVC.didMove(toParentViewController: self)
}
func addDescriptionLabel() {
let inset:CGFloat = 30
let descriptionLabel = UILabel(frame: CGRect(
x: inset,
y: inset,
width: view.bounds.width - 2 * inset,
height: view.bounds.width * 1.2 ))
descriptionLabel.text = descriptionText
descriptionLabel.numberOfLines = 0
descriptionLabel.textColor = UIColor.darkGray
descriptionLabel.font = UIFont(name: HelveticaNeue, size: 20)
view.addSubview(descriptionLabel)
}
}
extension ImproveVC: OutgoingVCDelegate {
func outgoingRadius() -> Double {
return 0;
}
func outgoingLongitude() -> Double {
return 0;
}
func outgoingLatitude() -> Double {
return 0;
}
func outgoingDidStart() {
}
func outgoingDidStop() {
print("outgoingDidStop")
dismiss(animated: true) {
//
}
}
}
| mit | c5effe9bb53bee0d4ec42f2b8767a4ae | 21.181818 | 70 | 0.680328 | 4.186275 | false | false | false | false |
cliffpanos/True-Pass-iOS | iOSApp/CheckIn/Managers/DataServices/Accounts.swift | 1 | 5198 | //
// Accounts.swift
// True Pass
//
// Created by Cliff Panos on 5/1/17.
// Copyright © 2017 Clifford Panos. All rights reserved.
//
import Foundation
import Firebase
import FirebaseDatabase
import FirebaseAuth
//import GoogleSignIn
//import FacebookCore
//import FacebookLogin
class Accounts {
static let shared = Accounts()
var current: User? {
return Auth.auth().currentUser
}
static var currentUser: TPUser!
func standardLogin(withEmail email: String, password: String, completion: @escaping ((_ loginSuccessful: Bool) -> Void)) {
Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
completion(error == nil)
}
}
func standardRegister(withEmail email: String, password: String, completion: @escaping ((Bool, Error?) -> Void)) {
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
print(error ?? "")
completion(error == nil, error)
}
}
func sendConfirmationEmail(forUser user: User) {
user.sendEmailVerification(completion: { success in
})
}
func updateEmail(to newEmail: String) {
Auth.auth().currentUser?.updateEmail(to: newEmail) { error in
if let error = error { print(error.localizedDescription) }
}
}
func logout(completion: @escaping ((_ failure: Error?) -> Void)) {
do {
// if AccessToken.current != nil { // authenticated with Facebook
// let loginManager = LoginManager()
// loginManager.logOut()
// }
try Auth.auth().signOut()
completion(nil)
} catch let error as NSError {
print("Error signing out: \(error.localizedDescription)")
completion(error)
}
}
var hasStandardAuth: Bool {
return userHasAuth(type: "password")
}
var hasFaceBookAuth: Bool {
return userHasAuth(type: "facebook")
}
var hasGoogleAuth: Bool {
return userHasAuth(type: "google")
}
private func userHasAuth(type: String) -> Bool {
for provider in current?.providerData ?? [] {
if provider.providerID.contains(type) {
return true;
}
}
return false
}
private func customLogin(credential: AuthCredential, completion: @escaping ((_ loginSuccessful: Bool) -> Void)) {
Auth.auth().signIn(with: credential) { (user, error) in
completion(error == nil)
}
}
}
//Handle the simple but incredibly important storage of user information
//Though ratchet, UserDefaults are used to provide a completely, 100% infallible way of preserving this data
extension Accounts {
enum TPUDKeys: String {
case TPUDkUserFirstName
case TPUDkUserLastName
case TPUDkUserIdenfitier
case TPUDkUserImageData
case TPUDkUserEmail
}
class func saveToUserDefaults(user: TPUser, updateImage: Bool = false) {
userFirstName = user.firstName ?? ""
userLastName = user.lastName ?? ""
userImageData = user.imageData as Data?
userEmail = user.email!
userIdentifier = user.identifier!
guard updateImage else { return }
FirebaseStorage.shared.retrieveProfilePicture(for: user.identifier!) { data, error in
if let data = data { userImageData = data }
}
}
class var userFirstName: String {
get {
return C.getFromUserDefaults(withKey: TPUDKeys.TPUDkUserFirstName.rawValue) as! String
}
set {
C.persistUsingUserDefaults(newValue, forKey: TPUDKeys.TPUDkUserFirstName.rawValue)
}
}
class var userLastName: String {
get {
return C.getFromUserDefaults(withKey: TPUDKeys.TPUDkUserLastName.rawValue) as! String
}
set {
C.persistUsingUserDefaults(newValue, forKey: TPUDKeys.TPUDkUserLastName.rawValue)
}
}
class var userName: String {
return userFirstName + " " + userLastName
}
class var userIdentifier: String {
get {
return C.getFromUserDefaults(withKey: TPUDKeys.TPUDkUserIdenfitier.rawValue) as! String
}
set {
C.persistUsingUserDefaults(newValue, forKey: TPUDKeys.TPUDkUserIdenfitier.rawValue)
}
}
class var userImageData: Data? {
get {
return C.getFromUserDefaults(withKey: TPUDKeys.TPUDkUserImageData.rawValue) as? Data
}
set {
C.persistUsingUserDefaults(newValue, forKey: TPUDKeys.TPUDkUserImageData.rawValue)
}
}
class var userImage: UIImage? {
if let imageData = Accounts.userImageData { return UIImage(data: imageData) }
return nil
}
class var userEmail: String {
get {
return C.getFromUserDefaults(withKey: TPUDKeys.TPUDkUserEmail.rawValue) as! String
}
set {
C.persistUsingUserDefaults(newValue, forKey: TPUDKeys.TPUDkUserEmail.rawValue)
}
}
}
| apache-2.0 | 93058815c8d436def8dddba10733cf4f | 29.934524 | 126 | 0.609582 | 4.590989 | false | false | false | false |
igerard/MetalByExampleInSwift | Chapter2/Chapter2/GIMLView.swift | 1 | 4626 | //
// GIMTLView.swift
// Chapter2
//
// Created by Gerard Iglesias on 01/12/2016.
// Copyright © 2016 Gerard Iglesias. All rights reserved.
//
import AppKit
class GIMTLView : NSView {
// MARK: Vars
var info : String
var mlLayer : CAMetalLayer? = nil
override var layer: CALayer? {
didSet {
mlLayer = layer as? CAMetalLayer
}
}
var device : MTLDevice
var displayLink : CVDisplayLink? = nil
// MARK: Init Phase
required init?(coder : NSCoder){
if let theDevice = MTLCreateSystemDefaultDevice(){
self.device = theDevice
self.info = "View to show metal rendering"
super.init(coder : coder)
self.wantsLayer = true
self.layerContentsRedrawPolicy = .onSetNeedsDisplay
self.layerContentsPlacement = .scaleAxesIndependently
}
else{
return nil
}
}
@objc override func makeBackingLayer() -> CALayer {
let mll = CAMetalLayer()
mll.device = self.device
mll.delegate = self
Swift.print("Pixel format raw value : ", mll.pixelFormat.rawValue)
Swift.print("Metal layer : ", mll)
return mll
}
// MARK: Display
@objc override func draw(_ dirtyRect: NSRect) {
redraw()
}
@objc override func updateLayer() {
Swift.print(self.layer?.description ?? "No layer")
}
@objc override func viewDidMoveToWindow() -> Void {
func GIDMLViewDisplayLinkRedrawCall(displayLink : CVDisplayLink,
inNow : UnsafePointer<CVTimeStamp>,
inOutputTime : UnsafePointer<CVTimeStamp>,
flagsIn : CVOptionFlags,
flagsOut : UnsafeMutablePointer<CVOptionFlags>,
displayLinkContext : UnsafeMutableRawPointer?) -> CVReturn{
_ = inNow[0]
_ = inOutputTime[0]
let view = unsafeBitCast(displayLinkContext, to: GIMTLView.self)
autoreleasepool{
view.redraw()
}
return kCVReturnSuccess
}
if self.window != nil {
CVDisplayLinkCreateWithCGDisplay(CGMainDisplayID(), &displayLink)
CVDisplayLinkSetOutputCallback(displayLink!, GIDMLViewDisplayLinkRedrawCall, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()))
CVDisplayLinkStart(displayLink!)
Swift.print("Layer rect : ", mlLayer != nil ? mlLayer!.bounds.debugDescription : "Not defined")
}
else{
if let link = displayLink {
CVDisplayLinkStop(link)
displayLink = nil
}
}
redraw()
}
@objc override func resizeSubviews(withOldSize oldSize: NSSize) {
super.resizeSubviews(withOldSize: oldSize)
mlLayer?.drawableSize = CGSize(width: bounds.size.width, height: bounds.size.height)
}
func redraw() -> Void {
if let drawable = self.mlLayer?.nextDrawable(){
let passDescr = MTLRenderPassDescriptor()
passDescr.colorAttachments[0].texture = drawable.texture
passDescr.colorAttachments[0].loadAction = .clear
passDescr.colorAttachments[0].storeAction = .store
let value = Double(sin(1.00 * CACurrentMediaTime()))
passDescr.colorAttachments[0].clearColor = MTLClearColor(red: value, green: value, blue: value, alpha: 0.5)
if let commandQueue = device.makeCommandQueue(),
let commandBuffer = commandQueue.makeCommandBuffer(),
let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: passDescr){
commandEncoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.commit()
}
}
}
// MARK: Archive
@objc override func awakeFromNib() {
Swift.print(self.layer?.description ?? "No layer")
}
// MARK: Actions
@IBAction func showInfo(_ sender : AnyObject) -> Void{
Swift.print(self.description , " - ", self.layer?.description ?? "No layer")
Swift.print("layer delegate : ", self.layer?.delegate?.description ?? "No layer delegate")
needsDisplay = true
redraw()
}
}
// MARK: CALayerDelegate
extension GIMTLView : CALayerDelegate{
@objc func display(_ layer: CALayer) {
let drawable = self.mlLayer?.nextDrawable()
Swift.print(self.layer?.description ?? "No layer")
Swift.print(drawable?.description ?? "No rawable")
}
@objc func layerWillDraw(_ layer: CALayer){
Swift.print(self.description , " - ", self.layer?.description ?? "No layer")
Swift.print("layer delegate : ", self.layer?.delegate?.description ?? "No layer delegate")
}
}
| mit | 65d6d1da17f33e13322d85bf99efcda6 | 28.458599 | 150 | 0.633081 | 4.579208 | false | false | false | false |
tbaranes/SwiftyUtils | Sources/Extensions/UIKit/UICollectionViewCell/UICollectionViewCellExtension.swift | 1 | 2408 | //
// UICollectionViewCell.swift
// SwiftyUtils iOS
//
// Created by Tom Baranes on 25/04/2020.
// Copyright © 2020 Tom Baranes. All rights reserved.
//
#if os(iOS)
import UIKit
extension UICollectionViewCell {
/// Apply corner radius to the cell.
/// - Parameters:
/// - radius: The radius that will be applied to the cell.
public func applyCornerRadius(_ radius: CGFloat) {
contentView.layer.cornerRadius = radius
contentView.layer.masksToBounds = true
}
}
// MARK: - Animations
extension UICollectionViewCell {
/// Configure and animate the cell animation, mainly used when the cell is highlighted.
/// - Parameters:
/// - shouldScale: Either the animation should do a scale animation or not.
/// - duration: The animation duration. Default value is `0.35`
/// - transformScale: The transform scale delta. Default value is `0.97`
/// - damping: The damping ratio for the spring animation as it approaches its quiescent state.
/// Default value is `0.7`
/// - options: A mask of options indicating how you want to perform the animations. Default value is empty.
/// - delay: The delay duration before starting the animation. Default value is `0.0`
/// - velocity: `CGFloat`, default is `0.0`
/// - completion: An optional block called once the animation did finish. Default value is nil.
public func animate(scale: Bool,
duration: TimeInterval = 0.35,
transformScale: CGFloat = 0.97,
damping: CGFloat = 0.7,
options: UIView.AnimationOptions = [],
delay: TimeInterval = 0.0,
velocity: CGFloat = 0.0,
completion: ((Bool) -> Void)? = nil) {
UIView.animate(withDuration: duration,
delay: delay,
usingSpringWithDamping: damping,
initialSpringVelocity: velocity,
options: options,
animations: { [unowned self] in
let scaleTransform = CGAffineTransform(scaleX: transformScale, y: transformScale)
self.contentView.transform = scale ? scaleTransform : .identity
}, completion: completion)
}
}
#endif
| mit | f92db92b89d4b7624333244ebd11ffed | 39.116667 | 115 | 0.584961 | 5.014583 | false | false | false | false |
blast78/laposte-sdk-ios-ci | LaPosteEasyServices/LaPoste.swift | 1 | 7149 | //
// LaPoste.swift
// LaPosteEasyServices
//
// Created by Grunt on 02/02/2017.
// Copyright © 2017 Grunt. All rights reserved.
//
import Foundation
import Alamofire
public class LaPoste {
//the key used by the server to authenticate (must subscribe to the service before)
static let serverKey = "VBOAJGog/9iuodsBEzlQNctU0b4479aR0QV/RlOzTShg6jPxme/dyAY/7gdIa8NZ"
//the api URL
static let apiUrl = "https://api.laposte.fr/"
//the endpoint for the price request
static let apiEndPointTarif = "tarifenvoi/v1?"
//the endpoint for the track request
static let apiEndPointTrack = "suivi/v1/?"
/**
* Static function that takes 2 parameters and escapes a completionHandler to return the returnValue
* and the error. Both may be nil.
* If a request is successful, it will return an array of PriceResponse for the value and nil for the
* error
* If a request fails, it will return nil for the value and the error
* @param type : String that defines the type of package to send. According to the doc, values can be
* “colis”, “chronopost”, or “lettre”. If the value is incorrect the default value will be “lettre”
* @param weight : Int that corresponds to the weight of the package in milligrams
**/
class func getPackagePrice(type: String, weight: Int, completionHandler: @escaping (Array<PriceResponse>?, Error?) -> ()) {
//format the header to authorize and get correct response format
let headers: HTTPHeaders = [
"X-Okapi-Key":LaPoste.serverKey,
"Accept": "application/json"
]
//send the request with headers, format it with apiUrl and correct endpoint, then add the
//parameters.
Alamofire.request("\(apiUrl)\(apiEndPointTarif)type=\(type)&weight=\(weight)", headers: headers)
.validate(contentType: ["application/json"])
.responseJSON { response in
//test the response to know if it failed or succeeded
switch response.result {
case .success(let value):
//we get the array of responses
let array = value as! Array<Any>
//we create a new array to store the formatted objects
var responses: [PriceResponse] = []
//we loop in the array to populate the formatted array
for i in (0..<array.count) {
//format the entry
if let resp = PriceResponse(json: array[i] as! [String : Any]) {
//then add it to the array
responses.append(resp)
}
}
//return the response array for the value and nil for the error
completionHandler(responses, nil)
case .failure(let error):
//return nil for the value and the error for error
completionHandler(nil, error)
}
}
}
/**
* Static function that takes 1 parameter and escapes a completionHandler to return the returnValue
* and the error. Both may be nil.
* If a request is successful, it will return a TrackResponse for the value and nil for the
* error
* If a request fails, it will return nil for the value and the error
* @param code : String that defines the code of the package to track. According to the doc, the
* string size has to be 13 characters to be valid
**/
class func getTrack(code: String, completionHandler: @escaping (TrackResponse?, Error?) -> ()) {
//format the header to authorize and get correct response format
let headers: HTTPHeaders = [
"X-Okapi-Key":LaPoste.serverKey,
"Accept": "application/json"
]
//send the request with headers, format it with apiUrl and correct endpoint, then add the
//parameters.
Alamofire.request("\(apiUrl)\(apiEndPointTrack)?code=\(code)", headers: headers)
.validate(contentType: ["application/json"])
.responseJSON { response in
//test the response to know if it failed or succeeded
switch response.result {
case .success(let value):
//we get the response and format it in a TrackResponse object
let track = TrackResponse(json: value as! [String : Any])
//return the value and a nil error
completionHandler(track, nil)
case .failure(let error):
//return nil for the value and the error
completionHandler(nil, error)
}
}
}
class func getCheckAddress(address: String, completionHandler: @escaping (CheckedAddress?, Error?) -> ()) {
let headers: HTTPHeaders = [
"X-Okapi-Key":LaPoste.serverKey,
"Accept": "application/json"
]
print("---Request prepared---")
Alamofire.request("https://api.laposte.fr/controladresse/v1/adresses?q=\(address)", headers: headers)
.validate(contentType: ["application/json"])
.responseJSON { response in
print("---Response received---")
//print(response)
switch response.result {
case .success(let value):
print(value)
let dico = value as! Array<Any>
var responses: [CheckAddress] = []
for i in (0..<dico.count) {
if let resp = CheckAddress(json: dico[i] as! [String : Any]) {
responses.append(resp)
}
}
if (responses.count > 0) {
let requestCode = responses[0].code
Alamofire.request("https://api.laposte.fr/controladresse/v1/adresses/\(requestCode)", headers: headers)
.validate(contentType: ["application/json"])
.responseJSON { response in
print("---Response received---")
//print(response)
switch response.result {
case .success(let value):
print(value)
let checkedAddress = CheckedAddress(json: value as! [String : Any])
completionHandler(checkedAddress, nil)
case .failure(let error):
completionHandler(nil, error)
}
}
}
//completionHandler(responses, nil)
case .failure(let error):
completionHandler(nil, error)
}
}
}
}
| bsd-3-clause | 010dc103e1fcc0d7e04d993ca64245c3 | 45.614379 | 127 | 0.538699 | 5.047417 | false | false | false | false |
DanielSmith1239/KosherSwift | KosherSwift/Categories/Foundation/nsdate/NSDate_Components.swift | 1 | 4257 | //
// Created by Daniel Smith on 3/9/16.
// Copyright (c) 2016 Dani Smith. All rights reserved.
//
import Foundation
extension NSDate
{
class public func dateWithDay(day: Int, month: Int, year: Int) -> NSDate
{
return NSDate.dateWithDay(day, Month: month, Year: year, andCalendar: NSDate.defaultCalendar())
}
class public func dateWithDay(day: Int, Month month: Int, Year year: Int, andCalendar calendar: NSCalendar) -> NSDate
{
let components: NSDateComponents = NSDateComponents()
components.day = day
components.month = month
components.year = year
return calendar.dateFromComponents(components)!
}
class public func dateWithEra(era: Int, year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, week: Int, weekday: Int, weekdayOrdinal: Int, andCalendar calendar: NSCalendar) -> NSDate
{
let components: NSDateComponents = NSDateComponents()
components.era = era
components.year = year
components.month = month
components.day = day
components.hour = hour
components.minute = minute
components.second = second
components.weekOfYear = week
components.weekday = weekday
components.weekdayOrdinal = weekdayOrdinal
return calendar.dateFromComponents(components)!
}
class public func defaultEraForCalendar(calendar: NSCalendar) -> Int
{
return NSDate.defaultComponentsForCalendar(calendar).era
}
class public func defaultYearForCalendar(calendar: NSCalendar) -> Int
{
return NSDate.defaultComponentsForCalendar(calendar).year
}
class public func defaultMonthForCalendar(calendar: NSCalendar) -> Int
{
return NSDate.defaultComponentsForCalendar(calendar).month
}
class public func defaultDayForCalendar(calendar: NSCalendar) -> Int
{
return NSDate.defaultComponentsForCalendar(calendar).day
}
class public func defaultHourForCalendar(calendar: NSCalendar) -> Int
{
return NSDate.defaultComponentsForCalendar(calendar).hour
}
class public func defaultMinuteForCalendar(calendar: NSCalendar) -> Int
{
return NSDate.defaultComponentsForCalendar(calendar).minute
}
class public func defaultSecondForCalendar(calendar: NSCalendar) -> Int
{
return NSDate.defaultComponentsForCalendar(calendar).second
}
class public func defaultWeekForCalendar(calendar: NSCalendar) -> Int
{
return NSDate.defaultComponentsForCalendar(calendar).weekOfYear
}
class public func defaultWeekdayForCalendar(calendar: NSCalendar) -> Int
{
return NSDate.defaultComponentsForCalendar(calendar).weekday
}
class public func defaultWeekdayOrdinalForCalendar(calendar: NSCalendar) -> Int
{
return NSDate.defaultComponentsForCalendar(calendar).weekdayOrdinal
}
class public func defaultEra() -> Int
{
return NSDate.defaultComponents().era
}
class public func defaultYear() -> Int
{
return NSDate.defaultComponents().year
}
class public func defaultMonth() -> Int
{
return NSDate.defaultComponents().month
}
class public func defaultDay() -> Int
{
return NSDate.defaultComponents().day
}
class public func defaultHour() -> Int
{
return NSDate.defaultComponents().hour
}
class public func defaultMinute() -> Int
{
return NSDate.defaultComponents().minute
}
class public func defaultSecond() -> Int
{
return NSDate.defaultComponents().second
}
class public func defaultWeek() -> Int
{
return NSDate.defaultComponents().weekOfYear
}
class public func defaultWeekday() -> Int
{
return NSDate.defaultComponents().weekday
}
class public func defaultWeekdayOrdinal() -> Int
{
return NSDate.defaultComponents().weekdayOrdinal
}
class public func defaultComponents() -> NSDateComponents
{
return defaultComponentsForCalendar(NSDate.defaultCalendar())
}
class public func defaultComponentsForCalendar(calendar: NSCalendar) -> NSDateComponents
{
return calendar.components([.Era, .Year, .Month, .Day, .Hour, .Minute, .Second, .Weekday, .WeekdayOrdinal, .Quarter, .WeekOfYear, .WeekOfMonth, .YearForWeekOfYear, .Calendar, .TimeZone], fromDate:NSDate())
}
class public func defaultCalendar() -> NSCalendar
{
return NSCalendar.currentCalendar()
}
} | lgpl-3.0 | 6600831cd336cac64701c0e4ccb8192b | 26.294872 | 210 | 0.730092 | 4.210682 | false | false | false | false |
paulofaria/SwiftHTTPServer | HTML Response/HTTPResponse+HTML.swift | 3 | 1952 | // HTTPResponse+HTML.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
extension HTTPResponse {
init(
status: HTTPStatus = .OK,
headers: [String: String] = [:],
HTML: String) {
self.init(
status: status,
headers: headers + ["content-type": "text/html"],
body: Data(string: HTML)
)
}
init(
status: HTTPStatus = .OK,
headers: [String: String] = [:],
HTMLPath: String) throws {
guard let file = File(path: HTMLPath) else {
throw Error.Generic("File Body", "Could not find file \(HTMLPath)")
}
self.init(
status: status,
headers: headers + ["content-type": "text/html"],
body: file.data
)
}
} | mit | 4e67d4ba2aa01c2fd99b498e5ac2cec9 | 32.101695 | 83 | 0.630635 | 4.58216 | false | false | false | false |
laszlokorte/reform-swift | ReformExpression/ReformExpression/Solver.swift | 1 | 1998 | //
// Solver.swift
// ExpressionEngine
//
// Created by Laszlo Korte on 07.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
final public class Solver {
let dataSet : WritableDataSet
public init(dataSet: WritableDataSet) {
self.dataSet = dataSet
}
public func evaluate(_ sheet : Sheet)
{
dataSet.clear()
let (duplicates, definitions) = sheet.sortedDefinitions
for defValue in definitions {
let id = defValue.id
switch defValue.value {
case .array(_):
fatalError()
case .expr(let expr):
let result = expr.eval(dataSet)
switch result {
case .success(let value):
dataSet.put(id, value: value)
case .fail(let error):
dataSet.put(id, value: Value.intValue(value: 0))
dataSet.markError(id, error: error)
}
case .primitive(let value):
dataSet.put(id, value: value)
default:
break
}
}
for d in duplicates {
dataSet.markError(d, error: EvaluationError.duplicateDefinition(referenceId: d))
}
}
}
final public class WritableDataSet : DataSet {
var data : [ReferenceId:Value] = [ReferenceId:Value]()
var errors: [ReferenceId:EvaluationError] = [ReferenceId:EvaluationError]()
public init() {
}
public func lookUp(_ id: ReferenceId) -> Value? {
return data[id]
}
public func getError(_ id: ReferenceId) -> EvaluationError? {
return errors[id]
}
func put(_ id: ReferenceId, value: Value) {
data[id] = value
}
func markError(_ id: ReferenceId, error: EvaluationError) {
errors[id] = error
}
func clear() {
errors.removeAll()
data.removeAll()
}
}
| mit | b7a7b36d5bf092445c111436ed943d5f | 24.602564 | 92 | 0.529795 | 4.665888 | false | false | false | false |
cnoon/swift-compiler-crashes | crashes-duplicates/24715-no-stacktrace.swift | 9 | 2389 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
0.a")
0.C
class A?enum S<T where B:e
0.E
func b<T where B :P
enum b {
[]
struct B<d { func b: b { func b:b
st
class B, leng
func a<d {
a {
}
}
}
}
protocol P {
protocol P {
protocol e {
func b<d where B :{
b: A.E
0.c : a{{
protocol c {
protocol c {
protocol e : e : a {
func a
0.E
class A {
}
typealias e func a
struct B<T where T where H:{
let a
struct B:A? f: a {
}
class A {
class b:a<H : e {} k. "))))
enum B : b {}{
protocol A.a"
0.g:P{
[]
protocol P {
class b
protocol e {
}enum S<T : a {
import c}
}
b<H:P
enum b { b<H : b {
var _ = b:a
class A {}
protocol B : b {
st
g {
func c
class A
protocol P {
var f.C
let a"
}
}{
class a
func a
struct B, leng
[]
enum B{{
[]
func a
}
protocol e {protocol P {
extension NSData {protocol P {
class x
enum S<d {
impundation
class A {
0.C
let t: A{
return ")
}
class A {
st
0.E
protocol c {let start = c
class B<H : A {
class A {{
protocol e : b { b<d {V
protocol c {
struct B<H : e}
}
protocol A {
let start = c
protocol P {
func b
extension NSData {
}
}}struct B, leng
class b
enum B<T where T{
0.a
st
class A {var d where B : e = c
func a")
}
class A {
}
var a{
enum B :{func a(")
struct B, leng
protocol e : a {
var _ = F>(a{
0.c : A{var _ = B:P
protocol P {
struct B, leng
class b
struct B< E {
st
}
struct B, leng
enum S<d where g: A.C
struct B, leng
protocol B :A
class b<T where B :g{a
class A {
func a
func a<H : A {
<T where T where B{
func a
func a"
protocol c {
<A.g "
class A {
class A {
typealias e = F>()e:)}}}}}}var b{class A{func d<S:d
}
let start = b{
class A {
typealias e : a {
}
typealias e : e : a {{
protocol c {
typealias F = B, leng
0.C
[]
st
return "
}enum S{
}
class A.c : A.g ")
}
[]
0.a
}
}
impundation
class A {var f
class A {
struct Q<H : b {
func b{
<d {
typealias e : a {}
func b
g {{{
class A {
b: f: e : b { func b{
extension NSData {
[]
{}
<T where T : e : A
}enum b {
0.E
func a<T where T {}
struct B:a<T : a
<H : A.c : a {}struct d {
struct B, leng
return "
}
typealias F>()e:)}}}}}}var b{class A{func d<S:d
let t: a {var f: P{
class A {
protocol A {
class a{
func c
protocol e {
import c}
class A.a<T where g{
class b{
<T {
func a
protocol A {
if true {}
func a(a=0.a("
}enum b { func c
<T where f: P
[a:T{
typealias e : A.a<d {
let t: f
| mit | cdfdd7ac2867e55e34d0bf024f02e350 | 11.005025 | 87 | 0.599414 | 2.314922 | false | false | false | false |
steelwheels/Coconut | CoconutData/Test/UnitTest/UTAttributedString.swift | 1 | 5767 | /**
* @file UTAttrobutedString.swift
* @brief Test function for CNAttributedString
* @par Copyright
* Copyright (C) 2019 Steel Wheels Project
*/
#if os(OSX)
import Cocoa
#endif
import CoconutData
import Foundation
private struct TestString {
var text: NSMutableAttributedString
var index: Int
public init(text txt: String, index idx: Int) {
let t = NSMutableAttributedString(string: txt)
self.text = t
self.index = idx
}
public func dump(console cons: CNConsole) {
var ptr = 0
let end = text.string.count
cons.print(string: "-------- [begin]\n")
while ptr < end {
if ptr == index {
cons.print(string: "*")
} else {
cons.print(string: ".")
}
if let c = text.character(at: ptr) {
if c == " " {
cons.print(string: "_")
} else if c.isNewline {
cons.print(string: "$\n")
} else {
cons.print(string: "\(c)")
}
} else {
cons.print(string: "Invalid-index")
}
ptr += 1
}
if index == end {
cons.print(string: "*<")
}
cons.print(string: "\n-------- [end]\n")
}
}
public func testAttributedString(console cons: CNConsole) -> Bool
{
let vectors: Array<TestString> = [
TestString(text: "abc", index: 1),
TestString(text: "abc\ndef\nghi\n", index: 6),
TestString(text: "ドライブ", index: 3),
TestString(text: "ドライブ1\nドライブ2\n", index: 4)
]
var result0 = true
for vector in vectors {
let terminfo = CNTerminalInfo(width: 40, height: 10)
if !testVector(vector: vector, console: cons, terminalInfo: terminfo) {
result0 = false
}
}
let result1 = testPadding(console: cons)
let result = result0 && result1
if result {
cons.print(string: "testAttributedString .. OK\n")
} else {
cons.print(string: "testAttributedString .. NG\n")
}
return result
}
private func testVector(vector src: TestString, console cons: CNConsole, terminalInfo terminfo: CNTerminalInfo) -> Bool
{
cons.print(string: "Start Vector Test --------------\n")
let fnt = NSFont.systemFont(ofSize: 10.0)
var vec = src
vec.dump(console: cons)
let cnt = vec.text.lineCount(from: 0, to: vec.text.string.count)
cons.print(string: "Line count = \(cnt)\n")
let hoff = vec.text.distanceFromLineStart(to: vec.index)
cons.print(string: "holizOffset = \(hoff)\n")
let hroff = vec.text.distanceToLineEnd(from: vec.index)
cons.print(string: "holizReverseOffset = \(hroff)\n")
cons.print(string: "moveCursorBackward(1)\n")
vec.index = vec.text.moveCursorBackward(from: vec.index, number: 1)
vec.dump(console: cons)
cons.print(string: "moveCursorBackward(2)\n")
vec.index = vec.text.moveCursorBackward(from: vec.index, number: 2)
vec.dump(console: cons)
cons.print(string: "moveCursorForward(3)\n")
vec.index = vec.text.moveCursorForward(from: vec.index, number: 3)
vec.dump(console: cons)
cons.print(string: "moveCursorForward(4)\n")
vec.index = vec.text.moveCursorForward(from: vec.index, number: 4)
vec.dump(console: cons)
cons.print(string: "moveCursorToLineStart\n")
vec.index = vec.text.moveCursorToLineStart(from: vec.index)
vec.dump(console: cons)
cons.print(string: "moveCursorToLineEnd\n")
vec.index = vec.text.moveCursorToLineEnd(from: vec.index)
vec.dump(console: cons)
cons.print(string: "moveCursorUpOrDown(up, 1)\n")
vec.index = vec.text.moveCursorUpOrDown(from: vec.index, doUp: true, number: 1)
vec.dump(console: cons)
cons.print(string: "moveCursorUpOrDown(down, 2)\n")
vec.index = vec.text.moveCursorUpOrDown(from: vec.index, doUp: false, number: 2)
vec.dump(console: cons)
cons.print(string: "moveCursorTo(x=1)\n")
vec.index = vec.text.moveCursorTo(from: vec.index, x: 1)
vec.dump(console: cons)
cons.print(string: "moveCursorTo(x=0, y=1)\n")
vec.index = vec.text.moveCursorTo(x: 0, y: 1)
vec.dump(console: cons)
cons.print(string: "moveCursorForward(2)\n")
vec.index = vec.text.moveCursorForward(from: vec.index, number: 2)
vec.dump(console: cons)
cons.print(string: "insert(\"ドライブ\", \(vec.index)\n")
vec.text.insert(NSAttributedString(string: "ドライブ"), at: vec.index)
vec.dump(console: cons)
cons.print(string: "write(\"ABCD\")\n")
vec.index = vec.text.write(string: "ABCD", at: vec.index, font: fnt, terminalInfo: terminfo)
vec.dump(console: cons)
cons.print(string: "moveCursorBackward(2)\n")
vec.index = vec.text.moveCursorBackward(from: vec.index, number: 2)
vec.dump(console: cons)
cons.print(string: "deleteForwardCharacters(1)\n")
vec.index = vec.text.deleteForwardCharacters(from: vec.index, number: 1)
vec.dump(console: cons)
cons.print(string: "deleteBackwardCharacters(1)\n")
vec.index = vec.text.deleteBackwardCharacters(from: vec.index, number: 1)
vec.dump(console: cons)
cons.print(string: "deleteEntireLine\n")
vec.index = vec.text.deleteEntireLine(from: vec.index)
vec.dump(console: cons)
return true
}
private func testPadding(console cons: CNConsole) -> Bool
{
let str1 = TestString(text: "aaa\nbb", index: 0)
let str2 = TestString(text: "aaa\nbb", index: 0)
let str3 = TestString(text: "a\n-b\n--c\n---d\n----e", index: 0)
let str4 = TestString(text: "", index: 0)
//let str5 = TestString(text: "\n", index: 0, xPos: 0, yPos: 0)
//let str6 = TestString(text: "a", index: 0, xPos: 0, yPos: 0)
//let str7 = TestString(text: "a\n", index: 0, xPos: 0, yPos: 0)
let strs = [str1, str2, str3, str4] //, str5] //, str6, str7]
for str in strs {
cons.print(string: "*** Test padding\n")
testPadding(string: str, console: cons)
}
return true
}
private func testPadding(string str: TestString, console cons: CNConsole) {
let terminfo = CNTerminalInfo(width: 5, height: 5)
let font = CNFont.systemFont(ofSize: 10.0)
str.text.resize(width: 5, height: 5, font: font, terminalInfo: terminfo)
str.dump(console: cons)
}
| lgpl-2.1 | 8999da2728d9d6dd89e2ad578d65fc40 | 28.520619 | 119 | 0.685525 | 2.822573 | false | true | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile/Profile.swift | 1 | 23360 | //
// Profile.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
import ProfilePayloads
public class Profile: NSDocument, NSCopying {
// MARK: -
// MARK: Constant Variables
let settings: ProfileSettings
// MARK: -
// MARK: Variables
var alert: Alert?
// MARK: -
// MARK: Computer Variables
public var enabledPayloadsCount: Int {
self.settings.payloadSettingsEnabledCount()
}
public var identifier: UUID {
self.settings.identifier
}
public var versionFormatSupported: Bool {
kSaveFormatVersionMin <= self.settings.formatVersion
}
// MARK: -
// MARK: Initialization
override init() {
self.settings = ProfileSettings()
super.init()
// ---------------------------------------------------------------------
// Set reference to self in ProfileSettings
// ---------------------------------------------------------------------
self.settings.profile = self
}
init?(withMobileconfig mobileconfig: [String: Any]) throws {
self.settings = try ProfileSettings(withMobileconfig: mobileconfig)
super.init()
self.settings.profile = self
}
init?(withSettings settings: [String: Any]) throws {
self.settings = try ProfileSettings(withSettings: settings)
super.init()
self.settings.profile = self
}
public func copy(with zone: NSZone? = nil, withTitle title: String) -> Any {
guard let newProfile = self.copy() as? Profile else { return Profile() }
newProfile.fileURL = nil
newProfile.settings.setValue(title, forValueKeyPath: PayloadKey.payloadDisplayName, domainIdentifier: kManifestDomainConfiguration, payloadType: .manifestsApple, payloadIndex: 0)
newProfile.settings.updateUUIDs()
// -------------------------------------------------------------
// Save the profile to disk
// -------------------------------------------------------------
newProfile.save(self)
return newProfile
}
public func copy(with zone: NSZone? = nil) -> Any {
do {
guard let copy = try Profile(withSettings: self.settings.currentSettings()) else { return Profile() }
return copy
} catch {
Log.shared.error(message: "Failed to copy profile with error: \(error)", category: String(describing: self))
return Profile()
}
}
func saveCheck(key: String, value: Any, newValue: Any?) {
if
let valueDict = value as? [String: Any],
let newValueDict = newValue as? [String: Any] {
if valueDict != newValueDict {
Log.shared.debug(message: "The key: \(key) (Dictionary) has a new value")
for (key, value) in valueDict {
self.saveCheck(key: key, value: value, newValue: newValueDict[key])
}
return
}
} else if
let valueString = value as? String,
let newValueString = newValue as? String {
if valueString != newValueString {
Log.shared.debug(message: "The key: \(key) (String) has a new value")
Log.shared.debug(message: "The key: \(key) saved value: \(valueString)")
Log.shared.debug(message: "The key: \(key) new value: \(newValueString)")
}
return
} else if
let valueInt = value as? Int,
let newValueInt = newValue as? Int {
if valueInt != newValueInt {
Log.shared.debug(message: "The key: \(key) (Int) has a new value")
Log.shared.debug(message: "The key: \(key) saved value: \(valueInt)")
Log.shared.debug(message: "The key: \(key) new value: \(newValueInt)")
}
return
} else if
let valueBool = value as? Bool,
let newValueBool = newValue as? Bool {
if valueBool != newValueBool {
Log.shared.debug(message: "The key: \(key) (Bool) has a new value")
Log.shared.debug(message: "The key: \(key) saved value: \(valueBool)")
Log.shared.debug(message: "The key: \(key) new value: \(newValueBool)")
}
return
} else if
let valueArray = value as? [Any],
let newValueArray = newValue as? [Any] {
Log.shared.debug(message: "The key: \(key) (Array) might have a new value. Currently arrays can't be compared")
Log.shared.debug(message: "The key: \(key) saved value: \(valueArray)")
Log.shared.debug(message: "The key: \(key) new value: \(newValueArray)")
return
} else if let valueFloat = value as? Float,
let newValueFloat = newValue as? Float {
if valueFloat != newValueFloat {
Log.shared.debug(message: "The key: \(key) (Float) has a new value")
Log.shared.debug(message: "The key: \(key) saved value: \(valueFloat)")
Log.shared.debug(message: "The key: \(key) new value: \(newValueFloat)")
}
return
} else if let valueDate = value as? Date,
let newValueDate = newValue as? Date {
if valueDate != newValueDate {
Log.shared.debug(message: "The key: \(key) (Date) has a new value")
Log.shared.debug(message: "The key: \(key) saved value: \(valueDate)")
Log.shared.debug(message: "The key: \(key) new value: \(newValueDate)")
}
return
} else if let valueData = value as? Data,
let newValueData = newValue as? Data {
if valueData != newValueData {
Log.shared.debug(message: "The key: \(key) (Data) has a new value")
Log.shared.debug(message: "The key: \(key) saved value: \(valueData)")
Log.shared.debug(message: "The key: \(key) new value: \(newValueData)")
}
return
}
}
// MARK: -
func showAlertUnsaved(closeWindow: Bool) {
guard
let windowController = self.windowControllers.first as? ProfileEditorWindowController,
let window = windowController.window else { Log.shared.error(message: "No window found for ProfileEditorWindowController", category: String(describing: self)); return }
let alert = Alert()
self.alert = alert
let alertMessage = NSLocalizedString("Unsaved Settings", comment: "")
let alertInformativeText = NSLocalizedString("If you close this window, all unsaved changes will be lost. Are you sure you want to close the window?", comment: "")
if self.settings.title == StringConstant.defaultProfileName {
let firstButtonTitle: String
if closeWindow {
firstButtonTitle = ButtonTitle.saveAndClose
} else {
firstButtonTitle = ButtonTitle.save
}
let informativeText: String
if self.isSaved() {
informativeText = NSLocalizedString("You need to give your profile a name before it can be saved.", comment: "")
} else {
informativeText = alertInformativeText + "\n\n" + NSLocalizedString("You need to give your profile a name before it can be saved.", comment: "")
}
// ---------------------------------------------------------------------
// Show unnamed and unsaved settings alert to user
// ---------------------------------------------------------------------
alert.showAlert(message: alertMessage,
informativeText: informativeText,
window: window,
defaultString: StringConstant.defaultProfileName,
placeholderString: NSLocalizedString("Name", comment: ""),
firstButtonTitle: firstButtonTitle,
secondButtonTitle: ButtonTitle.close,
thirdButtonTitle: ButtonTitle.cancel,
firstButtonState: true,
sender: self) { newProfileName, response in
switch response {
case .alertFirstButtonReturn:
self.settings.setValue(newProfileName, forValueKeyPath: PayloadKey.payloadDisplayName, domainIdentifier: kManifestDomainConfiguration, payloadType: .manifestsApple, payloadIndex: 0)
self.save(operationType: .saveOperation, completionHandler: { saveError in
if saveError == nil {
if closeWindow {
windowController.performSelector(onMainThread: #selector(windowController.windowClose), with: windowController, waitUntilDone: false)
}
Log.shared.log(message: "Saving profile: \"\(self.settings.title)\" at path: \(self.fileURL?.path ?? "") was successful")
} else {
Log.shared.error(message: "Saving profile: \(self.settings.title) failed with error: \(String(describing: saveError?.localizedDescription))")
}
})
case .alertSecondButtonReturn:
windowController.performSelector(onMainThread: #selector(windowController.windowClose), with: windowController, waitUntilDone: false)
case .alertThirdButtonReturn:
Log.shared.debug(message: "User canceled", category: String(describing: self))
default:
Log.shared.debug(message: "Unknown modal response from alert: \(response)", category: String(describing: self))
}
}
// ---------------------------------------------------------------------
// Select the text field in the alert sheet
// ---------------------------------------------------------------------
if let textFieldInput = alert.textFieldInput {
textFieldInput.selectText(self)
alert.firstButton?.isEnabled = false
}
} else {
// ---------------------------------------------------------------------
// Show unsaved settings alert to user
// ---------------------------------------------------------------------
self.alert?.showAlert(message: alertMessage,
informativeText: alertInformativeText,
window: window,
firstButtonTitle: ButtonTitle.saveAndClose,
secondButtonTitle: ButtonTitle.close,
thirdButtonTitle: ButtonTitle.cancel,
firstButtonState: true,
sender: self) { response in
switch response {
case .alertFirstButtonReturn:
self.save(operationType: .saveOperation, completionHandler: { saveError in
if saveError == nil {
windowController.performSelector(onMainThread: #selector(windowController.windowClose), with: windowController, waitUntilDone: false)
Log.shared.log(message: "Saving profile: \"\(self.settings.title)\" at path: \(self.fileURL?.path ?? "") was successful")
} else {
Log.shared.error(message: "Saving profile: \(self.settings.title) failed with error: \(String(describing: saveError?.localizedDescription))")
}
})
case .alertSecondButtonReturn:
windowController.performSelector(onMainThread: #selector(windowController.windowClose), with: windowController, waitUntilDone: false)
case .alertThirdButtonReturn:
Log.shared.debug(message: "User canceled", category: String(describing: self))
default:
Log.shared.debug(message: "Unknown modal response from alert: \(response)", category: String(describing: self))
}
}
}
}
// MARK: -
// MARK: Public Functions
public func isSaved() -> Bool {
// NOTE: Should maybe use: self.isDocumentEdited and update change counts instead
// ---------------------------------------------------------------------
// Check if the profile document has a url, if not it's never been saved
// ---------------------------------------------------------------------
if self.fileURL == nil { return false }
// ---------------------------------------------------------------------
// Get the current settings dictionary
// ---------------------------------------------------------------------
// let settingsCurrent = self.settings.settingsCurrent()
let currentSettings = self.settings.currentSettings()
#if DEBUG
// ---------------------------------------------------------------------
// DEBUG: Print all settings that has changed
// ---------------------------------------------------------------------
for (key, value) in self.settings.settingsSaved {
self.saveCheck(key: key, value: value, newValue: currentSettings[key])
}
#endif
// ---------------------------------------------------------------------
// Compare the saved settings to current settings to determine if something has changed
// ---------------------------------------------------------------------
return self.settings.settingsSaved == currentSettings
}
public func edit() {
let windowController: NSWindowController
if 0 < self.windowControllers.count {
windowController = self.windowControllers.first!
} else {
windowController = ProfileEditorWindowController(profile: self)
self.addWindowController(windowController)
}
windowController.window?.makeKeyAndOrderFront(self)
}
// MARK: -
// MARK: Private Functions
private func saveURL(profilesDirectoryURL: URL) -> URL? {
if UserDefaults.standard.string(forKey: PreferenceKey.profileLibraryFileNameFormat) == ProfileLibraryFileNameFormat.payloadIdentifier {
guard let payloadIdentifier = self.settings.value(forValueKeyPath: PayloadKey.payloadIdentifier, domainIdentifier: kManifestDomainConfiguration, payloadType: .manifestsApple, payloadIndex: 0) as? String else { return nil }
return profilesDirectoryURL.appendingPathComponent(payloadIdentifier).appendingPathExtension(FileExtension.profile)
} else {
return profilesDirectoryURL.appendingPathComponent(self.identifier.uuidString).appendingPathExtension(FileExtension.profile)
}
}
private func save(operationType: NSDocument.SaveOperationType, completionHandler: @escaping (Error?) -> Void) {
// ---------------------------------------------------------------------
// Get path to profile save folder
// ---------------------------------------------------------------------
guard let profilesDirectoryURL = URL(applicationDirectory: .profiles) else {
// FIXME: Correct Error
return
}
// ---------------------------------------------------------------------
// Get or create a new path for the profile save file
// ---------------------------------------------------------------------
let saveURL: URL
var moveURL: URL?
if let currentSaveURL = self.saveURL(profilesDirectoryURL: profilesDirectoryURL) {
if let fileURL = self.fileURL, fileURL != currentSaveURL {
saveURL = fileURL
moveURL = currentSaveURL
} else {
saveURL = currentSaveURL
}
} else if let fileURL = self.fileURL {
saveURL = fileURL
} else {
saveURL = profilesDirectoryURL.appendingPathComponent(self.identifier.uuidString).appendingPathExtension(FileExtension.profile)
}
// ---------------------------------------------------------------------
// Call the NSDocument save function
// ---------------------------------------------------------------------
super.save(to: saveURL, ofType: TypeName.profile, for: operationType) { saveError in
if saveError == nil {
// -----------------------------------------------------------------
// Post notification that this profile was saved
// -----------------------------------------------------------------
NotificationCenter.default.post(name: .didSaveProfile, object: self, userInfo: [NotificationKey.identifier: self.identifier])
// -----------------------------------------------------------------
// Update settingsSaved with the settings that were written to disk
// -----------------------------------------------------------------
self.settings.settingsSaved = self.settings.currentSettings()
if let targetURL = moveURL {
guard !FileManager.default.fileExists(atPath: targetURL.path) else {
let error = NSError(domain: "profileCreatorError", code: -1, userInfo: [NSLocalizedDescriptionKey: "File already exists at target path: \(targetURL.path)"]) as Error
completionHandler(error)
return
}
super.move(to: targetURL, completionHandler: completionHandler)
}
} else { completionHandler(saveError) }
}
}
}
// MARK: -
// MARK: NSDocument Functions
extension Profile {
override public func makeWindowControllers() {
let windowController = ProfileEditorWindowController(profile: self)
self.addWindowController(windowController)
}
override public func save(_ sender: Any?) {
if self.settings.title == StringConstant.defaultProfileName { self.showAlertUnsaved(closeWindow: false); return }
self.save(operationType: .saveOperation) { saveError in
if saveError == nil {
Log.shared.log(message: "Saving profile: \"\(self.settings.title)\" at path: \(self.fileURL?.path ?? "") was successful")
} else {
Log.shared.error(message: "Saving profile: \(self.settings.title) failed with error: \(String(describing: saveError?.localizedDescription))")
}
}
}
override public func data(ofType typeName: String) throws -> Data {
guard typeName == TypeName.profile else {
// FIXME: Correct Error
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
do {
let profileData = try PropertyListSerialization.data(fromPropertyList: self.settings.currentSettings(), format: .xml, options: 0)
return profileData
} catch { Log.shared.error(message: "Creating property list from current settings failed with error: \(error)", category: String(describing: self)) }
// FIXME: Correct Error
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
override public func read(from data: Data, ofType typeName: String) throws {
guard typeName == TypeName.profile else {
// FIXME: Correct Error
throw NSError(type: .unknown)
}
do {
if let profileDict = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] {
/*
guard
let saveFormatVersion = profileDict[SettingsKey.saveFormatVersion] as? Int,
kSaveFormatVersionMin <= saveFormatVersion else {
// FIXME: Correct Error
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
*/
self.settings.restoreSettingsSaved(profileDict)
return
}
} catch {
// TODO: Proper Logging
}
// Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false.
// You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead.
// If you override either of these, you should also override -isEntireFileLoaded to return false if the contents are lazily loaded.
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
}
// MARK: -
// MARK: NSTextFieldDelegate Functions
extension Profile: NSTextFieldDelegate {
// -------------------------------------------------------------------------
// Used when selecting a new profile name to not allow default or empty name
// -------------------------------------------------------------------------
public func controlTextDidChange(_ notification: Notification) {
// ---------------------------------------------------------------------
// Get current text in the text field
// ---------------------------------------------------------------------
guard let userInfo = notification.userInfo,
let fieldEditor = userInfo["NSFieldEditor"] as? NSTextView,
let string = fieldEditor.textStorage?.string else {
return
}
// ---------------------------------------------------------------------
// If current text in the text field is either:
// * Empty
// * Matches the default profile name
// Disable the OK button.
// ---------------------------------------------------------------------
if let alert = self.alert {
if alert.firstButton!.isEnabled && (string.isEmpty || string == StringConstant.defaultProfileName) {
alert.firstButton!.isEnabled = false
} else {
alert.firstButton!.isEnabled = true
}
}
}
}
| mit | 0297bb5eb004e86ee9d5f7a859541ae9 | 47.162887 | 234 | 0.507941 | 5.883879 | false | false | false | false |
an-indya/SupportMate | SupportMate/TeamViewController.swift | 1 | 4155 | //
// TeamViewController.swift
// SupportMate
//
// Created by Anindya Sengupta on 5/10/15.
// Copyright (c) 2015 Anindya Sengupta. All rights reserved.
//
import UIKit
import CoreData
let reuseIdentifier = "TeamCollectionViewCell"
class TeamViewController: UICollectionViewController {
var teamMembers = [TeamMember]()
let managedObjectContext = ((UIApplication.sharedApplication()).delegate as!AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Team Members"
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
if appDel.role == "Manager" {
let barbuttonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addTeamMember")
self.navigationItem.rightBarButtonItem = barbuttonItem
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Create a new fetch request using the LogItem entity
let fetchRequest = NSFetchRequest(entityName: "TeamMember")
// Execute the fetch request, and cast the results to an array of LogItem objects
if let fetchResults = (try? managedObjectContext!.executeFetchRequest(fetchRequest)) as? [TeamMember] {
teamMembers = fetchResults
print(teamMembers)
collectionView?.reloadData()
}
}
func addTeamMember () {
performSegueWithIdentifier("AddMemberDetails", sender: self)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let cell = sender as! UICollectionViewCell
if segue.identifier == "ShowTeamMemberDetails" {
let indexPath = collectionView!.indexPathForCell(cell)
let destinationViewController = segue.destinationViewController as! TeamMemberDetailsViewController;
destinationViewController.teamMember = teamMembers[indexPath!.row]
}
else if segue.identifier == "AddMemberDetails" {
}
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return teamMembers.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! TeamCollectionViewCell
let member = teamMembers[indexPath.row] as TeamMember
let image = UIImage(named: member.image)
cell.teamMember.image = image
return cell
}
// MARK: UICollectionViewDelegate
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
*/
}
| mit | 1ff7c051525b01830cf1d5f7ade390e6 | 34.512821 | 185 | 0.701324 | 5.952722 | false | false | false | false |
midoks/Swift-Learning | GitHubStar/GitHubStar/GitHubStar/Vendor/GitHub/GitHubApi.swift | 1 | 11437 |
//
// GitHubApi.swift
// GitHubStar
//
// Created by midoks on 15/12/18.
// Copyright © 2015年 midoks. All rights reserved.
//
import Foundation
import UIKit
import SwiftyJSON
import Alamofire
//MARK: - 基本的设置功能 -
public class GitHubApi:NSObject {
public var clientID:String = ""
public var clientSecret:String = ""
public var scope:String = "user,user:follow,repo,public_repo,notifications,gist,read:org"
let apiUrl = "https://api.github.com"
public var request:NSMutableURLRequest?
public var task:URLSessionDataTask?
public var session:URLSession?
public var oauth_token:String?
public var isShowAlert = false
static let instance = GitHubApi()
//设置应用的clientID,clientSecret
init(clientID:String = "", clientSecret:String = ""){
self.clientID = clientID
self.clientSecret = clientSecret
}
//实例化再配置
func initConfig(clientID:String, clientSecret:String){
self.clientID = clientID
self.clientSecret = clientSecret
}
//设置访问权限
func setScope(scope:String){
self.scope = scope
}
//组装url
func buildUrl(path:String) -> String {
let url = apiUrl + path
return url
}
//组装url
func bulidUrl(path:String, params:Dictionary<String, String>) -> String {
let url = path + "?" + self.buildParam(params: params)
return url
}
//组装参数
public func buildParam(params:Dictionary<String, String>) -> String {
var args = ""
for (k,v) in params {
if(!k.isEmpty){
args += k + "=" + v + "&"
}else{
args = v
}
}
return args.trim()
}
}
//MARK: - 数据请求 -
extension GitHubApi{
//GET获取数据带参数
public func get(url:String, params: Dictionary<String, String> = Dictionary<String, String>(), callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){
MDTask.shareInstance.asynTaskBack {
self.request(method: "GET", url: url, params: params, callback: callback)
}
}
//POST数据
public func post(url:String, params: Dictionary<String, String> = Dictionary<String, String>(), callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){
MDTask.shareInstance.asynTaskBack {
self.request(method: "POST", url: url, params: params, callback: callback)
}
}
//PUT数据
func put(url:String, params: Dictionary<String, String> = Dictionary<String, String>(), callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){
MDTask.shareInstance.asynTaskBack {
self.request(method: "PUT", url: url, params: params, callback: callback)
}
}
//DELETE数据
func delete(url:String, params: Dictionary<String, String> = Dictionary<String, String>(), callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){
MDTask.shareInstance.asynTaskBack {
self.request(method: "DELETE", url: url, params: params, callback: callback)
}
}
//更全面的请求
private func request(method:String, url:String, params: Dictionary<String, String> = Dictionary<String, String>(), callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){
var newURL = url
//GET传值
if method == "GET" {
if newURL.range(of: "?") == nil {
if params.count > 0 {
newURL += "?" + self.buildParam(params: params)
}
} else {
newURL += self.buildParam(params: params)
}
}
//print(newURL)
//newURL = self.buildClientUrl(newURL)
self.request = NSMutableURLRequest(url: NSURL(string: newURL)! as URL)
//self.request!.URL = NSURL(string: newURL)!
self.request?.httpMethod = method
self.request?.addValue("GitHubStar Client/1.0.1([email protected])", forHTTPHeaderField: "User-Agent")
if( self.oauth_token != nil){
self.request?.addValue("token " + self.oauth_token!, forHTTPHeaderField: "Authorization")
}
//POST传值
if method == "POST" {
self.request?.addValue("application/json", forHTTPHeaderField: "Accept")
self.request?.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
self.request?.httpBody = self.buildParam(params: params).data(using: String.Encoding.utf8, allowLossyConversion: true)
} else if method == "PUT" {
self.request?.httpMethod = method
} else if method == "DELETE" {
self.request?.httpMethod = method
}
//执行请求
self.session = URLSession.shared
UIApplication.shared.isNetworkActivityIndicatorVisible = true
self.task = self.session!.dataTask(with: self.request! as URLRequest, completionHandler: { (data, response, error) -> Void in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
MDTask.shareInstance.asynTaskFront(callback: {
callback(data as NSData?, response, error as NSError?)
})
})
self.task!.resume()
}
//设置Header信息
func setHeader(key:String, value:String){
self.request?.addValue(value, forHTTPHeaderField: key)
}
func buildClientUrl(url:String) -> String {
var _url = url
if self.clientID != "" && self.clientSecret != "" {
if url.range(of: "?") == nil {
_url += "?client_id=" + self.clientID + "&client_serect=" + self.clientSecret
} else {
_url += "&client_id=" + self.clientID + "&client_serect=" + self.clientSecret
}
}
return _url
}
//取消请求
func close(){
self.task?.cancel()
}
}
//MARK: - 获取token -
extension GitHubApi{
//第三方url地址
public func authUrl() -> String {
let url = self.bulidUrl(path: "https://github.com/login/oauth/authorize",
params: ["scope" : self.scope,
"client_id" : self.clientID,
"state" : "midoks"])
return url
}
//获取token
public func getToken(code:String, callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){
self.post(url: "https://github.com/login/oauth/access_token", params: [
"scope" : self.scope,
"client_id" : self.clientID,
"client_secret" : self.clientSecret,
"code" : code,
"state" : "midoks"]) { (data, response, error) -> Void in
callback(data, response, error)
}
}
//在请求里加入token
public func setToken(token:String){
self.oauth_token = token
}
//获取token
public func getToken() -> String {
return oauth_token!
}
}
//GitHub数据编码
extension GitHubApi {
func dataEncode64(strVal:String) -> String {
let strValData = strVal.data(using: String.Encoding.utf8)
let strValEncodeData = strValData!.base64EncodedData(options: Data.Base64EncodingOptions(rawValue: 0))
let strValEncode = String(data: strValEncodeData, encoding: String.Encoding.utf8)
return strValEncode!
}
func dataDecode64(strVal:String) -> String {
let data = NSData(base64Encoded:strVal ,options: .ignoreUnknownCharacters)!
let strValDecode = String(data: data as Data, encoding: String.Encoding.utf8)
if strValDecode == nil {
return ""
}
return strValDecode!
}
}
//MARK: - 用户相关操作 -
extension GitHubApi{
//用户数据
func user(callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){
self.get(url: self.buildUrl(path: "/user")) { (data, response, error) -> Void in
callback(data, response, error)
}
}
//获取用户邮件地址列表
func userEmails(callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){
self.get(url: self.buildUrl(path: "/user/emails")) { (data, response, error) -> Void in
callback(data, response, error)
}
}
}
//MARK: - 容纳GitHub所有的请求 -
extension GitHubApi{
//所有GET操作
public func webGet(absoluteUrl:String, callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){
self.get(url: absoluteUrl) { (data, response, error) -> Void in
if self.checkGitAllError(data: data, response: response, error: error) {
callback(data, response, error)
} else {
callback(nil, nil, nil)
}
}
}
//所有GET操作
public func urlGet(url:String, callback:@escaping (_ data: NSData?, _ response: URLResponse?, _ error:NSError?)->Void){
self.get(url: self.buildUrl(path: url)) { (data, response, error) -> Void in
if self.checkGitAllError(data: data, response: response, error: error) {
callback(data, response, error)
} else {
callback(nil, nil, nil)
}
}
}
private func gitJsonParse(data:NSData) -> JSON {
let _data = String(data: data as Data, encoding: String.Encoding.utf8)!
let _dataJson = JSON.parse(_data)
return _dataJson
}
//- 获取当前的视图 -
private func getRootVC() -> UIViewController {
let window = UIApplication.shared.keyWindow
return (window?.rootViewController)!
}
//显示提示信息
private func showNotice(msg:String){
if self.isShowAlert {
return;
}
self.isShowAlert = true
let root = self.getRootVC()
root.showTextWithTime(msg: msg, time: 2) {
self.isShowAlert = false
}
}
public func checkGitAllError(data: NSData!, response: URLResponse!, error:NSError!) -> Bool {
if error != nil {
if error.code == -999 {//self close request
} else {
self.showNotice(msg: "网络不好!!!")
print(error)
}
}
if data != nil {
let resp = response as! HTTPURLResponse
let status = resp.statusCode
if status == 204 || status == 404 {} else {
let _json = self.gitJsonParse(data: data)
if _json["message"].stringValue != "" {
print(_json)
self.showNotice(msg: _json["message"].stringValue)
return false
}
}
}
return true
}
}
| apache-2.0 | 37e1fb048c50122d79eef35018e4e2cc | 30.397183 | 208 | 0.556343 | 4.308465 | false | false | false | false |
edx/edx-app-ios | Source/UserProfile.swift | 1 | 4386 | //
// Profile.swift
// edX
//
// Created by Michael Katz on 9/24/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
import edXCore
public class UserProfile {
public enum ProfilePrivacy: String {
case Private = "private"
case Public = "all_users"
}
enum ProfileFields: String, RawStringExtractable {
case Image = "profile_image"
case HasImage = "has_image"
case ImageURL = "image_url_full"
case Username = "username"
case LanguagePreferences = "language_proficiencies"
case Country = "country"
case Bio = "bio"
case YearOfBirth = "year_of_birth"
case ParentalConsent = "requires_parental_consent"
case AccountPrivacy = "account_privacy"
}
let hasProfileImage: Bool
let imageURL: String?
let username: String?
var preferredLanguages: [[String: Any]]?
var countryCode: String?
var bio: String?
var birthYear: Int?
let parentalConsent: Bool?
var accountPrivacy: ProfilePrivacy?
var hasUpdates: Bool { return updateDictionary.count > 0 }
var updateDictionary = [String: AnyObject]()
public init?(json: JSON) {
let profileImage = json[ProfileFields.Image]
if let hasImage = profileImage[ProfileFields.HasImage].bool, hasImage {
hasProfileImage = true
imageURL = profileImage[ProfileFields.ImageURL].string
} else {
hasProfileImage = false
imageURL = nil
}
username = json[ProfileFields.Username].string
preferredLanguages = json[ProfileFields.LanguagePreferences].arrayObject as? [[String: Any]]
countryCode = json[ProfileFields.Country].string
bio = json[ProfileFields.Bio].string
birthYear = json[ProfileFields.YearOfBirth].int
parentalConsent = json[ProfileFields.ParentalConsent].bool
accountPrivacy = ProfilePrivacy(rawValue: json[ProfileFields.AccountPrivacy].string ?? "")
}
internal init(username : String, bio : String? = nil, parentalConsent : Bool? = false, countryCode : String? = nil, accountPrivacy : ProfilePrivacy? = nil) {
self.accountPrivacy = accountPrivacy
self.username = username
self.hasProfileImage = false
self.imageURL = nil
self.parentalConsent = parentalConsent
self.bio = bio
self.countryCode = countryCode
}
var languageCode: String? {
get {
guard let languages = preferredLanguages, languages.count > 0 else { return nil }
return languages[0]["code"] as? String
}
set {
guard let code = newValue else { preferredLanguages = []; return }
guard preferredLanguages != nil && preferredLanguages!.count > 0 else {
preferredLanguages = [["code": code]]
return
}
let cRange = 0...0
let range = Range(cRange)
preferredLanguages?.replaceSubrange(range, with: [["code": code]])
}
}
}
extension UserProfile { //ViewModel
func image(networkManager: NetworkManager) -> RemoteImage {
let placeholder = UIImage(named: "person_black")
if let url = imageURL, hasProfileImage {
return RemoteImageImpl(url: url, networkManager: networkManager, placeholder: placeholder, persist: true)
}
else {
return RemoteImageJustImage(image: placeholder)
}
}
var country: String? {
guard let code = countryCode else { return nil }
return (Locale.current as NSLocale).displayName(forKey: NSLocale.Key.countryCode, value: code) ?? ""
}
var language: String? {
return languageCode.flatMap { return (Locale.current as NSLocale).displayName(forKey: NSLocale.Key.languageCode, value: $0) }
}
var sharingLimitedProfile: Bool {
get {
return (parentalConsent ?? false) || (accountPrivacy == nil) || (accountPrivacy! == .Private)
}
}
func setLimitedProfile(newValue:Bool) {
let newStatus: ProfilePrivacy = newValue ? .Private: .Public
if newStatus != accountPrivacy {
updateDictionary[ProfileFields.AccountPrivacy.rawValue] = newStatus.rawValue as AnyObject?
}
accountPrivacy = newStatus
}
}
| apache-2.0 | 1398349bba3bc1f2cac85a5dc462c59f | 34.362903 | 161 | 0.627822 | 4.966025 | false | false | false | false |
edx/edx-app-ios | Source/OEXRegistrationViewController+Swift.swift | 1 | 8794 | //
// OEXRegistrationViewController+Swift.swift
// edX
//
// Created by Danial Zahid on 9/5/16.
// Copyright © 2016 edX. All rights reserved.
//
import Foundation
extension OEXRegistrationViewController {
@objc func getRegistrationFormDescription(success: @escaping (_ response: OEXRegistrationDescription) -> ()) {
let networkManager = environment.networkManager
let apiVersion = environment.config.apiUrlVersionConfig.registration
let networkRequest = RegistrationFormAPI.registrationFormRequest(version: apiVersion)
self.stream = networkManager.streamForRequest(networkRequest)
(self.stream as! OEXStream<OEXRegistrationDescription>).listen(self) {[weak self] (result) in
if let data = result.value {
self?.loadController.state = .Loaded
success(data)
}
else{
self?.loadController.state = LoadState.failed(error: result.error)
}
}
}
private func error(with name: String, _ validationDecisions: ValidationDecisions) -> String? {
guard let value = ValidationDecisions.Keys(rawValue: name),
ValidationDecisions.Keys.allCases.contains(value),
let errorValue = validationDecisions.value(forKeyPath: value.rawValue) as? String,
!errorValue.isEmpty else { return nil }
return errorValue
}
private func handle(_ error: NSError) {
view.isUserInteractionEnabled = true
if error.code == -1001 || error.code == -1003 {
UIAlertController().showAlert(withTitle: Strings.timeoutAlertTitle, message: Strings.timeoutCheckInternetConnection, onViewController: self)
} else {
UIAlertController().showAlert(withTitle: Strings.Accessibility.errorText, message: error.localizedDescription, onViewController: self)
}
}
@objc func validateRegistrationForm(parameters: [String: String]) {
showProgress(true)
let networkManager = environment.networkManager
let networkRequest = RegistrationFormAPI.registrationFormValidationRequest(parameters: parameters)
networkManager.taskForRequest(networkRequest) { [weak self] result in
if let error = result.error {
self?.showProgress(false)
self?.handle(error)
return
}
guard let owner = self,
let validationDecisions = result.data?.validationDecisions else {
self?.showProgress(false)
self?.register(withParameters: parameters)
return
}
var firstControllerWithError: OEXRegistrationFieldController?
for case let controller as OEXRegistrationFieldController in owner.fieldControllers {
controller.accessibleInputField?.resignFirstResponder()
if let error = owner.error(with: controller.field.name, validationDecisions) {
controller.handleError(error)
if firstControllerWithError == nil {
firstControllerWithError = controller
}
}
}
owner.showProgress(false)
if firstControllerWithError == nil {
owner.register(withParameters: parameters)
} else {
owner.refreshFormFields()
UIAlertController().showAlert(withTitle: Strings.registrationErrorAlertTitle, message: Strings.registrationErrorAlertMessage, cancelButtonTitle: Strings.ok, onViewController: owner) { _, _, _ in
firstControllerWithError?.accessibleInputField?.becomeFirstResponder()
}
}
}
}
@objc func register(withParameters parameter:[String:String]) {
showProgress(true)
let infoDict: [String: String] = [OEXAnalyticsKeyProvider: externalProvider?.backendName ?? ""]
environment.analytics.trackEvent(OEXAnalytics.registerEvent(name: AnalyticsEventName.UserRegistrationClick.rawValue, displayName: AnalyticsDisplayName.CreateAccount.rawValue), forComponent: nil, withInfo: infoDict)
let apiVersion = environment.config.apiUrlVersionConfig.registration
OEXAuthentication.registerUser(withApiVersion: apiVersion, paramaters: parameter) { [weak self] (data: Data?, response: HTTPURLResponse?, error: Error?) in
if let owner = self {
if let data = data, error == nil {
let completion: ((_: Data?, _: HTTPURLResponse?, _: Error?) -> Void) = {(_ data: Data?, _ response: HTTPURLResponse?, _ error: Error?) -> Void in
if response?.statusCode == OEXHTTPStatusCode.code200OK.rawValue {
owner.environment.analytics.trackEvent(OEXAnalytics.registerEvent(name: AnalyticsEventName.UserRegistrationSuccess.rawValue, displayName: AnalyticsDisplayName.RegistrationSuccess.rawValue), forComponent: nil, withInfo: infoDict)
owner.delegate?.registrationViewControllerDidRegister(owner, completion: nil)
}
else if let error = error as NSError?, error.oex_isNoInternetConnectionError {
owner.showNoNetworkError()
}
owner.showProgress(false)
}
if (response?.statusCode == OEXHTTPStatusCode.code200OK.rawValue) {
if let externalProvider = self?.externalProvider {
owner.attemptExternalLogin(with: externalProvider, token: owner.externalAccessToken, completion: completion)
}
else {
let username = parameter["username"] ?? ""
let password = parameter["password"] ?? ""
OEXAuthentication.requestToken(withUser: username, password: password, completionHandler: completion)
}
}
else {
var controllers : [String: Any] = [:]
for controller in owner.fieldControllers {
let controller = controller as? OEXRegistrationFieldController
controllers.setSafeObject(controller, forKey: controller?.field.name ?? "")
controller?.handleError("")
}
do {
let dictionary = try JSONSerialization.jsonObject(with: data, options: []) as AnyObject
if dictionary is Dictionary<AnyHashable, Any> {
dictionary.enumerateKeysAndObjects({ (key, value, stop) in
let key = key as? String ?? ""
weak var controller: OEXRegistrationFieldController? = controllers[key] as? OEXRegistrationFieldController
if let array = value as? NSArray {
let errorStrings = array.oex_map({ (info) -> Any in
if let info = info as? [AnyHashable: Any] {
return OEXRegistrationFieldError(dictionary: info).userMessage
}
return OEXRegistrationFieldError().userMessage
})
let errors = (errorStrings as NSArray).componentsJoined(by: " ")
controller?.handleError(errors)
}
})
}
} catch let error as NSError {
Logger.logError("Registration", "Failed to load: \(error.localizedDescription)")
}
owner.showProgress(false)
owner.refreshFormFields()
}
}
else {
if let error = error as NSError?, error.oex_isNoInternetConnectionError {
owner.showNoNetworkError()
}
owner.showProgress(false)
}
}
}
}
//Testing only
public var t_loaded : OEXStream<()> {
return (self.stream as! OEXStream<OEXRegistrationDescription>).map {_ in () }
}
}
| apache-2.0 | 23a3567217ca98110547a01028680e44 | 51.339286 | 256 | 0.553622 | 6.157563 | false | false | false | false |
lorentey/swift | benchmark/single-source/NSStringConversion.swift | 6 | 10176 | //===--- NSStringConversion.swift -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// <rdar://problem/19003201>
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import TestsUtils
import Foundation
fileprivate var test:NSString = ""
fileprivate var mutableTest = ""
public let NSStringConversion = [
BenchmarkInfo(name: "NSStringConversion",
runFunction: run_NSStringConversion,
tags: [.validation, .api, .String, .bridging]),
BenchmarkInfo(name: "NSStringConversion.UTF8",
runFunction: run_NSStringConversion_nonASCII,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSString(cString: "tëst", encoding: String.Encoding.utf8.rawValue)! }),
BenchmarkInfo(name: "NSStringConversion.Mutable",
runFunction: run_NSMutableStringConversion,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSMutableString(cString: "test", encoding: String.Encoding.ascii.rawValue)! }),
BenchmarkInfo(name: "NSStringConversion.Medium",
runFunction: run_NSStringConversion_medium,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSString(cString: "aaaaaaaaaaaaaaa", encoding: String.Encoding.ascii.rawValue)! } ),
BenchmarkInfo(name: "NSStringConversion.Long",
runFunction: run_NSStringConversion_long,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSString(cString: "The quick brown fox jumps over the lazy dog", encoding: String.Encoding.ascii.rawValue)! } ),
BenchmarkInfo(name: "NSStringConversion.LongUTF8",
runFunction: run_NSStringConversion_longNonASCII,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSString(cString: "Thë qüick bröwn föx jumps over the lazy dög", encoding: String.Encoding.utf8.rawValue)! } ),
BenchmarkInfo(name: "NSStringConversion.Rebridge",
runFunction: run_NSStringConversion_rebridge,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSString(cString: "test", encoding: String.Encoding.ascii.rawValue)! }),
BenchmarkInfo(name: "NSStringConversion.Rebridge.UTF8",
runFunction: run_NSStringConversion_nonASCII_rebridge,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSString(cString: "tëst", encoding: String.Encoding.utf8.rawValue)! }),
BenchmarkInfo(name: "NSStringConversion.Rebridge.Mutable",
runFunction: run_NSMutableStringConversion_rebridge,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSMutableString(cString: "test", encoding: String.Encoding.ascii.rawValue)! }),
BenchmarkInfo(name: "NSStringConversion.Rebridge.Medium",
runFunction: run_NSStringConversion_medium_rebridge,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSString(cString: "aaaaaaaaaaaaaaa", encoding: String.Encoding.ascii.rawValue)! } ),
BenchmarkInfo(name: "NSStringConversion.Rebridge.Long",
runFunction: run_NSStringConversion_long_rebridge,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSString(cString: "The quick brown fox jumps over the lazy dog", encoding: String.Encoding.ascii.rawValue)! } ),
BenchmarkInfo(name: "NSStringConversion.Rebridge.LongUTF8",
runFunction: run_NSStringConversion_longNonASCII_rebridge,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSString(cString: "Thë qüick bröwn föx jumps over the lazy dög", encoding: String.Encoding.utf8.rawValue)! } ),
BenchmarkInfo(name: "NSStringConversion.MutableCopy.UTF8",
runFunction: run_NSStringConversion_nonASCIIMutable,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { mutableTest = "tëst" }),
BenchmarkInfo(name: "NSStringConversion.MutableCopy.Medium",
runFunction: run_NSStringConversion_mediumMutable,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { mutableTest = "aaaaaaaaaaaaaaa" } ),
BenchmarkInfo(name: "NSStringConversion.MutableCopy.Long",
runFunction: run_NSStringConversion_longMutable,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { mutableTest = "The quick brown fox jumps over the lazy dog" } ),
BenchmarkInfo(name: "NSStringConversion.MutableCopy.LongUTF8",
runFunction: run_NSStringConversion_longNonASCIIMutable,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { mutableTest = "Thë qüick bröwn föx jumps over the lazy dög" } ),
BenchmarkInfo(name: "NSStringConversion.MutableCopy.Rebridge",
runFunction: run_NSStringConversion_rebridgeMutable,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { mutableTest = "test" }),
BenchmarkInfo(name: "NSStringConversion.MutableCopy.Rebridge.UTF8",
runFunction: run_NSStringConversion_nonASCII_rebridgeMutable,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { mutableTest = "tëst" }),
BenchmarkInfo(name: "NSStringConversion.MutableCopy.Rebridge.Medium",
runFunction: run_NSStringConversion_medium_rebridgeMutable,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { mutableTest = "aaaaaaaaaaaaaaa" } ),
BenchmarkInfo(name: "NSStringConversion.MutableCopy.Rebridge.Long",
runFunction: run_NSStringConversion_long_rebridgeMutable,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { mutableTest = "The quick brown fox jumps over the lazy dog" } ),
BenchmarkInfo(name: "NSStringConversion.MutableCopy.Rebridge.LongUTF8",
runFunction: run_NSStringConversion_longNonASCII_rebridgeMutable,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { mutableTest = "Thë qüick bröwn föx jumps over the lazy dög" } )
]
public func run_NSStringConversion(_ N: Int) {
let test:NSString = NSString(cString: "test", encoding: String.Encoding.ascii.rawValue)!
for _ in 1...N * 10000 {
//Doesn't test accessing the String contents to avoid changing historical benchmark numbers
blackHole(identity(test) as String)
}
}
fileprivate func innerLoop(_ str: NSString, _ N: Int, _ scale: Int = 5000) {
for _ in 1...N * scale {
for char in (identity(str) as String).utf8 {
blackHole(char)
}
}
}
public func run_NSStringConversion_nonASCII(_ N: Int) {
innerLoop(test, N, 2500)
}
public func run_NSMutableStringConversion(_ N: Int) {
innerLoop(test, N)
}
public func run_NSStringConversion_medium(_ N: Int) {
innerLoop(test, N, 1000)
}
public func run_NSStringConversion_long(_ N: Int) {
innerLoop(test, N, 1000)
}
public func run_NSStringConversion_longNonASCII(_ N: Int) {
innerLoop(test, N, 300)
}
fileprivate func innerMutableLoop(_ str: String, _ N: Int, _ scale: Int = 5000) {
for _ in 1...N * scale {
let copy = (str as NSString).mutableCopy() as! NSMutableString
for char in (identity(copy) as String).utf8 {
blackHole(char)
}
}
}
public func run_NSStringConversion_nonASCIIMutable(_ N: Int) {
innerMutableLoop(mutableTest, N, 500)
}
public func run_NSStringConversion_mediumMutable(_ N: Int) {
innerMutableLoop(mutableTest, N, 500)
}
public func run_NSStringConversion_longMutable(_ N: Int) {
innerMutableLoop(mutableTest, N, 250)
}
public func run_NSStringConversion_longNonASCIIMutable(_ N: Int) {
innerMutableLoop(mutableTest, N, 150)
}
fileprivate func innerRebridge(_ str: NSString, _ N: Int, _ scale: Int = 5000) {
for _ in 1...N * scale {
let bridged = identity(str) as String
blackHole(bridged)
blackHole(bridged as NSString)
}
}
public func run_NSStringConversion_rebridge(_ N: Int) {
innerRebridge(test, N, 2500)
}
public func run_NSStringConversion_nonASCII_rebridge(_ N: Int) {
innerRebridge(test, N, 2500)
}
public func run_NSMutableStringConversion_rebridge(_ N: Int) {
innerRebridge(test, N)
}
public func run_NSStringConversion_medium_rebridge(_ N: Int) {
innerRebridge(test, N, 1000)
}
public func run_NSStringConversion_long_rebridge(_ N: Int) {
innerRebridge(test, N, 1000)
}
public func run_NSStringConversion_longNonASCII_rebridge(_ N: Int) {
innerRebridge(test, N, 300)
}
fileprivate func innerMutableRebridge(_ str: String, _ N: Int, _ scale: Int = 5000) {
for _ in 1...N * scale {
let copy = (str as NSString).mutableCopy() as! NSMutableString
let bridged = identity(copy) as String
blackHole(bridged)
blackHole(bridged as NSString)
}
}
public func run_NSStringConversion_rebridgeMutable(_ N: Int) {
innerMutableRebridge(mutableTest, N, 1000)
}
public func run_NSStringConversion_nonASCII_rebridgeMutable(_ N: Int) {
innerMutableRebridge(mutableTest, N, 500)
}
public func run_NSStringConversion_medium_rebridgeMutable(_ N: Int) {
innerMutableRebridge(mutableTest, N, 500)
}
public func run_NSStringConversion_long_rebridgeMutable(_ N: Int) {
innerMutableRebridge(mutableTest, N, 500)
}
public func run_NSStringConversion_longNonASCII_rebridgeMutable(_ N: Int) {
innerMutableRebridge(mutableTest, N, 300)
}
#endif
| apache-2.0 | 4b65aa199a0ecc1c067c6090e05e93da | 43.13913 | 152 | 0.663712 | 4.208955 | false | true | false | false |
jeffreybergier/WaterMe2 | WaterMe/WaterMe/PurchaseConfirmation/PurchaseThanksViewController.swift | 1 | 6354 | //
// PurchaseThanksViewController.swift
// WaterMe
//
// Created by Jeffrey Bergier on 14/1/18.
// Copyright © 2018 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WaterMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import Cheers
import Store
import UIKit
typealias PurchaseThanksCompletion = (UIViewController?) -> Void
class PurchaseThanksViewController: StandardViewController {
class func newVC(for inFlight: InFlightTransaction, completion: @escaping PurchaseThanksCompletion) -> UIViewController? {
let alert: UIAlertController
switch inFlight.state {
case .cancelled:
return nil
case .success:
Analytics.log(event: Analytics.IAPOperation.buySuccess)
return PurchaseThanksViewController.newVC() { vc in
AppDelegate.shared.purchaseController?.finish(inFlight: inFlight)
completion(vc)
}
case .errorNetwork:
Analytics.log(event: Analytics.IAPOperation.buyErrorNetwork)
alert = UIAlertController(
title: LocalizedString.errorAlertTitle,
message: LocalizedString.errorNetworkAlertMessage,
preferredStyle: .alert
)
case .errorNotAllowed:
Analytics.log(event: Analytics.IAPOperation.buyErrorNotAllowed)
alert = UIAlertController(
title: LocalizedString.errorAlertTitle,
message: LocalizedString.errorNotAllowedAlertMessage,
preferredStyle: .alert
)
case .errorUnknown:
Analytics.log(event: Analytics.IAPOperation.buyErrorUnknown)
alert = UIAlertController(
title: LocalizedString.errorAlertTitle,
message: LocalizedString.errorUnknownAlertMessage,
preferredStyle: .alert
)
}
let confirm = UIAlertAction(title: UIAlertController.LocalizedString.buttonTitleDismiss,
style: .cancel)
{ _ in
AppDelegate.shared.purchaseController?.finish(inFlight: inFlight)
completion(nil)
}
Analytics.log(viewOperation: .errorAlertPurchase)
alert.addAction(confirm)
return alert
}
private class func newVC(completion: @escaping PurchaseThanksCompletion) -> UIViewController {
let sb = UIStoryboard(name: "PurchaseThanks", bundle: Bundle(for: self))
// swiftlint:disable:next force_cast
let vc = sb.instantiateInitialViewController() as! ModalParentViewController
vc.configureChild = { vc in
// swiftlint:disable:next force_cast
let vc = vc as! PurchaseThanksViewController
vc.completionHandler = completion
}
return vc
}
@IBOutlet private weak var contentView: UIView!
@IBOutlet private weak var titleLabel: UILabel?
@IBOutlet private weak var subtitleLabel: UILabel?
@IBOutlet private weak var bodyLabel: UILabel?
@IBOutlet private weak var reviewButton: UIButton?
@IBOutlet private weak var cancelButton: UIButton?
private var completionHandler: PurchaseThanksCompletion!
private let cheerView: CheerView = {
let v = CheerView()
v.config.colors = [Color.confetti1, Color.confetti2]
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
self.contentView.style_setCornerRadius()
self.contentView.addSubview(self.cheerView)
self.contentView.addConstraints([
self.contentView.leadingAnchor.constraint(equalTo: self.cheerView.leadingAnchor, constant: 0),
self.contentView.trailingAnchor.constraint(equalTo: self.cheerView.trailingAnchor, constant: 0),
self.cheerView.heightAnchor.constraint(equalToConstant: 1)
])
self.configureAttributedText()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.animateAlongSideTransitionCoordinator(animations: nil, completion: {
self.cheerView.start()
Timer.scheduledTimer(withTimeInterval: 7, repeats: false) { _ in
self.cheerView.stop()
}
})
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Analytics.log(viewOperation: .purchaseThanks)
}
private func configureAttributedText() {
self.titleLabel?.attributedText = NSAttributedString(string: LocalizedString.title, font: .migratorTitle)
self.subtitleLabel?.attributedText = NSAttributedString(string: LocalizedString.subtitle, font: .migratorSubtitle)
self.bodyLabel?.attributedText = NSAttributedString(string: LocalizedString.body, font: .migratorBody)
self.reviewButton?.setAttributedTitle(NSAttributedString(string: SettingsMainViewController.LocalizedString.cellTitleTipJarFree, font: .migratorPrimaryButton), for: .normal)
self.cancelButton?.setAttributedTitle(NSAttributedString(string: UIAlertController.LocalizedString.buttonTitleDismiss, font: .migratorSecondaryButton), for: .normal)
}
@IBAction private func reviewButtonTapped(_ sender: Any) {
UIApplication.shared.openWriteReviewPage(completion: { _ in self.completionHandler(self) })
}
@IBAction private func cancelButtonTapped(_ sender: Any) {
self.completionHandler(self)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.configureAttributedText()
}
}
| gpl-3.0 | 8b046d9dd72644862ccc73a36486c526 | 40.796053 | 181 | 0.685031 | 5.186122 | false | false | false | false |
hooman/swift | test/IDE/complete_in_result_builder.swift | 3 | 6534 | // RUN %empty-directory(%t)
// RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t
@resultBuilder
struct TupleBuilder<T> {
static func buildBlock() -> () { }
static func buildBlock(_ t1: T) -> T {
return t1
}
static func buildBlock(_ t1: T, _ t2: T) -> (T, T) {
return (t1, t2)
}
static func buildBlock(_ t1: T, _ t2: T, _ t3: T) -> (T, T, T) {
return (t1, t2, t3)
}
}
func buildStringTuple<Result>(@TupleBuilder<String> x: () -> Result) {}
enum StringFactory {
static func makeString(x: String) -> String { return x }
}
enum Letters {
case a
case b
case c
}
let MyConstantString = "MyConstant"
let MyConstantBool = true
func testGlobalLookup() {
@TupleBuilder<String> var x1 {
#^GLOBAL_LOOKUP^#
// GLOBAL_LOOKUP: Begin completions
// GLOBAL_LOOKUP: Decl[GlobalVar]/CurrModule: MyConstantString[#String#];
// GLOBAL_LOOKUP: End completions
}
@TupleBuilder<String> var x2 {
if true {
#^GLOBAL_LOOKUP_IN_IF_BODY?check=GLOBAL_LOOKUP^#
}
}
@TupleBuilder<String> var x3 {
if {
#^GLOBAL_LOOKUP_IN_IF_BODY_WITHOUT_CONDITION?check=GLOBAL_LOOKUP^#
}
}
@TupleBuilder<String> var x4 {
guard else {
#^GLOBAL_LOOKUP_IN_GUARD_BODY_WITHOUT_CONDITION?check=GLOBAL_LOOKUP^#
}
}
@TupleBuilder<String> var x5 {
"hello: \(#^GLOBAL_LOOKUP_IN_STRING_LITERAL^#)"
// GLOBAL_LOOKUP_IN_STRING_LITERAL: Begin completions
// GLOBAL_LOOKUP_IN_STRING_LITERAL: Decl[GlobalVar]/CurrModule/TypeRelation[Convertible]: MyConstantString[#String#];
// GLOBAL_LOOKUP_IN_STRING_LITERAL: End completions
}
@TupleBuilder<String> var x5 {
if #^GLOBAL_LOOKUP_IN_IF_CONDITION^# {
// GLOBAL_LOOKUP_IN_IF_CONDITION: Begin completions
// GLOBAL_LOOKUP_IN_IF_CONDITION: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: MyConstantBool[#Bool#]; name=MyConstantBool
// GLOBAL_LOOKUP_IN_IF_CONDITION: End completions
}
}
}
func testStaticMemberLookup() {
@TupleBuilder<String> var x1 {
StringFactory.#^COMPLETE_STATIC_MEMBER^#
// COMPLETE_STATIC_MEMBER: Begin completions
// COMPLETE_STATIC_MEMBER: Decl[StaticMethod]/CurrNominal: makeString({#x: String#})[#String#];
// COMPLETE_STATIC_MEMBER: End completions
}
@TupleBuilder<String> var x2 {
if true {
StringFactory.#^COMPLETE_STATIC_MEMBER_IN_IF_BODY?check=COMPLETE_STATIC_MEMBER^#
}
}
@TupleBuilder<String> var x3 {
"hello: \(StringFactory.#^COMPLETE_STATIC_MEMBER_IN_STRING_LITERAL?check=COMPLETE_STATIC_MEMBER;xfail=rdar78015646^#)"
}
}
struct FooStruct {
var instanceVar : Int
init(_: Int = 0) { }
func boolGen() -> Bool { return false }
func intGen() -> Int { return 1 }
}
func testPatternMatching() {
@TupleBuilder<String> var x1 {
let x = Letters.b
if case .#^COMPLETE_PATTERN_MATCHING_IN_IF?check=COMPLETE_CASE^# = x {
// COMPLETE_CASE: Begin completions
// COMPLETE_CASE-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: a[#Letters#];
// COMPLETE_CASE-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: b[#Letters#];
// COMPLETE_CASE-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Identical]: c[#Letters#];
// COMPLETE_CASE: End completions
}
}
@TupleBuilder<String> var x2 {
let x = Letters.a
switch x {
case .#^COMPLETE_CASE_IN_SWITCH?check=COMPLETE_CASE^#:
break
}
}
@TupleBuilder<String> var x3 {
let x: FooStruct? = FooStruct()
guard case .#^GUARD_CASE_PATTERN_1?check=OPTIONAL_FOOSTRUCT^# = x {}
// OPTIONAL_FOOSTRUCT: Begin completions, 9 items
// OPTIONAL_FOOSTRUCT-DAG: Keyword[nil]/None/Erase[1]/TypeRelation[Identical]: nil[#FooStruct?#]; name=nil
// OPTIONAL_FOOSTRUCT-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: none[#Optional<FooStruct>#]; name=none
// OPTIONAL_FOOSTRUCT-DAG: Decl[EnumElement]/CurrNominal/IsSystem/TypeRelation[Identical]: some({#FooStruct#})[#Optional<FooStruct>#]; name=some()
// FIXME: 'FooStruct' members should not be shown.
// OPTIONAL_FOOSTRUCT-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Convertible]: init()[#FooStruct#]; name=init()
// OPTIONAL_FOOSTRUCT-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Convertible]: init({#Int#})[#FooStruct#]; name=init()
// OPTIONAL_FOOSTRUCT-DAG: Decl[InstanceMethod]/CurrNominal: boolGen({#(self): FooStruct#})[#() -> Bool#]; name=boolGen(:)
// OPTIONAL_FOOSTRUCT-DAG: Decl[InstanceMethod]/CurrNominal: intGen({#(self): FooStruct#})[#() -> Int#]; name=intGen(:)
// OPTIONAL_FOOSTRUCT-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: map({#(self): Optional<FooStruct>#})[#((FooStruct) throws -> U) -> U?#]; name=map(:)
// OPTIONAL_FOOSTRUCT-DAG: Decl[InstanceMethod]/CurrNominal/IsSystem: flatMap({#(self): Optional<FooStruct>#})[#((FooStruct) throws -> U?) -> U?#]; name=flatMap(:)
// OPTIONAL_FOOSTRUCT-NOT: init({#(some):
// OPTIONAL_FOOSTRUCT-NOT: init({#nilLiteral:
// OPTIONAL_FOOSTRUCT: End completions
}
@TupleBuilder<String> var x4 {
let x: FooStruct? = FooStruct()
guard case .#^GUARD_CASE_PATTERN_2?check=OPTIONAL_FOOSTRUCT^#some() = x {}
}
}
func testCompleteFunctionArgumentLabels() {
@TupleBuilder<String> var x1 {
StringFactory.makeString(#^FUNCTION_ARGUMENT_LABEL^#)
// FUNCTION_ARGUMENT_LABEL: Begin completions, 1 item
// FUNCTION_ARGUMENT_LABEL: Decl[StaticMethod]/CurrNominal/Flair[ArgLabels]: ['(']{#x: String#}[')'][#String#];
// FUNCTION_ARGUMENT_LABEL: End completions
}
}
func testCompleteFunctionArgument() {
@TupleBuilder<String> var x1 {
StringFactory.makeString(x: #^ARGUMENT_LOOKUP^#)
// ARGUMENT_LOOKUP: Begin completions
// ARGUMENT_LOOKUP: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: MyConstantString[#String#];
// ARGUMENT_LOOKUP: End completions
}
@TupleBuilder<String> var x2 {
if true {
StringFactory.makeString(x: #^ARGUMENT_LOOKUP_IN_IF_BODY?check=ARGUMENT_LOOKUP^#)
}
}
}
func testCompleteErrorTypeInCatch() {
enum Error4 : Error {
case E1
case E2(Int32)
}
@TupleBuilder<String> var x1 {
do {} catch Error4.#^CATCH2^#
}
// CATCH2: Begin completions
// CATHC2-DAG: Decl[EnumElement]/CurrNominal/TypeRelation[Convertible]: E1[#Error4#]; name=E1
// CATHC2-DAG: Decl[EnumElement]/CurrNominal/TypeRelation[Convertible]: E2({#Int32#})[#Error4#]; name=E2(Int32)
// CATCH2: End completions
}
| apache-2.0 | b5872337adf4a1efc1bd76b5ea2981a1 | 34.51087 | 167 | 0.68442 | 3.644172 | false | false | false | false |
rene-dohan/CS-IOS | Renetik/Renetik/Classes/Core/Classes/Controller/CSMBProgressController.swift | 1 | 1297 | //
// Created by Rene Dohan on 1/11/20.
//
import Foundation
import MBProgressHUD
import ChameleonFramework
public class CSMBProgressController: CSObject, CSHasProgressProtocol, CSHasDialogVisible {
public var backgroundColor = UIColor.flatBlack()!.lighten(byPercentage: 0.03)!.add(alpha: 0.85)
public var foregroundColor = UIColor.white
private unowned let view: UIView
private var hud: MBProgressHUD?
public init(in controller: UIViewController) {
view = controller.view
}
public init(in view: UIView) {
self.view = view
}
public var isDialogVisible: Bool { hud.notNil }
public func hideDialog(animated: Bool = true) { hud?.hide(animated: animated) }
public func show(progress title: String, _ cancel: CSDialogAction?,
_ graceTime: TimeInterval?, _ minShowTime: TimeInterval?) -> CSHasDialogVisible {
hud = MBProgressHUD.showProgress(view: view, title: title,
foregroundColor: foregroundColor, backgroundColor: backgroundColor,
canCancel: cancel.notNil, cancelTitle: cancel?.title, onCancel: cancel?.action,
graceTime: graceTime, minShowTime: minShowTime)
hud!.completionBlock = { [weak self] in self?.hud = nil }
return self
}
}
| mit | e00992cdaf9e3ee5ecf9374c4c0e5a35 | 34.054054 | 102 | 0.681573 | 4.632143 | false | false | false | false |
MKGitHub/UIPheonix | Demo/Shared/Views/Collection View/SimpleButtonModelCVCell.swift | 1 | 3770 | /**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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.
*/
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
final class SimpleButtonModelCVCell:UIPBaseCollectionViewCell
{
// MARK: Private IB Outlet
@IBOutlet private weak var ibButton:UIPPlatformButton!
@IBOutlet private weak var ibCenterConstraint:NSLayoutConstraint!
// MARK: Private Members
private weak var mDelegate:UIPButtonDelegate?
private var mButtonId:Int!
// MARK:- UICollectionViewCell
override func prepareForReuse()
{
super.prepareForReuse()
mDelegate = nil
}
deinit
{
mDelegate = nil
}
// MARK:- UIPBaseCollectionViewCell/UIPBaseCollectionViewCellProtocol
override func update(withModel model:Any, delegate:Any, collectionView:UIPPlatformCollectionView, indexPath:IndexPath) -> UIPCellSize
{
// apply model to view
let simpleButtonModel:SimpleButtonModel = model as! SimpleButtonModel
#if os(iOS) || os(tvOS)
UIView.performWithoutAnimation(
{
[weak self] in
self?.ibButton.setTitle(simpleButtonModel.pTitle, for:UIControl.State())
self?.ibButton.layoutIfNeeded()
})
#elseif os(macOS)
ibButton.title = simpleButtonModel.pTitle
ibButton.sizeToFit()
alignButton(with:simpleButtonModel.pAlignment)
#endif
// view delegate handling
mDelegate = delegate as? UIPButtonDelegate
mButtonId = simpleButtonModel.pId
// layer drawing
#if os(iOS) || os(tvOS)
ibButton.layer.cornerRadius = CGFloat.valueForPlatform(mac:10, mobile:10, tv:40)
#elseif os(macOS)
ibButton.layer?.cornerRadius = CGFloat.valueForPlatform(mac:10, mobile:10, tv:40)
#endif
// return view size
return UIPCellSize(replaceWidth:true, width:collectionView.bounds.size.width,
replaceHeight:false, height:0)
}
// MARK:- IBAction
@IBAction func buttonAction(_ sender:AnyObject)
{
mDelegate?.handleAction(forButtonId:mButtonId)
}
// MARK:- Private
#if os(macOS)
private func alignButton(with aligment:String)
{
let buttonWidth:CGFloat = ibButton.bounds.size.width
let cellViewHalfWidth:CGFloat = (self.view.bounds.size.width / 2)
switch (aligment)
{
case SimpleButtonModel.Alignment.left:
ibCenterConstraint.constant = -cellViewHalfWidth + (buttonWidth / 2) + 13
break
case SimpleButtonModel.Alignment.center:
ibCenterConstraint.constant = 0
break
case SimpleButtonModel.Alignment.right:
ibCenterConstraint.constant = cellViewHalfWidth - (buttonWidth / 2) - 13
break
default:
break
}
}
#endif
}
| apache-2.0 | 665e7cf0558047502b656a77a780d8df | 27.126866 | 137 | 0.632529 | 4.856959 | false | false | false | false |
PraveenSakthivel/BRGO-IOS | Pods/CVCalendar/CVCalendar/CVCalendarContentViewController.swift | 2 | 8447 | //
// CVCalendarContentViewController.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 12/04/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
public typealias Identifier = String
open class CVCalendarContentViewController: UIViewController {
// MARK: - Constants
open let previous = "Previous"
open let presented = "Presented"
open let following = "Following"
// MARK: - Public Properties
open unowned let calendarView: CalendarView
open let scrollView: UIScrollView
open var presentedMonthView: MonthView
open var bounds: CGRect {
return scrollView.bounds
}
open var currentPage = 1
open var pageChanged: Bool {
get {
return currentPage == 1 ? false : true
}
}
open var pageLoadingEnabled = true
open var presentationEnabled = true
open var lastContentOffset: CGFloat = 0
open var direction: CVScrollDirection = .none
open var toggleDateAnimationDuration: Double {
return calendarView.delegate?.toggleDateAnimationDuration?() ?? 0.8
}
public init(calendarView: CalendarView, frame: CGRect) {
self.calendarView = calendarView
scrollView = UIScrollView(frame: frame)
presentedMonthView = MonthView(calendarView: calendarView, date: Foundation.Date())
presentedMonthView.updateAppearance(frame)
super.init(nibName: nil, bundle: nil)
scrollView.contentSize = CGSize(width: frame.width * 3, height: frame.height)
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.layer.masksToBounds = true
scrollView.isPagingEnabled = true
scrollView.delegate = self
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI Refresh
extension CVCalendarContentViewController {
public func updateFrames(_ frame: CGRect) {
if frame != CGRect.zero {
scrollView.frame = frame
scrollView.removeAllSubviews()
scrollView.contentSize = CGSize(width: frame.size.width * 3, height: frame.size.height)
}
calendarView.isHidden = false
}
}
//MARK: - Month Refresh
extension CVCalendarContentViewController {
public func refreshPresentedMonth() {
for weekV in presentedMonthView.weekViews {
for dayView in weekV.dayViews {
removeCircleLabel(dayView)
dayView.setupDotMarker()
dayView.preliminarySetup()
dayView.supplementarySetup()
dayView.topMarkerSetup()
}
}
}
}
// MARK: Delete circle views (in effect refreshing the dayView circle)
extension CVCalendarContentViewController {
func removeCircleLabel(_ dayView: CVCalendarDayView) {
for each in dayView.subviews {
if each is UILabel {
continue
} else if each is CVAuxiliaryView {
continue
} else {
each.removeFromSuperview()
}
}
}
}
//MARK: Delete dot views (in effect refreshing the dayView dots)
extension CVCalendarContentViewController {
func removeDotViews(_ dayView: CVCalendarDayView) {
for each in dayView.subviews {
if each is CVAuxiliaryView && each.frame.height == 13 {
each.removeFromSuperview()
}
}
}
}
// MARK: - Abstract methods
/// UIScrollViewDelegate
extension CVCalendarContentViewController: UIScrollViewDelegate { }
// Convenience API.
extension CVCalendarContentViewController {
public func performedDayViewSelection(_ dayView: DayView) { }
public func togglePresentedDate(_ date: Foundation.Date) { }
public func presentNextView(_ view: UIView?) { }
public func presentPreviousView(_ view: UIView?) { }
public func updateDayViews(_ hidden: Bool) { }
}
// MARK: - Contsant conversion
extension CVCalendarContentViewController {
public func indexOfIdentifier(_ identifier: Identifier) -> Int {
let index: Int
switch identifier {
case previous: index = 0
case presented: index = 1
case following: index = 2
default: index = -1
}
return index
}
}
// MARK: - Date management
extension CVCalendarContentViewController {
public func dateBeforeDate(_ date: Foundation.Date) -> Foundation.Date {
var components = Manager.componentsForDate(date)
let calendar = Calendar.current
components.month! -= 1
let dateBefore = calendar.date(from: components)!
return dateBefore
}
public func dateAfterDate(_ date: Foundation.Date) -> Foundation.Date {
var components = Manager.componentsForDate(date)
let calendar = Calendar.current
components.month! += 1
let dateAfter = calendar.date(from: components)!
return dateAfter
}
public func matchedMonths(_ lhs: CVDate, _ rhs: CVDate) -> Bool {
return lhs.year == rhs.year && lhs.month == rhs.month
}
public func matchedWeeks(_ lhs: CVDate, _ rhs: CVDate) -> Bool {
return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.week == rhs.week)
}
public func matchedDays(_ lhs: CVDate, _ rhs: CVDate) -> Bool {
return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day)
}
}
// MARK: - AutoLayout Management
extension CVCalendarContentViewController {
fileprivate func layoutViews(_ views: [UIView], toHeight height: CGFloat) {
scrollView.frame.size.height = height
var superStack = [UIView]()
var currentView: UIView = calendarView
while let currentSuperview = currentView.superview , !(currentSuperview is UIWindow) {
superStack += [currentSuperview]
currentView = currentSuperview
}
for view in views + superStack {
view.layoutIfNeeded()
}
}
public func updateHeight(_ height: CGFloat, animated: Bool) {
if calendarView.shouldAnimateResizing {
var viewsToLayout = [UIView]()
if let calendarSuperview = calendarView.superview {
for constraintIn in calendarSuperview.constraints {
if let firstItem = constraintIn.firstItem as? UIView,
let _ = constraintIn.secondItem as? CalendarView {
viewsToLayout.append(firstItem)
}
}
}
for constraintIn in calendarView.constraints where
constraintIn.firstAttribute == NSLayoutAttribute.height {
constraintIn.constant = height
if animated {
UIView.animate(withDuration: 0.2, delay: 0,
options: UIViewAnimationOptions.curveLinear,
animations: {
self.layoutViews(viewsToLayout, toHeight: height)
}) { _ in
self.presentedMonthView.frame.size =
self.presentedMonthView.potentialSize
self.presentedMonthView.updateInteractiveView()
}
} else {
layoutViews(viewsToLayout, toHeight: height)
presentedMonthView.updateInteractiveView()
presentedMonthView.frame.size = presentedMonthView.potentialSize
presentedMonthView.updateInteractiveView()
}
break
}
}
}
public func updateLayoutIfNeeded() {
if presentedMonthView.potentialSize.height != scrollView.bounds.height {
updateHeight(presentedMonthView.potentialSize.height, animated: true)
} else if presentedMonthView.frame.size != scrollView.frame.size {
presentedMonthView.frame.size = presentedMonthView.potentialSize
presentedMonthView.updateInteractiveView()
}
}
}
extension UIView {
public func removeAllSubviews() {
for subview in subviews {
subview.removeFromSuperview()
}
}
}
| mit | 3d6a2245219dbbb5aae89e16145cad67 | 30.285185 | 99 | 0.613235 | 5.557237 | false | false | false | false |
honishi/Hakumai | Hakumai/Managers/SpeechManager/SpeechManager.swift | 1 | 15733 | //
// SpeechManager.swift
// Hakumai
//
// Created by Hiroyuki Onishi on 11/26/15.
// Copyright © 2015 Hiroyuki Onishi. All rights reserved.
//
import Foundation
import AVFoundation
private let dequeuSpeechQueueInterval: TimeInterval = 0.25
private let maxSpeechCountForRefresh = 30
private let maxRecentSpeechTextsCount = 50
private let maxPreloadAudioCount = 5
private let maxCommentLengthSkippingDuplicate = 10
// https://stackoverflow.com/a/38409026/13220031
// See unicode list at https://0g0.org/ or https://0g0.org/unicode-list/
// See unicode search at https://www.marbacka.net/msearch/tool.php#chr2enc
private let emojiPattern = "[\\U0001F000-\\U0001F9FF]"
private let lineBreakPattern = "\n"
// https://stackoverflow.com/a/1660739/13220031
// private let repeatedCharPattern = "(.)\\1{9,}"
// https://so-zou.jp/software/tech/programming/tech/regular-expression/meta-character/variable-width-encoding.htm#no1
private let repeatedKanjiPattern = "(\\p{Han})\\1{9,}"
private let repeatedNumberPattern = "[12345678901234567890]{9,}"
private let cleanCommentPatterns = [
("https?://[\\w!?/+\\-_~;.,*&@#$%()'\\[\\]=]+", " URL "),
("(w|W|w|W){2,}", " わらわら"),
("(w|W|w|W)$", " わら"),
("(8|8){3,}", "ぱちぱち"),
("ニコ生(?!放送)", "ニコなま"),
("初見", "しょけん"),
// Removing Kao-moji.
// https://qiita.com/sanma_ow/items/b49b39ad5699bbcac0e9
("\\([^あ-ん\\u30A1-\\u30F4\\u2E80-\\u2FDF\\u3005-\\u3007\\u3400-\\u4DBF\\u4E00-\\u9FFF\\uF900-\\uFAFF\\U00020000-\\U0002EBEF]+?\\)", ""),
// At last, remove leading, trailing and middle white spaces.
// https://stackoverflow.com/a/19020103/13220031
("(^\\s+|\\s+$|\\s+(?=\\s))", "")
]
private let speechTextSkip = "コメント省略"
private let speechTextDuplicate = "コメント重複"
private let speechTextRefresh = "読み上げリセット"
@available(macOS 10.14, *)
final class _Synthesizer {
static let shared = _Synthesizer()
let synthesizer = AVSpeechSynthesizer()
}
final class SpeechManager: NSObject {
// MARK: - Types
enum CommentPreCheckResult: Equatable {
case accept
case reject(PreCheckRejectReason)
}
enum PreCheckRejectReason: Equatable {
case duplicate, long, manyEmoji, manyLines, manySameKanji, manyNumber
}
struct Speech {
let text: String
let audioLoader: AudioLoaderType
}
// MARK: - Properties
private var speechQueue: [Speech] = []
private var activeSpeech: Speech?
private var allSpeeches: [Speech] { ([activeSpeech] + speechQueue).compactMap { $0 } }
private var recentSpeechTexts: [String] = []
private var trashQueue: [Speech] = []
// min(normal): 1.0, fast: 2.0
private var voiceSpeed = VoiceSpeed.default
// min: 0, max(normal): 100
private var voiceVolume = VoiceVolume.default
private var voiceSpeaker = 0
private var timer: Timer?
// swiftlint:disable force_try
private let emojiRegexp = try! NSRegularExpression(pattern: emojiPattern, options: [])
private let lineBreakRegexp = try! NSRegularExpression(pattern: lineBreakPattern, options: [])
private let repeatedKanjiRegexp = try! NSRegularExpression(pattern: repeatedKanjiPattern, options: [])
private let repeatedNumberRegexp = try! NSRegularExpression(pattern: repeatedNumberPattern, options: [])
// swiftlint:enable force_try
private var player: AVAudioPlayer = AVAudioPlayer()
private var waitingExclusiveAudioLoadCompletion = false
// Debug: for logger
private var _previousSpeechQueueLogMessage = ""
private var _previousPreloadStatusMessage = ""
// MARK: - Object Lifecycle
override init() {
super.init()
configure()
}
deinit { log.debug("") }
}
extension SpeechManager {
func startManager() {
guard timer == nil else { return }
// use explicit main queue to ensure that the timer continues to run even when caller thread ends.
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(
timeInterval: dequeuSpeechQueueInterval,
target: self,
selector: #selector(SpeechManager.dequeue(_:)),
userInfo: nil,
repeats: true)
}
log.debug("started speech manager.")
}
func stopManager() {
DispatchQueue.main.async {
self.timer?.invalidate()
self.timer = nil
}
objc_sync_enter(self)
defer { objc_sync_exit(self) }
speechQueue.removeAll()
recentSpeechTexts.removeAll()
activeSpeech = nil
trashQueue.removeAll()
log.debug("stopped speech manager.")
}
// min/max: 0-100
func setVoiceVolume(_ volume: Int) {
voiceVolume = VoiceVolume(volume)
log.debug("set volume: \(voiceVolume)")
}
func setVoiceSpeaker(_ speaker: Int) {
voiceSpeaker = speaker
log.debug("set speaker: \(speaker)")
}
func enqueue(comment: String, name: String? = nil, skipIfDuplicated: Bool = true) {
let clean = cleanComment(from: comment)
let text = [name, checkAndMakeText(clean)]
.compactMap { $0 }
.joined(separator: " ")
objc_sync_enter(self)
defer { objc_sync_exit(self) }
appendToSpeechQueue(text: text)
if skipIfDuplicated {
appendToRecentSpeechTexts(text)
}
refreshSpeechQueueIfNeeded()
}
@objc func dequeue(_ timer: Timer?) {
guard #available(macOS 10.14, *) else { return }
objc_sync_enter(self)
defer { objc_sync_exit(self) }
logAudioQueue()
preloadAudioIfAvailable()
// log.debug("\(requestingAudioLoad), \(player.isPlaying)")
guard !waitingExclusiveAudioLoadCompletion else { return }
let isSpeaking = player.isPlaying || _Synthesizer.shared.synthesizer.isSpeaking
guard !isSpeaking else { return }
guard !speechQueue.isEmpty else { return }
activeSpeech = speechQueue.removeFirst()
guard let speech = activeSpeech else { return }
voiceSpeed = adjustedVoiceSpeed(
currentCommentLength: speech.text.count,
remainingCommentLength: speechQueue.map { $0.text.count }.reduce(0, +),
currentVoiceSpeed: voiceSpeed)
log.debug("Q:[\(speechQueue.count)] "
+ "Act:[\(speech.audioLoader.state)] "
+ "Sp:[\(voiceSpeed)/\(voiceSpeed.asVoicevox)/\(voiceSpeed.asAVSpeechSynthesizer)] "
+ "Tx:[\(speech.text)]")
switch speech.audioLoader.state {
case .notLoaded:
speech.audioLoader.startLoad(
speedScale: voiceSpeed.asVoicevox,
volumeScale: voiceVolume.asVoicevox,
speaker: voiceSpeaker)
fallthrough
case .loading:
speech.audioLoader.setStateChangeListener { [weak self] in
log.debug("Got status update: [\($0)] [\(speech.text)]")
self?.listenStateChangeForExclusiveAudioLoad(state: $0, speech: speech)
}
case .loaded, .failed:
break
}
playAudioIfLoadFinished(speech: speech)
}
// define as 'internal' for test
func cleanComment(from comment: String) -> String {
var cleaned = comment
cleanCommentPatterns.forEach {
cleaned = cleaned.stringByReplacingRegexp(pattern: $0.0, with: $0.1)
}
return cleaned
}
// define as 'internal' for test
func preCheckComment(_ comment: String) -> CommentPreCheckResult {
if comment.count > 100 {
return .reject(.long)
} else if emojiRegexp.matchCount(in: comment) > 5 {
return .reject(.manyEmoji)
} else if lineBreakRegexp.matchCount(in: comment) > 3 {
return .reject(.manyLines)
} else if repeatedKanjiRegexp.matchCount(in: comment) > 0 {
return .reject(.manySameKanji)
} else if repeatedNumberRegexp.matchCount(in: comment) > 0 {
return .reject(.manyNumber)
}
let isUniqueComment = recentSpeechTexts.filter { $0 == comment }.isEmpty
let isShortComment = comment.count <= maxCommentLengthSkippingDuplicate
if isUniqueComment || isShortComment {
return .accept
}
return .reject(.duplicate)
}
}
private extension SpeechManager {
func configure() {
let volume = UserDefaults.standard.integer(forKey: Parameters.commentSpeechVolume)
setVoiceVolume(volume)
let speakerId = UserDefaults.standard.integer(forKey: Parameters.commentSpeechVoicevoxSpeaker)
setVoiceSpeaker(speakerId)
}
func checkAndMakeText(_ text: String) -> String {
switch preCheckComment(text) {
case .accept:
return text
case .reject(let reason):
switch reason {
case .duplicate:
return speechTextDuplicate
case .long, .manyEmoji, .manyLines, .manySameKanji, .manyNumber:
return speechTextSkip
}
}
}
func appendToSpeechQueue(text: String) {
let speech = Speech(
text: text,
audioLoader: AudioLoader(
text: text,
maxTextLengthForEnablingCache: maxCommentLengthSkippingDuplicate
)
)
speechQueue.append(speech)
}
func appendToRecentSpeechTexts(_ text: String) {
recentSpeechTexts.append(text)
let isRecentSpeechTextsFull = recentSpeechTexts.count > maxRecentSpeechTextsCount
guard isRecentSpeechTextsFull else { return }
recentSpeechTexts.remove(at: 0)
}
func refreshSpeechQueueIfNeeded() {
let tooManySpeechesInQueue = speechQueue.count > maxSpeechCountForRefresh
guard tooManySpeechesInQueue else { return }
trashQueue = speechQueue
speechQueue.removeAll()
voiceSpeed = VoiceSpeed.default
appendToSpeechQueue(text: speechTextRefresh)
}
func preloadAudioIfAvailable() {
if let firstLoadingInTrash = trashQueue.firstAudioLoader(state: .loading) {
logPreloadStatus("Audio load in trash q is in progress for [\(firstLoadingInTrash.text)].")
return
}
if let firstLoading = allSpeeches.firstAudioLoader(state: .loading) {
logPreloadStatus("Audio load is in progress for [\(firstLoading.text)].")
return
}
if allSpeeches.loadedAudioLoadersCount > maxPreloadAudioCount {
logPreloadStatus("Already preloaded enough audio.")
return
}
if let firstNotLoaded = allSpeeches.firstAudioLoader(state: .notLoaded) {
logPreloadStatus("Requesting load for [\(firstNotLoaded.text)].")
firstNotLoaded.startLoad(
speedScale: voiceSpeed.asVoicevox,
volumeScale: voiceVolume.asVoicevox,
speaker: voiceSpeaker)
return
}
logPreloadStatus("Seems no audio needs to request load.")
}
func adjustedVoiceSpeed(currentCommentLength current: Int, remainingCommentLength remaining: Int, currentVoiceSpeed: VoiceSpeed) -> VoiceSpeed {
let total = Float(current) + Float(remaining)
let averageCommentLength: Float = 20
let normalCommentCount: Float = 5
let candidateSpeed = max(min(total / averageCommentLength / normalCommentCount, 2), 1)
let adjusted = remaining == 0 ? candidateSpeed : max(currentVoiceSpeed.value, candidateSpeed)
// log.debug("current: \(current) remaining: \(remaining) total: \(total) candidate: \(candidateSpeed) adjusted: \(adjusted)")
return VoiceSpeed(adjusted)
}
func listenStateChangeForExclusiveAudioLoad(state: AudioLoaderState, speech: Speech) {
switch state {
case .notLoaded:
break
case .loading:
waitingExclusiveAudioLoadCompletion = true
case .loaded, .failed:
waitingExclusiveAudioLoadCompletion = false
}
playAudioIfLoadFinished(speech: speech)
}
func playAudioIfLoadFinished(speech: Speech) {
switch speech.audioLoader.state {
case .notLoaded, .loading:
break
case .loaded(let data):
playAudio(data: data)
case .failed:
speakOnAVSpeechSynthesizer(
comment: speech.text,
speed: voiceSpeed.asAVSpeechSynthesizer,
volume: voiceVolume.asAVSpeechSynthesizer)
}
}
func speakOnAVSpeechSynthesizer(comment: String, speed: Float, volume: Float) {
guard #available(macOS 10.14, *) else { return }
let utterance = AVSpeechUtterance.init(string: comment)
utterance.rate = speed
utterance.volume = volume
let voice = AVSpeechSynthesisVoice.init(language: "ja-JP")
utterance.voice = voice
_Synthesizer.shared.synthesizer.speak(utterance)
}
func playAudio(data: Data) {
guard let player = try? AVAudioPlayer(data: data) else { return }
self.player = player
self.player.play()
}
}
extension String {
var stringByRemovingHeadingEmojiSpace: String {
stringByReplacingRegexp(pattern: "^\(emojiPattern)\\s", with: "")
}
}
private struct VoiceSpeed: CustomStringConvertible {
// min~max: 1.0~2.0
let value: Float
var description: String { String(value) }
static var `default`: VoiceSpeed { VoiceSpeed(1) }
init(_ value: Float) {
self.value = max(min(value, 2), 1)
}
}
private extension VoiceSpeed {
// min~max: 1.0~2.0 -> 1.0~1.7
var asVoicevox: Float { 1.0 + (value - 1) * 0.7 }
// min~max: 1.0~2.0 -> 0.5~0.75
var asAVSpeechSynthesizer: Float { 0.5 + (value - 1) * 0.25 }
}
private struct VoiceVolume: CustomStringConvertible {
// min~max: 0~100
let value: Int
var description: String { String(value) }
static var `default`: VoiceVolume { VoiceVolume(100) }
init(_ value: Int) {
self.value = max(min(value, 100), 0)
}
}
private extension VoiceVolume {
// min~max: 0~100 -> 0.0~1.0
var asVoicevox: Float { Float(value) / 100.0 }
// min~max: 0~100 -> 0.0~1.0
var asAVSpeechSynthesizer: Float { Float(value) / 100.0 }
}
private extension NSRegularExpression {
func matchCount(in text: String) -> Int {
return numberOfMatches(in: text, options: [], range: NSRange(0..<text.count))
}
}
private extension Array where Element == SpeechManager.Speech {
func audioLoaders(state: AudioLoaderState) -> [AudioLoaderType] {
return map { $0.audioLoader }.filter { $0.state == state }
}
func firstAudioLoader(state: AudioLoaderState) -> AudioLoaderType? {
return audioLoaders(state: state).first
}
var loadedAudioLoadersCount: Int {
map { $0.audioLoader }
.filter {
if case .loaded = $0.state { return true }
return false
}.count
}
}
private extension SpeechManager {
func logAudioQueue() {
let message = "speechQueueCount: \(speechQueue.count), speed: \(voiceSpeed)"
if message != _previousSpeechQueueLogMessage {
log.debug(message)
}
_previousSpeechQueueLogMessage = message
}
func logPreloadStatus(_ message: String) {
if message != _previousPreloadStatusMessage {
log.debug(message)
}
_previousPreloadStatusMessage = message
}
}
| mit | 7a7693d0e4e2c7fe0cb8f9b1a473c386 | 33.303297 | 148 | 0.629485 | 4.185573 | false | false | false | false |
hanzhuzi/XRCustomProgressView | XRCustomProgressView/Classes/Defines.swift | 1 | 1177 | //
// Defines.swift
// XRCustomProgressView
//
// Created by xuran on 2017/10/1.
// Copyright © 2017年 xuran. All rights reserved.
//
import Foundation
import UIKit
//MARK: - 颜色
// 颜色(RGB)
func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) -> UIColor
{
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
func RGBCOLOR(r:CGFloat, g:CGFloat, b:CGFloat) -> UIColor
{
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1)
}
func UIColorFromRGB(hexRGB: UInt32) -> UIColor
{
let redComponent = (hexRGB & 0xFF0000) >> 16
let greenComponent = (hexRGB & 0x00FF00) >> 8
let blueComponent = hexRGB & 0x0000FF
return RGBCOLOR(r: CGFloat(redComponent), g: CGFloat(greenComponent), b: CGFloat(blueComponent))
}
//RGB颜色转换(16进制)+ 透明度 --add by gyanping
func UIColorFromRGBAlpha(hexRGB: UInt32, alphas: CGFloat) -> UIColor
{
let redComponent = (hexRGB & 0xFF0000) >> 16
let greenComponent = (hexRGB & 0x00FF00) >> 8
let blueComponent = hexRGB & 0x0000FF
return RGBA(r: CGFloat(redComponent), g: CGFloat(greenComponent), b: CGFloat(blueComponent),a: alphas)
}
| mit | c8c2fd44bb0931b3c00c215835aeca6f | 26.902439 | 106 | 0.675699 | 3.100271 | false | false | false | false |
vector-im/riot-ios | Riot/Managers/KeyValueStorage/KeychainStore.swift | 1 | 2859 | //
// Copyright 2020 Vector Creations 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
import KeychainAccess
/// Extension on Keychain to get/set booleans
extension Keychain {
public func set(_ value: Bool, key: String, ignoringAttributeSynchronizable: Bool = true) throws {
try set(value.description, key: key, ignoringAttributeSynchronizable: ignoringAttributeSynchronizable)
}
public func getBool(_ key: String, ignoringAttributeSynchronizable: Bool = true) throws -> Bool? {
guard let value = try getString(key, ignoringAttributeSynchronizable: ignoringAttributeSynchronizable) else {
return nil
}
guard value == true.description || value == false.description else { return nil }
return value == true.description
}
}
class KeychainStore {
private var keychain: Keychain
/// Initializer
/// - Parameter keychain: Keychain instance to be used to read/write
init(withKeychain keychain: Keychain) {
self.keychain = keychain
}
}
extension KeychainStore: KeyValueStore {
// setters
func set(_ value: Data?, forKey key: KeyValueStoreKey) throws {
guard let value = value else {
try removeObject(forKey: key)
return
}
try keychain.set(value, key: key)
}
func set(_ value: String?, forKey key: KeyValueStoreKey) throws {
guard let value = value else {
try removeObject(forKey: key)
return
}
try keychain.set(value, key: key)
}
func set(_ value: Bool?, forKey key: KeyValueStoreKey) throws {
guard let value = value else {
try removeObject(forKey: key)
return
}
try keychain.set(value, key: key)
}
// getters
func data(forKey key: KeyValueStoreKey) throws -> Data? {
return try keychain.getData(key)
}
func string(forKey key: KeyValueStoreKey) throws -> String? {
return try keychain.getString(key)
}
func bool(forKey key: KeyValueStoreKey) throws -> Bool? {
return try keychain.getBool(key)
}
// remove
func removeObject(forKey key: KeyValueStoreKey) throws {
try keychain.remove(key)
}
}
| apache-2.0 | 3744d76954d4aeb31ad6936e6546682a | 28.474227 | 117 | 0.641833 | 4.717822 | false | false | false | false |
hi-hu/Hu-Carousel | Hu-Carousel/SignInViewController.swift | 1 | 6425 | //
// SignInViewController.swift
// Hu-Carousel
//
// Created by Hi_Hu on 2/11/15.
// Copyright (c) 2015 hi_hu. All rights reserved.
//
import UIKit
class SignInViewController: UIViewController, UIAlertViewDelegate {
@IBOutlet weak var loginContainer: UIView!
@IBOutlet weak var signInContainer: UIView!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
var loginContainerOriginY: CGFloat!
var signInContainerOriginY: CGFloat!
var isKeyboardUp = false
override func viewDidLoad() {
super.viewDidLoad()
loginContainerOriginY = loginContainer.center.y
signInContainerOriginY = signInContainer.center.y
// registering keyboard events
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
// animate the fields after view load
UIView.animateWithDuration(0.6, animations: {
self.loginContainer.transform = CGAffineTransformMakeScale(0.4, 0.4)
self.loginContainer.alpha = 1
self.loginContainer.transform = CGAffineTransformMakeScale(1, 1)
})
// configure gesture recognition for swipe down
var swipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "dismissKeyboard")
swipe.direction = UISwipeGestureRecognizerDirection.Down
self.view.addGestureRecognizer(swipe)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// back button event that pops the navigation view
@IBAction func backDidPress(sender: AnyObject) {
navigationController!.popViewControllerAnimated(true)
}
// show alert view
@IBAction func signInDidPress(sender: AnyObject) {
if(emailField.text == "") {
var alertView = UIAlertView(
title: "Email Required",
message: "Please enter your email",
delegate: self,
cancelButtonTitle: "OK"
)
alertView.show()
} else if(passwordField.text == "") {
var alertView = UIAlertView(
title: "Password Required",
message: "Please enter your password",
delegate: self,
cancelButtonTitle: "OK"
)
alertView.show()
} else {
var alertView = UIAlertView(
title: "Signing in…",
message: nil,
delegate: self,
cancelButtonTitle: nil
)
alertView.show()
delay(2) {
alertView.dismissWithClickedButtonIndex(0, animated: true)
self.checkPassword()
}
}
}
// dismiss keyboard when tapping anywhere outside
@IBAction func tapGesture(sender: AnyObject) {
view.endEditing(true)
}
// keyboard show & hide functions
func keyboardWillShow(notification: NSNotification!) {
var userInfo = notification.userInfo!
// Get the keyboard height and width from the notification
// Size varies depending on OS, language, orientation
var kbSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size
var durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
var animationDuration = durationValue.doubleValue
var curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber
var animationCurve = curveValue.integerValue
if(isKeyboardUp == false) {
UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions(UInt(animationCurve << 16)), animations: {
self.loginContainer.center.y = self.loginContainer.center.y - kbSize.height/2
self.signInContainer.center.y = self.signInContainer.center.y - kbSize.height
}, completion: nil)
isKeyboardUp = true
}
}
func keyboardWillHide(notification: NSNotification!) {
var userInfo = notification.userInfo!
// Get the keyboard height and width from the notification
// Size varies depending on OS, language, orientation
var kbSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size
var durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
var animationDuration = durationValue.doubleValue
var curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber
var animationCurve = curveValue.integerValue
UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions(UInt(animationCurve << 16)), animations: {
self.loginContainer.center.y = self.loginContainerOriginY
self.signInContainer.center.y = self.signInContainerOriginY
}, completion: nil)
isKeyboardUp = false
}
func checkPassword() {
if(emailField.text == "[email protected]" && passwordField.text == "123456") {
// successful signin
self.performSegueWithIdentifier("loginSegue", sender: self)
} else {
var alertView = UIAlertView(
title: "Sign In Failed",
message: "Invalid email or password",
delegate: self,
cancelButtonTitle: "OK"
)
alertView.show()
}
}
func dismissKeyboard() {
self.emailField.resignFirstResponder()
self.passwordField.resignFirstResponder()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | bd114b496218a7fd9b6e07717e2397c9 | 35.702857 | 144 | 0.632882 | 5.719501 | false | false | false | false |
huangboju/Moots | Examples/SwiftUI/CreatingAmacOSApp/Complete/Landmarks/Landmarks/Models/Data.swift | 1 | 2039 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Helpers for loading images and data.
*/
import Foundation
import CoreLocation
import SwiftUI
import ImageIO
let landmarkData: [Landmark] = load("landmarkData.json")
let features = landmarkData.filter { $0.isFeatured }
let hikeData: [Hike] = load("hikeData.json")
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
final class ImageStore {
typealias _ImageDictionary = [String: CGImage]
fileprivate var images: _ImageDictionary = [:]
fileprivate static var scale = 2
static var shared = ImageStore()
func image(name: String) -> Image {
let index = _guaranteeImage(name: name)
return Image(images.values[index], scale: CGFloat(ImageStore.scale), label: Text(name))
}
static func loadImage(name: String) -> CGImage {
guard
let url = Bundle.main.url(forResource: name, withExtension: "jpg"),
let imageSource = CGImageSourceCreateWithURL(url as NSURL, nil),
let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil)
else {
fatalError("Couldn't load image \(name).jpg from main bundle.")
}
return image
}
fileprivate func _guaranteeImage(name: String) -> _ImageDictionary.Index {
if let index = images.index(forKey: name) { return index }
images[name] = ImageStore.loadImage(name: name)
return images.index(forKey: name)!
}
}
| mit | 17a526e9df60fb3dbaf73b9be2770242 | 27.690141 | 95 | 0.632302 | 4.279412 | false | false | false | false |
Aishwarya-Ramakrishnan/sparkios | Source/Room/RoomClient.swift | 1 | 5473 | // Copyright 2016 Cisco Systems Inc
//
// 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
/// Room HTTP client
open class RoomClient: CompletionHandlerType<Room> {
private func requestBuilder() -> ServiceRequest.Builder {
return ServiceRequest.Builder().path("rooms")
}
/// List rooms. By default, lists rooms to which the authenticated user belongs.
///
/// - parameter teamId: Limit the rooms to those associated with a team, by ID.
/// - parameter max: Limit the maximum number of rooms in the response.
/// - parameter type: Available values: direct and group. direct returns all 1-to-1 rooms. group returns all group rooms. If not specified or values not matched, will return all room types.
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter completionHandler: A closure to be executed once the request has finished.
/// - returns: Void
open func list(teamId: String? = nil , max: Int? = nil, type: RoomType? = nil, queue: DispatchQueue? = nil, completionHandler: @escaping ArrayHandler) {
let request = requestBuilder()
.method(.get)
.query(RequestParameter(["teamId": teamId, "max": max, "type": type?.rawValue]))
.keyPath("items")
.queue(queue)
.build()
request.responseArray(completionHandler)
}
/// Creates a room. The authenticated user is automatically added as a member of the room. See the Memberships API to learn how to add more people to the room.
///
/// - parameter title: A user-friendly name for the room.
/// - parameter teamId: The ID for the team with which this room is associated.
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter completionHandler: A closure to be executed once the request has finished.
/// - returns: Void
open func create(title: String, teamId: String? = nil, queue: DispatchQueue? = nil, completionHandler: @escaping ObjectHandler) {
let request = requestBuilder()
.method(.post)
.body(RequestParameter(["title": title, "teamId": teamId]))
.queue(queue)
.build()
request.responseObject(completionHandler)
}
/// Shows details for a room by id. Specify the room id in the roomId parameter in the URI.
///
/// - parameter roomId: The room id.
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter completionHandler: A closure to be executed once the request has finished.
/// - returns: Void
open func get(roomId: String, queue: DispatchQueue? = nil, completionHandler: @escaping ObjectHandler) {
let request = requestBuilder()
.method(.get)
.path(roomId)
.queue(queue)
.build()
request.responseObject(completionHandler)
}
/// Updates details for a room by id. Specify the room id in the roomId parameter in the URI.
///
/// - parameter roomId: The room id.
/// - parameter title: A user-friendly name for the room.
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter completionHandler: A closure to be executed once the request has finished.
/// - returns: Void
open func update(roomId: String, title: String, queue: DispatchQueue? = nil, completionHandler: @escaping ObjectHandler) {
let request = requestBuilder()
.method(.put)
.body(RequestParameter(["title": title]))
.path(roomId)
.queue(queue)
.build()
request.responseObject(completionHandler)
}
/// Deletes a room by id. Specify the room id in the roomId parameter in the URI.
///
/// - parameter roomId: The room id.
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter completionHandler: A closure to be executed once the request has finished.
/// - returns: Void
open func delete(roomId: String, queue: DispatchQueue? = nil, completionHandler: @escaping AnyHandler) {
let request = requestBuilder()
.method(.delete)
.path(roomId)
.queue(queue)
.build()
request.responseJSON(completionHandler)
}
}
| mit | 505fcd0457618bcda566b492d6a29964 | 46.591304 | 193 | 0.666362 | 4.817782 | false | false | false | false |
CulturaMobile/culturamobile-api | Sources/App/Routes.swift | 1 | 24755 | import Vapor
import AuthProvider
import Sessions
import Foundation
import Storage
import Random
final class Routes: RouteCollection {
let view: ViewRenderer
init(_ view: ViewRenderer) {
self.view = view
}
func build(_ builder: RouteBuilder) throws {
}
}
public func splitFilename(str: String) -> (directory: String, filenameOnly: String, ext: String) {
let url = URL(fileURLWithPath: str)
return (url.deletingLastPathComponent().path, url.deletingPathExtension().lastPathComponent, url.pathExtension)
}
extension Droplet {
func setupRoutes() throws {
try setupUnauthenticatedRoutes()
try setupPasswordProtectedRoutes()
try setupTokenProtectedRoutes()
}
/// Sets up all routes that can be accessed
/// without any authentication. This includes
/// creating a new User.
private func setupUnauthenticatedRoutes() throws {
// MARK: Request City
get("api/cities") { req in
let cities = try City.makeQuery().all().makeJSON()
return cities
}
put("api/cities") { req in
guard let json = req.json else {
throw Abort(.badRequest)
}
let city = try City(json: json)
guard try City.makeQuery().filter("name", city.name).first() == nil else {
throw Abort(.badRequest, reason: "A cidade já existe")
}
try city.save()
return city
}
get("api/cities") { req in
let cities = try City.makeQuery().all().makeJSON()
return cities
}
get("api/cities/:cityId") { req in
let cityId = req.parameters["cityId"]?.string
let city = try City.makeQuery().filter("id", cityId).first()?.makeJSON()
return city!
}
patch("api/cities/:cityId") { req in
guard let name = req.json?["name"]?.string else {
throw Abort(.badRequest)
}
let cityId = req.parameters["cityId"]?.string
let city = try City.makeQuery().filter("id", cityId).first()
city?.name = name
try city?.save()
return try city!.makeJSON()
}
delete("api/cities/:cityId") { req in
let cityId = req.parameters["cityId"]?.string
let city = try City.makeQuery().filter("id", cityId).first()
try city?.delete()
return Response(status: .ok)
}
// MARK: Request Franchise
put("api/:cityId/franchises") { req in
guard let json = req.json else {
throw Abort(.badRequest)
}
let owner = try User.find(json["user_id"]?.int)
let city = try City.find(json["city_id"]?.int)
let franchise = Franchise(name: (json["name"]?.string)!, code: (json["code"]?.string)!, owner: owner!, city: city!)
guard try Franchise.makeQuery().filter("name", franchise.name).first() == nil else {
throw Abort(.badRequest, reason: "Name already exists")
}
guard try Franchise.makeQuery().filter("code", franchise.code).first() == nil else {
throw Abort(.badRequest, reason: "Code already exists")
}
try franchise.save()
return franchise
}
get("api/:cityId/franchises") { req in
let cityId = req.parameters["cityId"]?.int
let franchises = try Franchise.makeQuery().filter("city_id", cityId).all().makeJSON()
return franchises
}
get("api/:cityId/franchises/:franchiseId") { req in
let franchiseId = req.parameters["franchiseId"]?.string
let franchise = try Franchise.makeQuery().filter("id", franchiseId).first()?.makeJSON()
return franchise!
}
patch("api/:cityId/franchises/:franchiseId") { req in
guard let json = req.json else {
throw Abort(.badRequest)
}
let franchiseId = req.parameters["franchiseId"]?.int
let franchise = try Franchise.makeQuery().filter("id", franchiseId).first()
let owner = try User.find(json["user_id"]?.int)
let city = try City.find(json["city_id"]?.int)
franchise?.name = (json["name"]?.string)!
franchise?.code = (json["code"]?.string)!
franchise?.owner = owner?.id
franchise?.city = city?.id
try franchise?.save()
return try franchise!.makeJSON()
}
delete("api/:cityId/franchises/:franchiseId") { req in
let franchiseId = req.parameters["franchiseId"]?.string
let franchise = try Franchise.makeQuery().filter("id", franchiseId).first()
try franchise?.delete()
return Response(status: .ok)
}
// MARK: Request Item Types
get("api/item-types") { req in
let itemType = try ItemType.makeQuery().all().makeJSON()
return itemType
}
put("api/item-types") { req in
guard let json = req.json else {
throw Abort(.badRequest)
}
let itemType = try ItemType(json: json)
guard try ItemType.makeQuery().filter("name", itemType.name).first() == nil else {
throw Abort(.badRequest, reason: "Item Type Already Exist")
}
try itemType.save()
return itemType
}
get("api/item-types/:itemTypeId") { req in
let itemTypeId = req.parameters["itemTypeId"]?.string
let itemType = try ItemType.makeQuery().filter("id", itemTypeId).first()?.makeJSON()
return itemType!
}
patch("api/item-types/:itemTypeId") { req in
guard let name = req.json?["name"]?.string else {
throw Abort(.badRequest)
}
let itemTypeId = req.parameters["cityId"]?.string
let itemType = try ItemType.makeQuery().filter("id", itemTypeId).first()
itemType?.name = name
try itemType?.save()
return try itemType!.makeJSON()
}
delete("api/item-types/:itemTypeId") { req in
let itemTypeId = req.parameters["itemTypeId"]?.string
let itemType = try ItemType.makeQuery().filter("id", itemTypeId).first()
try itemType?.delete()
return Response(status: .ok)
}
// MARK: Request Images
get("api/images") { req in
let images = try Image.makeQuery().all().makeJSON()
return images
}
get("api/images/:imageId") { req in
let imageId = req.parameters["imageId"]?.string
let image = try Image.makeQuery().filter("id", imageId).first()?.makeJSON()
return image!
}
put("api/images") { req in
guard let json = req.json else {
throw Abort(.badRequest)
}
let image = Image(url: (json["url"]?.string)!)
try image.save()
return image
}
delete("api/images/:imageId") { req in
let imageId = req.parameters["imageId"]?.string
let image = try Image.makeQuery().filter("id", imageId).first()
try image?.delete()
return Response(status: .ok)
}
// MARK: Request Categories
get("api/:franchiseCode/categories") { req in
let franchiseCode = req.parameters["franchiseCode"]?.string
let currentFranchise = try Franchise.makeQuery().filter("code", franchiseCode).first()
let categories = try Category.makeQuery().filter("franchise_id", currentFranchise?.id).all().makeJSON()
return categories
}
// MARK: Request Venues
get("api/:franchiseCode/venues") { req in
let franchiseCode = req.parameters["franchiseCode"]?.string
let currentFranchise = try Franchise.makeQuery().filter("code", franchiseCode).first()
let venues = try Venue.makeQuery().filter("franchise_id", currentFranchise?.id).all().makeJSON()
return venues
}
put("api/:franchiseCode/venues") { req in
let franchiseCode = req.parameters["franchiseCode"]?.string
let currentFranchise = try Franchise.makeQuery().filter("code", franchiseCode).first()
guard let json = req.json else {
throw Abort(.badRequest)
}
guard let name = json["name"]?.string else {
throw Abort(.badRequest, reason: "Need Name")
}
guard let description = json["description"]?.string else {
throw Abort(.badRequest, reason: "Need Description")
}
guard let latitude = json["location"]?["latitude"]?.string else {
throw Abort(.badRequest, reason: "Need Latitude")
}
guard let longitude = json["location"]?["longitude"]?.string else {
throw Abort(.badRequest, reason: "Need Longitude")
}
guard let address = json["location"]?["address"]?.string else {
throw Abort(.badRequest, reason: "Need Address")
}
guard let phone = json["phone"]?.string else {
throw Abort(.badRequest, reason: "Need phone")
}
guard let cellphone = json["cellphone"]?.string else {
throw Abort(.badRequest, reason: "Need phone")
}
guard let priceTier = json["price_tier"]?.double else {
throw Abort(.badRequest, reason: "Need price tier")
}
let venue = Venue(name: name, description: description, phone: phone, cellphone: cellphone, priceTier: priceTier, franchise: currentFranchise!)
try venue.save()
for c in (json["categories"]?.array)! {
let currentCategory = try Category.makeQuery().filter("name", c["name"]?.string).first()
if (currentCategory != nil) {
} else {
let itemType = try ItemType.find(c["category_type_id"]?.int)
let image = try Image.find(c["image_id"]?.int)
let size = c["size"]?.string
let position = c["position"]?.int
// currentCategory = Category(name: (c["name"]?.string)!, type: itemType!, size: size!, image: image!, position: position!, franchise: currentFranchise!)
//
// try currentCategory?.save()
}
let venueCategory = VenueCategory(venue: venue, category: currentCategory!)
try venueCategory.save()
}
for i in (json["images"]?.array)! {
let currentImage = try Image.makeQuery().filter("id", i["id"]?.int).first()
let venueImage = VenueImage(venue: venue, image: currentImage!)
try venueImage.save()
}
let location = Location(latitude: latitude, longitude: longitude, address: address)
try location.save()
let venueLocation = VenueLocation(venue: venue, location: location)
try venueLocation.save()
for oh in (json["open_hours"]?.array)! {
let currentOpenHour = OpenHour(day: (oh["day"]?.string)!, open: (oh["open"]?.string)!, close: (oh["close"]?.string)!)
try currentOpenHour.save()
let venueOpenHour = VenueOpenHours(venue: venue, openHours: currentOpenHour)
try venueOpenHour.save()
}
for t in (json["tags"]?.array)! {
var currentTag = try Tag.makeQuery().filter("name", t["name"]?.string).first()
if (currentTag != nil) {
} else {
currentTag = Tag(name: (t["name"]?.string)!)
try currentTag?.save()
}
let venueTag = VenueTag(venue: venue, tag: currentTag!)
try venueTag.save()
}
return venue
}
get("api/:franchiseCode/venues/:venueId") { req in
let venueId = req.parameters["venueId"]?.string
let venue = try Venue.makeQuery().filter("id", venueId).first()?.makeJSON()
return venue!
}
// MARK: Request Events
get("api/:franchiseCode/events") { req in
let franchiseCode = req.parameters["franchiseCode"]?.string
let currentFranchise = try Franchise.makeQuery().filter("code", franchiseCode).first()
let events = try Event.makeQuery().filter("franchise_id", currentFranchise?.id).all().makeJSON()
return events
}
put("api/:franchiseCode/events") { req in
let franchiseCode = req.parameters["franchiseCode"]?.string
let currentFranchise = try Franchise.makeQuery().filter("code", franchiseCode).first()
guard let json = req.json else {
throw Abort(.badRequest)
}
guard let title = json["title"]?.string else {
throw Abort(.badRequest, reason: "Need title")
}
guard let description = json["description"]?.string else {
throw Abort(.badRequest, reason: "Need description")
}
guard let priceTier = json["price_tier"]?.double else {
throw Abort(.badRequest, reason: "Need price tier")
}
guard let venueId = json["venue_id"]?.int else {
throw Abort(.badRequest, reason: "Need venue")
}
guard let phone = json["phone"]?.string else {
throw Abort(.badRequest, reason: "Need phone")
}
guard let cellphone = json["cellphone"]?.string else {
throw Abort(.badRequest, reason: "Need cellphone")
}
let currentVenue = try Venue.find(venueId)
let event = Event(franchise: currentFranchise!, title: title, description: description, priceTier: priceTier, venue: currentVenue!, phone: phone, cellphone: cellphone)
try event.save()
for c in (json["categories"]?.array)! {
var currentCategory = try Category.makeQuery().filter("name", c["name"]?.string).first()
if (currentCategory != nil) {
} else {
let itemType = try ItemType.find(c["category_type_id"]?.int)
let image = try Image.find(c["image_id"]?.int)
let size = c["size"]?.string
let position = c["position"]?.int
// currentCategory = Category(name: (c["name"]?.string)!, type: itemType!, size: size!, image: image!, position: position!, franchise: currentFranchise!)
//
// try currentCategory?.save()
}
let eventCategory = EventCategory(event: event, category: currentCategory!)
try eventCategory.save()
}
for i in (json["images"]?.array)! {
let currentImage = try Image.makeQuery().filter("id", i["id"]?.int).first()
let eventImage = EventImage(event: event, image: currentImage!)
try eventImage.save()
}
for d in (json["dates"]?.array)! {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let startDateFormated = dateFormatter.date(from: (d["start_date"]?.string)!)
let endDateFormated = dateFormatter.date(from: (d["end_date"]?.string)!)
let currentDate = Dates(startDate: startDateFormated!, endDate: endDateFormated!)
try currentDate.save()
let eventDate = EventDate(event: event, date: currentDate)
try eventDate.save()
}
for t in (json["tags"]?.array)! {
var currentTag = try Tag.makeQuery().filter("name", t["name"]?.string).first()
if (currentTag != nil) {
} else {
currentTag = Tag(name: (t["name"]?.string)!)
try currentTag?.save()
}
let eventTag = EventTag(event: event, tag: currentTag!)
try eventTag.save()
}
return event
}
get("api/:franchiseCode/events/:eventId") { req in
let eventId = req.parameters["eventId"]?.string
let event = try Event.makeQuery().filter("id", eventId).first()?.makeJSON()
return event!
}
// MARK: Tags
// MARK: Request Comments
// MARK: Guest List
// MARK: Users
// MARK: Roles
// MARK: Permissions
put("users") { req in
// require that the request body be json
guard let json = req.json else {
throw Abort(.badRequest)
}
// initialize the name and email from
// the request json
let user = try User(json: json)
// ensure no user with this email already exists
guard try User.makeQuery().filter("email", user.email).first() == nil else {
throw Abort(.badRequest, reason: "A user with that email already exists.")
}
// require a plaintext password is supplied
guard let password = json["password"]?.string else {
throw Abort(.badRequest)
}
// hash the password and set it on the user
user.password = try self.hash.make(password.makeBytes()).makeString()
// save and return the new user
try user.save()
return user
}
put("users-app") { req in
// require that the request body be json
guard let json = req.json else {
throw Abort(.badRequest)
}
// initialize the name and email from
// the request json
let user = try User(withFB: json)
// ensure no user with this email already exists
guard try User.makeQuery().filter("fbID", user.fbID).first() == nil else {
throw Abort(.badRequest, reason: "A user with that FBId already exists.")
}
// require a plaintext password is supplied
guard let email = json["email"]?.string else {
throw Abort(.badRequest)
}
// save and return the new user
try user.save()
return user
}
// create a new user
//
// POST /users
// <json containing new user information>
post("users") { req in
// require that the request body be json
guard let json = req.json else {
throw Abort(.badRequest)
}
// initialize the name and email from
// the request json
let user = try User(json: json)
// ensure no user with this email already exists
guard try User.makeQuery().filter("email", user.email).first() == nil else {
throw Abort(.badRequest, reason: "A user with that email already exists.")
}
// require a plaintext password is supplied
guard let password = json["password"]?.string else {
throw Abort(.badRequest)
}
// hash the password and set it on the user
user.password = try self.hash.make(password.makeBytes()).makeString()
// save and return the new user
try user.save()
return user
}
}
/// Sets up all routes that can be accessed using
/// username + password authentication.
/// Since we want to minimize how often the username + password
/// is sent, we will only use this form of authentication to
/// log the user in.
/// After the user is logged in, they will receive a token that
/// they can use for further authentication.
private func setupPasswordProtectedRoutes() throws {
// creates a route group protected by the password middleware.
// the User type can be passed to this middleware since it
// conforms to PasswordAuthenticatable
let password = grouped([
PasswordAuthenticationMiddleware(User.self)
])
// verifies the user has been authenticated using the password
// middleware, then generates, saves, and returns a new access token.
//
// POST /login
// Authorization: Basic <base64 email:password>
password.post("login") { req in
let user = try req.user()
let token = try Token.generate(for: user)
try token.save()
return "user"
}
}
/// Sets up all routes that can be accessed using
/// the authentication token received during login.
/// All of our secure routes will go here.
private func setupTokenProtectedRoutes() throws {
// creates a route group protected by the token middleware.
// the User type can be passed to this middleware since it
// conforms to TokenAuthenticatable
let token = grouped([
TokenAuthenticationMiddleware(User.self)
])
// simply returns a greeting to the user that has been authed
// using the token middleware.
//
// GET /me
// Authorization: Bearer <token from /login>
token.get("api/:franchiseCode/user") { req in
let franchiseCode = req.parameters["franchiseCode"]?.string
let user = try req.user()
return "Hello, \(user.name)"
}
}
}
| mit | 85cae77570e10da46b90b96f704ed5e7 | 33.963277 | 179 | 0.486467 | 5.36149 | false | false | false | false |
10686142/eChance | Iraffle/MoreVC.swift | 1 | 4176 | //
// MoreVC.swift
// Iraffle
//
// Created by Vasco Meerman on 03/05/2017.
// Copyright © 2017 Vasco Meerman. All rights reserved.
//
import UIKit
class MoreVC: UIViewController {
// MARK: - Outlets.
@IBOutlet weak var backHomeButton: UIButton!
@IBOutlet weak var logOutButton: UIButton!
@IBOutlet weak var shareCodeButton: UIButton!
@IBOutlet weak var accountButton: UIButton!
@IBOutlet weak var instagramButton: UIButton!
@IBOutlet weak var twitterButton: UIButton!
@IBOutlet weak var facebookButton: UIButton!
@IBOutlet weak var isIraffleRealButton: UIButton!
@IBOutlet weak var termsAndConditionsButton: UIButton!
// MARK: - Contants and Variables.
let defaults = UserDefaults.standard
var referalCode: String!
var sendURL: URL!
// CHANGE THESE TO CORRESPONDING PAGES
let instaLink = "https://www.instagram.com/?hl=en"
let twitterLink = "https://twitter.com"
let fbLink = "https://www.facebook.com"
let iraffleRealLink = "https://raffler.co/"
let termsAndCondLink = "https://raffler.co/"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func accountTapped(_ sender: Any) {
let vc = storyboard?.instantiateViewController(withIdentifier: "accountVC") as! AccountVC
present(vc, animated: true, completion: nil)
}
@IBAction func instagramTapped(_ sender: Any) {
defaults.set("Iraffle on Instagram", forKey: "sourceURL")
defaults.set(instaLink, forKey: "webPageURL")
let vc = storyboard?.instantiateViewController(withIdentifier: "webPageVC") as! WebPageVC
present(vc, animated: true, completion: nil)
}
@IBAction func twitterTapped(_ sender: Any) {
defaults.set("Iraffle on Twitter", forKey: "sourceURL")
defaults.set(twitterLink, forKey: "webPageURL")
let vc = storyboard?.instantiateViewController(withIdentifier: "webPageVC") as! WebPageVC
present(vc, animated: true, completion: nil)
}
@IBAction func facebookTapped(_ sender: Any) {
defaults.set("Iraffle on Facebook", forKey: "sourceURL")
defaults.set(fbLink, forKey: "webPageURL")
let vc = storyboard?.instantiateViewController(withIdentifier: "webPageVC") as! WebPageVC
present(vc, animated: true, completion: nil)
}
@IBAction func isIraffleRealTapped(_ sender: Any) {
defaults.set("Authenticity Iraffle", forKey: "sourceURL")
defaults.set(iraffleRealLink, forKey: "webPageURL")
let vc = storyboard?.instantiateViewController(withIdentifier: "webPageVC") as! WebPageVC
present(vc, animated: true, completion: nil)
}
@IBAction func termsAndConditionsTapped(_ sender: Any) {
defaults.set("Terms & Conditions", forKey: "sourceURL")
defaults.set(termsAndCondLink, forKey: "webPageURL")
let vc = storyboard?.instantiateViewController(withIdentifier: "webPageVC") as! WebPageVC
present(vc, animated: true, completion: nil)
}
@IBAction func shareCodeTapped(_ sender: Any) {
let textToShare = "Use this referal code to download the Iraffle App!"
// THIS HAS TE BE CHANGED DYNAMICALLY
referalCode = "ABCDE"
if referalCode != nil {
let vc = UIActivityViewController(activityItems: [textToShare, referalCode], applicationActivities: [])
self.present(vc, animated: true)
}
}
@IBAction func backHomeTapped(_ sender: Any) {
let vc = storyboard?.instantiateViewController(withIdentifier: "homeVC") as! HomeVC
present(vc, animated: true, completion: nil)
}
// ADD CODE TO ACTUALLY LOGOUT
@IBAction func logOutTapped(_ sender: Any) {
let vc = storyboard?.instantiateViewController(withIdentifier: "loginVC") as! LoginVC
present(vc, animated: true, completion: nil)
}
}
| mit | 1b62964bf41ea0fafb5c455c4d460c13 | 36.276786 | 115 | 0.666108 | 4.299691 | false | false | false | false |
viviancrs/fanboy | Pods/SwiftMessages/SwiftMessages/WindowViewController.swift | 1 | 1307 | //
// WindowViewController.swift
// SwiftMessages
//
// Created by Timothy Moose on 8/1/16.
// Copyright © 2016 SwiftKick Mobile LLC. All rights reserved.
//
import UIKit
class WindowViewController: UIViewController
{
fileprivate var window: UIWindow?
let windowLevel: UIWindowLevel
var statusBarStyle: UIStatusBarStyle?
init(windowLevel: UIWindowLevel = UIWindowLevelNormal)
{
self.windowLevel = windowLevel
let window = PassthroughWindow(frame: UIScreen.main.bounds)
self.window = window
super.init(nibName: nil, bundle: nil)
self.view = PassthroughView()
window.rootViewController = self
window.windowLevel = windowLevel
}
func install() {
guard let window = window else { return }
window.makeKeyAndVisible()
}
func uninstall() {
window?.isHidden = true
window = nil
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public var preferredStatusBarStyle: UIStatusBarStyle {
return statusBarStyle ?? UIApplication.shared.statusBarStyle
}
override var prefersStatusBarHidden: Bool {
return UIApplication.shared.isStatusBarHidden
}
}
| gpl-3.0 | 303d50cf4c3a3e36c7a683f885378b7a | 25.12 | 68 | 0.660031 | 5.24498 | false | false | false | false |
toadzky/SLF4Swift | Backend/XCGLogger/XCGLogger.swift | 1 | 4587 | //
// XCGLogger.swift
// SLF4Swift
/*
The MIT License (MIT)
Copyright (c) 2015 Eric Marchand (phimage)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
#if EXTERNAL
import SLF4Swift
#endif
import XCGLogger
public class XCGLoggerSLF: LoggerType {
public class var instance : XCGLoggerSLF {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : XCGLoggerSLF?
}
dispatch_once(&Static.onceToken) {
Static.instance = XCGLoggerSLF(logger: XCGLogger.defaultInstance())
}
return Static.instance!
}
public var level: SLFLogLevel {
get {
return XCGLoggerSLF.toLevel(self.logger.outputLogLevel)
}
set {
self.logger.outputLogLevel = XCGLoggerSLF.fromLevel(newValue)
}
}
public var name: LoggerKeyType {
return self.logger.identifier
}
public var logger: XCGLogger
public init(logger: XCGLogger) {
self.logger = logger
}
public func info(message: LogMessageType) {
self.logger.info(message)
}
public func error(message: LogMessageType) {
self.logger.error(message)
}
public func severe(message: LogMessageType) {
self.logger.severe(message)
}
public func warn(message: LogMessageType) {
self.logger.warning(message)
}
public func debug(message: LogMessageType) {
self.logger.debug(message)
}
public func verbose(message: LogMessageType) {
self.logger.verbose(message)
}
public func log(level: SLFLogLevel,_ message: LogMessageType) {
self.logger.logln(XCGLoggerSLF.fromLevel(level), closure: {message})
}
public func isLoggable(level: SLFLogLevel) -> Bool {
return level <= self.level
}
public static func toLevel(level:XCGLogger.LogLevel) -> SLFLogLevel {
switch(level){
case .None: return SLFLogLevel.Off
case .Severe: return SLFLogLevel.Severe
case .Error: return SLFLogLevel.Error
case .Warning: return SLFLogLevel.Warn
case .Info: return SLFLogLevel.Info
case .Debug: return SLFLogLevel.Debug
case .Verbose: return SLFLogLevel.Verbose
}
}
public static func fromLevel(level:SLFLogLevel) -> XCGLogger.LogLevel {
switch(level){
case .Off: return XCGLogger.LogLevel.None
case .Severe: return XCGLogger.LogLevel.Severe
case .Error: return XCGLogger.LogLevel.Error
case .Warn: return XCGLogger.LogLevel.Warning
case .Info: return XCGLogger.LogLevel.Info
case .Debug: return XCGLogger.LogLevel.Debug
case .Verbose: return XCGLogger.LogLevel.Verbose
case .All: return XCGLogger.LogLevel.Verbose
}
}
}
public class XCGLoggerSLFFactory: SLFLoggerFactory {
public class var instance : XCGLoggerSLFFactory {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : XCGLoggerSLFFactory?
}
dispatch_once(&Static.onceToken) {
let factory = XCGLoggerSLFFactory()
Static.instance = factory
factory.addLogger(XCGLoggerSLF.instance)
}
return Static.instance!
}
public override init(){
super.init()
}
public override func doCreateLogger(name: LoggerKeyType) -> LoggerType {
let logger = XCGLogger()
logger.identifier = name
return XCGLoggerSLF(logger: logger)
}
} | mit | 7c652e36dfafc0ef9fa1bd9ed5ea48f3 | 30.424658 | 79 | 0.670809 | 4.510324 | false | false | false | false |
M2Mobi/Marky-Mark | markymark/Classes/Layout Builders/AttributedString/Block Builders/Block/ListAttributedStringLayoutBlockBuilder.swift | 1 | 3896 | //
// Created by Jim van Zummeren on 06/05/16.
// Copyright © 2016 M2mobi. All rights reserved.
//
import Foundation
import UIKit
class ListAttributedStringLayoutBlockBuilder: InlineAttributedStringLayoutBlockBuilder {
// MARK: LayoutBuilder
override func relatedMarkDownItemType() -> MarkDownItem.Type {
return UnorderedListMarkDownItem.self
}
override func build(_ markDownItem: MarkDownItem, asPartOfConverter converter: MarkDownConverter<NSMutableAttributedString>, styling: ItemStyling) -> NSMutableAttributedString {
let listMarkDownItem = markDownItem as! ListMarkDownItem
let listAttributedString = getListAttributedString(listMarkDownItem, styling: styling)
return listAttributedString
}
// MARK: Private
}
private extension ListAttributedStringLayoutBlockBuilder {
/**
Loops recursively through all listItems to create
vertically appended list of ListItemView's
- parameter listMarkDownItem: MarkDownItem to loop through
- parameter styling: Styling to apply to each list item
- returns: A view containing all list items of given markDownItem
*/
func getListAttributedString(_ listMarkDownItem: ListMarkDownItem, styling: ItemStyling, level: CGFloat = 0) -> NSMutableAttributedString {
let listAttributedString = NSMutableAttributedString()
for listItem in listMarkDownItem.listItems ?? [] {
let bulletStyling = styling as? BulletStylingRule
let listStyling = styling as? ListItemStylingRule
let listItemAttributedString = NSMutableAttributedString()
listItemAttributedString.append(getBulletCharacter(listItem, styling: bulletStyling))
listItemAttributedString.addAttributes(
getBulletIndentingAttributesForLevel(level, listStyling: listStyling),
range: listItemAttributedString.fullRange()
)
let attributedString = attributedStringForMarkDownItem(listItem, styling: styling)
listItemAttributedString.append(attributedString)
listItemAttributedString.append(NSAttributedString(string: "\n"))
listAttributedString.append(listItemAttributedString)
if let nestedListItems = listItem.listItems, nestedListItems.count > 0 {
listAttributedString.append(getListAttributedString(listItem, styling: styling, level: level + 1))
}
}
return listAttributedString
}
func getBulletCharacter(_ listMarkDownItem: ListMarkDownItem, styling: BulletStylingRule?) -> NSAttributedString {
let string: String
if let indexCharacter = listMarkDownItem.indexCharacter {
string = indexCharacter + " "
} else {
string = "• "
}
return NSMutableAttributedString(string: string, attributes: getBulletStylingAttributes(styling))
}
func getBulletStylingAttributes(_ styling: BulletStylingRule?) -> [NSAttributedString.Key: Any] {
var attributes = [NSAttributedString.Key: Any]()
if let font = styling?.bulletFont {
attributes[.font] = font
}
if let textColor = styling?.bulletColor {
attributes[.foregroundColor] = textColor
}
return attributes
}
func getBulletIndentingAttributesForLevel(_ level: CGFloat, listStyling: ListItemStylingRule?) -> [NSAttributedString.Key: Any] {
let listIndentSpace = (listStyling?.listIdentSpace ?? 0)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.paragraphSpacing = (listStyling?.bottomListItemSpacing ?? 0)
paragraphStyle.firstLineHeadIndent = listIndentSpace * level
paragraphStyle.headIndent = listIndentSpace + listIndentSpace * level
return [.paragraphStyle: paragraphStyle]
}
}
| mit | e3f8ef41beeaa4ae54d36035d00a4546 | 35.726415 | 181 | 0.701516 | 5.69152 | false | false | false | false |
JadenGeller/Calcula | Sources/Term+Lossless.swift | 1 | 4024 | //
// Term+Lossless.swift
// Calcula
//
// Created by Jaden Geller on 6/12/16.
// Copyright © 2016 Jaden Geller. All rights reserved.
//
public enum ParseError: ErrorType {
case expectedCharacter(Character)
case expectedIdentifier
case expectedEnd
}
extension Term {
public init?(_ description: String) {
do {
self = try Term(parsing: description)
} catch {
return nil
}
}
public init(parsing description: String) throws {
var bindings: [String: Binding] = [:]
self = try Term(parsing: description, withExistingBindings: &bindings)
}
public init(parsing description: String, inout withExistingBindings bindings: [String : Binding]) throws {
var state = description.characters.generate()
let term = try Term(term: &state, bindings: &bindings)
guard state.peek() == nil else { throw ParseError.expectedEnd }
self = term
}
private init(inout term state: IndexingGenerator<String.CharacterView>, inout bindings: [String : Binding]) throws {
guard state.peek() != "λ" else {
self = try Term(lambda: &state, bindings: &bindings)
return
}
var terms: [Term] = []
repeat {
if state.peek() == "(" {
terms.append(try Term(parenthesized: &state, bindings: &bindings))
} else {
terms.append(try Term(variable: &state, bindings: &bindings))
}
while state.peek() == " " { state.next() } // Skip whitespace
} while state.peek() != nil && state.peek() != ")"
self = terms.reduce(Term.application)!
}
private init(inout parenthesized state: IndexingGenerator<String.CharacterView>, inout bindings: [String : Binding]) throws {
guard "(" == state.next() else { throw ParseError.expectedCharacter("(") }
let term = try Term(term: &state, bindings: &bindings)
guard ")" == state.next() else { throw ParseError.expectedCharacter(")") }
self = term
}
private init(inout variable state: IndexingGenerator<String.CharacterView>, inout bindings: [String : Binding]) throws {
let identifier: String = {
var characters: [Character] = []
while let character = state.peek() where "A"..."z" ~= character || "0"..."9" ~= character {
state.next()
characters.append(character)
}
return String(characters)
}()
guard identifier.characters.count > 0 else { throw ParseError.expectedIdentifier }
let binding: Binding = {
if let existing = bindings[identifier] { return existing }
else {
let new = Binding()
bindings[identifier] = new
return new
}
}()
self = Term.variable(binding)
}
private init(inout lambda state: IndexingGenerator<String.CharacterView>, inout bindings: [String : Binding]) throws {
guard state.next() == "λ" else { throw ParseError.expectedCharacter("λ") }
guard case .variable(let binding) = try Term(variable: &state, bindings: &bindings) else { fatalError() }
guard state.next() == "." else { throw ParseError.expectedCharacter(".") }
let term = try Term(term: &state, bindings: &bindings)
self = Term.lambda(binding, term)
}
}
extension IndexingGenerator {
private func peek() -> Generator.Element? {
var copy = self
return copy.next()
}
}
extension SequenceType where SubSequence: SequenceType {
private func reduce(@noescape combine: (Self.Generator.Element, Self.Generator.Element) throws -> Self.Generator.Element) rethrows -> Self.Generator.Element? {
var generator = generate()
var result = generator.next()
while let next = generator.next() {
result = try combine(result!, next)
}
return result
}
}
| mit | 38d251ca9beea7f15354cda0aa913c08 | 36.222222 | 163 | 0.59403 | 4.631336 | false | false | false | false |
austinzheng/swift | test/attr/attr_objc.swift | 1 | 94686 | // RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference | %FileCheck %s
// RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference > %t.ast
// RUN: %FileCheck -check-prefix CHECK-DUMP %s < %t.ast
// REQUIRES: objc_interop
import Foundation
class PlainClass {}
struct PlainStruct {}
enum PlainEnum {}
protocol PlainProtocol {} // expected-note {{protocol 'PlainProtocol' declared here}}
enum ErrorEnum : Error {
case failed
}
@objc class Class_ObjC1 {}
protocol Protocol_Class1 : class {} // expected-note {{protocol 'Protocol_Class1' declared here}}
protocol Protocol_Class2 : class {}
@objc protocol Protocol_ObjC1 {}
@objc protocol Protocol_ObjC2 {}
//===--- Subjects of @objc attribute.
@objc extension PlainStruct { } // expected-error{{'@objc' can only be applied to an extension of a class}}{{1-7=}}
class FáncyName {}
@objc (FancyName) extension FáncyName {}
@objc
var subject_globalVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
var subject_getterSetter: Int {
@objc
get { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
return 0
}
@objc
set { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
}
var subject_global_observingAccessorsVar1: Int = 0 {
@objc
willSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
}
@objc
didSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
}
}
class subject_getterSetter1 {
var instanceVar1: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
}
var instanceVar2: Int {
get {
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var instanceVar3: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var observingAccessorsVar1: Int = 0 {
@objc
willSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
@objc
didSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
}
}
class subject_staticVar1 {
@objc
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
@objc
class var staticVar2: Int { return 42 }
}
@objc
func subject_freeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}}
@objc
var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_nestedFreeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
}
@objc
func subject_genericFunc<T>(t: T) { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}}
@objc
var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
func subject_funcParam(a: @objc Int) { // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@objc }} {{27-33=}}
}
@objc // expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}}
struct subject_struct {
@objc
var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
@objc // expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}}
struct subject_genericStruct<T> {
@objc
var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
@objc
class subject_class1 { // no-error
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no-error
}
@objc
class subject_class2 : Protocol_Class1, PlainProtocol { // no-error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}}
class subject_genericClass<T> {
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{1-7=}}
class subject_genericClass2<T> : Class_ObjC1 {
@objc
var subject_instanceVar: Int // no-error
@objc
init(foo: Int) {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
extension subject_genericClass where T : Hashable {
@objc var prop: Int { return 0 } // expected-error{{members of constrained extensions cannot be declared @objc}}
}
extension subject_genericClass {
@objc var extProp: Int { return 0 } // expected-error{{members of extensions of generic classes cannot be declared @objc}}
@objc func extFoo() {} // expected-error{{members of extensions of generic classes cannot be declared @objc}}
}
@objc
enum subject_enum: Int {
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement1
@objc(subject_enumElement2)
case subject_enumElement2
@objc(subject_enumElement3)
case subject_enumElement3, subject_enumElement4 // expected-error {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}}{{3-30=}}
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement5, subject_enumElement6
@nonobjc // expected-error {{'@nonobjc' attribute cannot be applied to this declaration}}
case subject_enumElement7
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
enum subject_enum2 {
@objc(subject_enum2Element1)
case subject_enumElement1 // expected-error{{'@objc' enum case is not allowed outside of an '@objc' enum}}{{3-31=}}
}
@objc
protocol subject_protocol1 {
@objc
var subject_instanceVar: Int { get }
@objc
func subject_instanceFunc()
}
@objc protocol subject_protocol2 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol2 {
@objc protocol subject_protocol3 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol3 {
@objc
protocol subject_protocol4 : PlainProtocol {} // expected-error {{@objc protocol 'subject_protocol4' cannot refine non-@objc protocol 'PlainProtocol'}}
@objc
protocol subject_protocol5 : Protocol_Class1 {} // expected-error {{@objc protocol 'subject_protocol5' cannot refine non-@objc protocol 'Protocol_Class1'}}
@objc
protocol subject_protocol6 : Protocol_ObjC1 {}
protocol subject_containerProtocol1 {
@objc
var subject_instanceVar: Int { get } // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc
func subject_instanceFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc
static func subject_staticFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
@objc
protocol subject_containerObjCProtocol1 {
func func_FunctionReturn1() -> PlainStruct
// expected-error@-1 {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_FunctionParam1(a: PlainStruct)
// expected-error@-1 {{method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_Variadic(_: AnyObject...)
// expected-error @-1{{method cannot be a member of an @objc protocol because it has a variadic parameter}}
// expected-note @-2{{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
subscript(a: PlainStruct) -> Int { get }
// expected-error@-1 {{subscript cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
var varNonObjC1: PlainStruct { get }
// expected-error@-1 {{property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
}
@objc
protocol subject_containerObjCProtocol2 {
init(a: Int)
@objc init(a: Double)
func func1() -> Int
@objc func func1_() -> Int
var instanceVar1: Int { get set }
@objc var instanceVar1_: Int { get set }
subscript(i: Int) -> Int { get set }
@objc subscript(i: String) -> Int { get set}
}
protocol nonObjCProtocol {
@objc func objcRequirement() // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
func concreteContext1() {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext2 {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext3 {
func dynamicSelf1() -> Self { return self }
@objc func dynamicSelf1_() -> Self { return self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func genericParams<T: NSObject>() -> [T] { return [] }
// expected-error@-1{{method cannot be marked @objc because it has generic parameters}}
@objc func returnObjCProtocolMetatype() -> NSCoding.Protocol { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias AnotherNSCoding = NSCoding
typealias MetaNSCoding1 = NSCoding.Protocol
typealias MetaNSCoding2 = AnotherNSCoding.Protocol
@objc func returnObjCAliasProtocolMetatype1() -> AnotherNSCoding.Protocol { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnObjCAliasProtocolMetatype2() -> MetaNSCoding1 { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnObjCAliasProtocolMetatype3() -> MetaNSCoding2 { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias Composition = NSCopying & NSCoding
@objc func returnCompositionMetatype1() -> Composition.Protocol { return Composition.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnCompositionMetatype2() -> (NSCopying & NSCoding).Protocol { return (NSCopying & NSCoding).self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias NSCodingExistential = NSCoding.Type
@objc func inoutFunc(a: inout Int) {}
// expected-error@-1{{method cannot be marked @objc because inout parameters cannot be represented in Objective-C}}
@objc func metatypeOfExistentialMetatypePram1(a: NSCodingExistential.Protocol) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
@objc func metatypeOfExistentialMetatypePram2(a: NSCoding.Type.Protocol) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
}
func genericContext1<T>(_: T) {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {} // expected-error{{type 'subject_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{type 'subject_inGenericContext2' cannot be nested in generic function 'genericContext1'}}
class subject_constructor_inGenericContext { // expected-error{{type 'subject_constructor_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
init() {} // no-error
}
class subject_var_inGenericContext { // expected-error{{type 'subject_var_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
var subject_instanceVar: Int = 0 // no-error
}
class subject_func_inGenericContext { // expected-error{{type 'subject_func_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
func f() {} // no-error
}
}
class GenericContext2<T> {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {}
@objc
func f() {} // no-error
}
class GenericContext3<T> {
class MoreNested {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{5-11=}}
class subject_inGenericContext {}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{5-11=}}
class subject_inGenericContext2 : Class_ObjC1 {}
@objc
func f() {} // no-error
}
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}}
class ConcreteSubclassOfGeneric : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric {
@objc func foo() {} // okay
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{1-7=}}
class ConcreteSubclassOfGeneric2 : subject_genericClass2<Int> {}
extension ConcreteSubclassOfGeneric2 {
@objc func foo() {} // okay
}
@objc(CustomNameForSubclassOfGeneric) // okay
class ConcreteSubclassOfGeneric3 : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric3 {
@objc func foo() {} // okay
}
class subject_subscriptIndexed1 {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed2 {
@objc
subscript(a: Int8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed3 {
@objc
subscript(a: UInt8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed1 {
@objc
subscript(a: String) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed2 {
@objc
subscript(a: Class_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed3 {
@objc
subscript(a: Class_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed4 {
@objc
subscript(a: Protocol_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed5 {
@objc
subscript(a: Protocol_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed6 {
@objc
subscript(a: Protocol_ObjC1 & Protocol_ObjC2) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed7 {
@objc
subscript(a: (Protocol_ObjC1 & Protocol_ObjC2).Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptBridgedFloat {
@objc
subscript(a: Float32) -> Int {
get { return 0 }
}
}
class subject_subscriptGeneric<T> {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptInvalid2 {
@objc
subscript(a: PlainClass) -> Int {
// expected-error@-1 {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid3 {
@objc
subscript(a: PlainClass.Type) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid4 {
@objc
subscript(a: PlainStruct) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid5 {
@objc
subscript(a: PlainEnum) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{enums cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid6 {
@objc
subscript(a: PlainProtocol) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid7 {
@objc
subscript(a: Protocol_Class1) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid8 {
@objc
subscript(a: Protocol_Class1 & Protocol_Class2) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_propertyInvalid1 {
@objc
let plainStruct = PlainStruct() // expected-error {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
}
//===--- Tests for @objc inference.
@objc
class infer_instanceFunc1 {
// CHECK-LABEL: @objc class infer_instanceFunc1 {
func func1() {}
// CHECK-LABEL: @objc func func1() {
@objc func func1_() {} // no-error
func func2(a: Int) {}
// CHECK-LABEL: @objc func func2(a: Int) {
@objc func func2_(a: Int) {} // no-error
func func3(a: Int) -> Int {}
// CHECK-LABEL: @objc func func3(a: Int) -> Int {
@objc func func3_(a: Int) -> Int {} // no-error
func func4(a: Int, b: Double) {}
// CHECK-LABEL: @objc func func4(a: Int, b: Double) {
@objc func func4_(a: Int, b: Double) {} // no-error
func func5(a: String) {}
// CHECK-LABEL: @objc func func5(a: String) {
@objc func func5_(a: String) {} // no-error
func func6() -> String {}
// CHECK-LABEL: @objc func func6() -> String {
@objc func func6_() -> String {} // no-error
func func7(a: PlainClass) {}
// CHECK-LABEL: {{^}} func func7(a: PlainClass) {
@objc func func7_(a: PlainClass) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func7m(a: PlainClass.Type) {}
// CHECK-LABEL: {{^}} func func7m(a: PlainClass.Type) {
@objc func func7m_(a: PlainClass.Type) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
func func8() -> PlainClass {}
// CHECK-LABEL: {{^}} func func8() -> PlainClass {
@objc func func8_() -> PlainClass {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func8m() -> PlainClass.Type {}
// CHECK-LABEL: {{^}} func func8m() -> PlainClass.Type {
@objc func func8m_() -> PlainClass.Type {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
func func9(a: PlainStruct) {}
// CHECK-LABEL: {{^}} func func9(a: PlainStruct) {
@objc func func9_(a: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func10() -> PlainStruct {}
// CHECK-LABEL: {{^}} func func10() -> PlainStruct {
@objc func func10_() -> PlainStruct {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func11(a: PlainEnum) {}
// CHECK-LABEL: {{^}} func func11(a: PlainEnum) {
@objc func func11_(a: PlainEnum) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
func func12(a: PlainProtocol) {}
// CHECK-LABEL: {{^}} func func12(a: PlainProtocol) {
@objc func func12_(a: PlainProtocol) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
func func13(a: Class_ObjC1) {}
// CHECK-LABEL: @objc func func13(a: Class_ObjC1) {
@objc func func13_(a: Class_ObjC1) {} // no-error
func func14(a: Protocol_Class1) {}
// CHECK-LABEL: {{^}} func func14(a: Protocol_Class1) {
@objc func func14_(a: Protocol_Class1) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
func func15(a: Protocol_ObjC1) {}
// CHECK-LABEL: @objc func func15(a: Protocol_ObjC1) {
@objc func func15_(a: Protocol_ObjC1) {} // no-error
func func16(a: AnyObject) {}
// CHECK-LABEL: @objc func func16(a: AnyObject) {
@objc func func16_(a: AnyObject) {} // no-error
func func17(a: @escaping () -> ()) {}
// CHECK-LABEL: {{^}} @objc func func17(a: @escaping () -> ()) {
@objc func func17_(a: @escaping () -> ()) {}
func func18(a: @escaping (Int) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func18(a: @escaping (Int) -> (), b: Int)
@objc func func18_(a: @escaping (Int) -> (), b: Int) {}
func func19(a: @escaping (String) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func19(a: @escaping (String) -> (), b: Int) {
@objc func func19_(a: @escaping (String) -> (), b: Int) {}
func func_FunctionReturn1() -> () -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn1() -> () -> () {
@objc func func_FunctionReturn1_() -> () -> () {}
func func_FunctionReturn2() -> (Int) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn2() -> (Int) -> () {
@objc func func_FunctionReturn2_() -> (Int) -> () {}
func func_FunctionReturn3() -> () -> Int {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn3() -> () -> Int {
@objc func func_FunctionReturn3_() -> () -> Int {}
func func_FunctionReturn4() -> (String) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn4() -> (String) -> () {
@objc func func_FunctionReturn4_() -> (String) -> () {}
func func_FunctionReturn5() -> () -> String {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn5() -> () -> String {
@objc func func_FunctionReturn5_() -> () -> String {}
func func_ZeroParams1() {}
// CHECK-LABEL: @objc func func_ZeroParams1() {
@objc func func_ZeroParams1a() {} // no-error
func func_OneParam1(a: Int) {}
// CHECK-LABEL: @objc func func_OneParam1(a: Int) {
@objc func func_OneParam1a(a: Int) {} // no-error
func func_TupleStyle1(a: Int, b: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle1(a: Int, b: Int) {
@objc func func_TupleStyle1a(a: Int, b: Int) {}
func func_TupleStyle2(a: Int, b: Int, c: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle2(a: Int, b: Int, c: Int) {
@objc func func_TupleStyle2a(a: Int, b: Int, c: Int) {}
// Check that we produce diagnostics for every parameter and return type.
@objc func func_MultipleDiags(a: PlainStruct, b: PlainEnum) -> Any {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter 1 cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-error@-3 {{method cannot be marked @objc because the type of the parameter 2 cannot be represented in Objective-C}}
// expected-note@-4 {{non-'@objc' enums cannot be represented in Objective-C}}
@objc func func_UnnamedParam1(_: Int) {} // no-error
@objc func func_UnnamedParam2(_: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
@objc func func_varParam1(a: AnyObject) {
var a = a
let b = a; a = b
}
func func_varParam2(a: AnyObject) {
var a = a
let b = a; a = b
}
// CHECK-LABEL: @objc func func_varParam2(a: AnyObject) {
}
@objc
class infer_constructor1 {
// CHECK-LABEL: @objc class infer_constructor1
init() {}
// CHECK: @objc init()
init(a: Int) {}
// CHECK: @objc init(a: Int)
init(a: PlainStruct) {}
// CHECK: {{^}} init(a: PlainStruct)
init(malice: ()) {}
// CHECK: @objc init(malice: ())
init(forMurder _: ()) {}
// CHECK: @objc init(forMurder _: ())
}
@objc
class infer_destructor1 {
// CHECK-LABEL: @objc class infer_destructor1
deinit {}
// CHECK: @objc deinit
}
// @!objc
class infer_destructor2 {
// CHECK-LABEL: {{^}}class infer_destructor2
deinit {}
// CHECK: @objc deinit
}
@objc
class infer_instanceVar1 {
// CHECK-LABEL: @objc class infer_instanceVar1 {
init() {}
var instanceVar1: Int
// CHECK: @objc var instanceVar1: Int
var (instanceVar2, instanceVar3): (Int, PlainProtocol)
// CHECK: @objc var instanceVar2: Int
// CHECK: {{^}} var instanceVar3: PlainProtocol
@objc var (instanceVar1_, instanceVar2_): (Int, PlainProtocol)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var intstanceVar4: Int {
// CHECK: @objc var intstanceVar4: Int {
get {}
// CHECK-NEXT: @objc get {}
}
var intstanceVar5: Int {
// CHECK: @objc var intstanceVar5: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
@objc var instanceVar5_: Int {
// CHECK: @objc var instanceVar5_: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
var observingAccessorsVar1: Int {
// CHECK: @objc @_hasStorage var observingAccessorsVar1: Int {
willSet {}
// CHECK-NEXT: {{^}} @objc get
didSet {}
// CHECK-NEXT: {{^}} @objc set
}
@objc var observingAccessorsVar1_: Int {
// CHECK: {{^}} @objc @_hasStorage var observingAccessorsVar1_: Int {
willSet {}
// CHECK-NEXT: {{^}} @objc get
didSet {}
// CHECK-NEXT: {{^}} @objc set
}
var var_Int: Int
// CHECK-LABEL: @objc var var_Int: Int
var var_Bool: Bool
// CHECK-LABEL: @objc var var_Bool: Bool
var var_CBool: CBool
// CHECK-LABEL: @objc var var_CBool: CBool
var var_String: String
// CHECK-LABEL: @objc var var_String: String
var var_Float: Float
var var_Double: Double
// CHECK-LABEL: @objc var var_Float: Float
// CHECK-LABEL: @objc var var_Double: Double
var var_Char: Unicode.Scalar
// CHECK-LABEL: @objc var var_Char: Unicode.Scalar
//===--- Tuples.
var var_tuple1: ()
// CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple1: ()
@objc var var_tuple1_: ()
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple2: Void
// CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple2: Void
@objc var var_tuple2_: Void
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple3: (Int)
// CHECK-LABEL: @objc var var_tuple3: (Int)
@objc var var_tuple3_: (Int) // no-error
var var_tuple4: (Int, Int)
// CHECK-LABEL: {{^}} var var_tuple4: (Int, Int)
@objc var var_tuple4_: (Int, Int)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{tuples cannot be represented in Objective-C}}
//===--- Stdlib integer types.
var var_Int8: Int8
var var_Int16: Int16
var var_Int32: Int32
var var_Int64: Int64
// CHECK-LABEL: @objc var var_Int8: Int8
// CHECK-LABEL: @objc var var_Int16: Int16
// CHECK-LABEL: @objc var var_Int32: Int32
// CHECK-LABEL: @objc var var_Int64: Int64
var var_UInt8: UInt8
var var_UInt16: UInt16
var var_UInt32: UInt32
var var_UInt64: UInt64
// CHECK-LABEL: @objc var var_UInt8: UInt8
// CHECK-LABEL: @objc var var_UInt16: UInt16
// CHECK-LABEL: @objc var var_UInt32: UInt32
// CHECK-LABEL: @objc var var_UInt64: UInt64
var var_OpaquePointer: OpaquePointer
// CHECK-LABEL: @objc var var_OpaquePointer: OpaquePointer
var var_PlainClass: PlainClass
// CHECK-LABEL: {{^}} var var_PlainClass: PlainClass
@objc var var_PlainClass_: PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
var var_PlainStruct: PlainStruct
// CHECK-LABEL: {{^}} var var_PlainStruct: PlainStruct
@objc var var_PlainStruct_: PlainStruct
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
var var_PlainEnum: PlainEnum
// CHECK-LABEL: {{^}} var var_PlainEnum: PlainEnum
@objc var var_PlainEnum_: PlainEnum
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
var var_PlainProtocol: PlainProtocol
// CHECK-LABEL: {{^}} var var_PlainProtocol: PlainProtocol
@objc var var_PlainProtocol_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_ClassObjC: Class_ObjC1
// CHECK-LABEL: @objc var var_ClassObjC: Class_ObjC1
@objc var var_ClassObjC_: Class_ObjC1 // no-error
var var_ProtocolClass: Protocol_Class1
// CHECK-LABEL: {{^}} var var_ProtocolClass: Protocol_Class1
@objc var var_ProtocolClass_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_ProtocolObjC: Protocol_ObjC1
// CHECK-LABEL: @objc var var_ProtocolObjC: Protocol_ObjC1
@objc var var_ProtocolObjC_: Protocol_ObjC1 // no-error
var var_PlainClassMetatype: PlainClass.Type
// CHECK-LABEL: {{^}} var var_PlainClassMetatype: PlainClass.Type
@objc var var_PlainClassMetatype_: PlainClass.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainStructMetatype: PlainStruct.Type
// CHECK-LABEL: {{^}} var var_PlainStructMetatype: PlainStruct.Type
@objc var var_PlainStructMetatype_: PlainStruct.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainEnumMetatype: PlainEnum.Type
// CHECK-LABEL: {{^}} var var_PlainEnumMetatype: PlainEnum.Type
@objc var var_PlainEnumMetatype_: PlainEnum.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainExistentialMetatype: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_PlainExistentialMetatype: PlainProtocol.Type
@objc var var_PlainExistentialMetatype_: PlainProtocol.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ClassObjCMetatype: Class_ObjC1.Type
// CHECK-LABEL: @objc var var_ClassObjCMetatype: Class_ObjC1.Type
@objc var var_ClassObjCMetatype_: Class_ObjC1.Type // no-error
var var_ProtocolClassMetatype: Protocol_Class1.Type
// CHECK-LABEL: {{^}} var var_ProtocolClassMetatype: Protocol_Class1.Type
@objc var var_ProtocolClassMetatype_: Protocol_Class1.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
@objc var var_ProtocolObjCMetatype1_: Protocol_ObjC1.Type // no-error
var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
@objc var var_ProtocolObjCMetatype2_: Protocol_ObjC2.Type // no-error
var var_AnyObject1: AnyObject
var var_AnyObject2: AnyObject.Type
// CHECK-LABEL: @objc var var_AnyObject1: AnyObject
// CHECK-LABEL: @objc var var_AnyObject2: AnyObject.Type
var var_Existential0: Any
// CHECK-LABEL: @objc var var_Existential0: Any
@objc var var_Existential0_: Any
var var_Existential1: PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential1: PlainProtocol
@objc var var_Existential1_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential2: PlainProtocol & PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential2: PlainProtocol
@objc var var_Existential2_: PlainProtocol & PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential3: PlainProtocol & Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential3: PlainProtocol & Protocol_Class1
@objc var var_Existential3_: PlainProtocol & Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential4: PlainProtocol & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential4: PlainProtocol & Protocol_ObjC1
@objc var var_Existential4_: PlainProtocol & Protocol_ObjC1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential5: Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential5: Protocol_Class1
@objc var var_Existential5_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential6: Protocol_Class1 & Protocol_Class2
// CHECK-LABEL: {{^}} var var_Existential6: Protocol_Class1 & Protocol_Class2
@objc var var_Existential6_: Protocol_Class1 & Protocol_Class2
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential7: Protocol_Class1 & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential7: Protocol_Class1 & Protocol_ObjC1
@objc var var_Existential7_: Protocol_Class1 & Protocol_ObjC1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential8: Protocol_ObjC1
// CHECK-LABEL: @objc var var_Existential8: Protocol_ObjC1
@objc var var_Existential8_: Protocol_ObjC1 // no-error
var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
@objc var var_Existential9_: Protocol_ObjC1 & Protocol_ObjC2 // no-error
var var_ExistentialMetatype0: Any.Type
var var_ExistentialMetatype1: PlainProtocol.Type
var var_ExistentialMetatype2: (PlainProtocol & PlainProtocol).Type
var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
var var_ExistentialMetatype5: (Protocol_Class1).Type
var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
var var_ExistentialMetatype8: Protocol_ObjC1.Type
var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype0: Any.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype1: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype2: (PlainProtocol).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype5: (Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
// CHECK-LABEL: @objc var var_ExistentialMetatype8: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
// CHECK-LABEL: var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
var var_Optional1: Class_ObjC1?
var var_Optional2: Protocol_ObjC1?
var var_Optional3: Class_ObjC1.Type?
var var_Optional4: Protocol_ObjC1.Type?
var var_Optional5: AnyObject?
var var_Optional6: AnyObject.Type?
var var_Optional7: String?
var var_Optional8: Protocol_ObjC1?
var var_Optional9: Protocol_ObjC1.Type?
var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
var var_Optional12: OpaquePointer?
var var_Optional13: UnsafeMutablePointer<Int>?
var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional1: Class_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional2: Protocol_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional3: Class_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional4: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional5: AnyObject?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional6: AnyObject.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional7: String?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional8: Protocol_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional9: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional12: OpaquePointer?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional13: UnsafeMutablePointer<Int>?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional5: AnyObject!
var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
var var_ImplicitlyUnwrappedOptional7: String!
var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional5: AnyObject!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional7: String!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
var var_Optional_fail1: PlainClass?
var var_Optional_fail2: PlainClass.Type?
var var_Optional_fail3: PlainClass!
var var_Optional_fail4: PlainStruct?
var var_Optional_fail5: PlainStruct.Type?
var var_Optional_fail6: PlainEnum?
var var_Optional_fail7: PlainEnum.Type?
var var_Optional_fail8: PlainProtocol?
var var_Optional_fail10: PlainProtocol?
var var_Optional_fail11: (PlainProtocol & Protocol_ObjC1)?
var var_Optional_fail12: Int?
var var_Optional_fail13: Bool?
var var_Optional_fail14: CBool?
var var_Optional_fail20: AnyObject??
var var_Optional_fail21: AnyObject.Type??
var var_Optional_fail22: ComparisonResult? // a non-bridged imported value type
var var_Optional_fail23: NSRange? // a bridged struct imported from C
// CHECK-NOT: @objc{{.*}}Optional_fail
// CHECK-LABEL: @objc var var_CFunctionPointer_1: @convention(c) () -> ()
var var_CFunctionPointer_1: @convention(c) () -> ()
// CHECK-LABEL: @objc var var_CFunctionPointer_invalid_1: Int
var var_CFunctionPointer_invalid_1: @convention(c) Int // expected-error {{@convention attribute only applies to function types}}
// CHECK-LABEL: {{^}} var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int
var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int // expected-error {{'(PlainStruct) -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
// <rdar://problem/20918869> Confusing diagnostic for @convention(c) throws
var var_CFunctionPointer_invalid_3 : @convention(c) (Int) throws -> Int // expected-error {{'(Int) throws -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
weak var var_Weak1: Class_ObjC1?
weak var var_Weak2: Protocol_ObjC1?
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//weak var var_Weak3: Class_ObjC1.Type?
//weak var var_Weak4: Protocol_ObjC1.Type?
weak var var_Weak5: AnyObject?
//weak var var_Weak6: AnyObject.Type?
weak var var_Weak7: Protocol_ObjC1?
weak var var_Weak8: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak1: @sil_weak Class_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak2: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak5: @sil_weak AnyObject
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak7: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak8: @sil_weak (Protocol_ObjC1 & Protocol_ObjC2)?
weak var var_Weak_fail1: PlainClass?
weak var var_Weak_bad2: PlainStruct?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
weak var var_Weak_bad3: PlainEnum?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
weak var var_Weak_bad4: String?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Weak_fail
unowned var var_Unowned1: Class_ObjC1
unowned var var_Unowned2: Protocol_ObjC1
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//unowned var var_Unowned3: Class_ObjC1.Type
//unowned var var_Unowned4: Protocol_ObjC1.Type
unowned var var_Unowned5: AnyObject
//unowned var var_Unowned6: AnyObject.Type
unowned var var_Unowned7: Protocol_ObjC1
unowned var var_Unowned8: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc unowned var var_Unowned1: @sil_unowned Class_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned2: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned5: @sil_unowned AnyObject
// CHECK-LABEL: @objc unowned var var_Unowned7: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned8: @sil_unowned Protocol_ObjC1 & Protocol_ObjC2
unowned var var_Unowned_fail1: PlainClass
unowned var var_Unowned_bad2: PlainStruct
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
unowned var var_Unowned_bad3: PlainEnum
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
unowned var var_Unowned_bad4: String
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Unowned_fail
var var_FunctionType1: () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType1: () -> ()
var var_FunctionType2: (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType2: (Int) -> ()
var var_FunctionType3: (Int) -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionType3: (Int) -> Int
var var_FunctionType4: (Int, Double) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType4: (Int, Double) -> ()
var var_FunctionType5: (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType5: (String) -> ()
var var_FunctionType6: () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionType6: () -> String
var var_FunctionType7: (PlainClass) -> ()
// CHECK-NOT: @objc var var_FunctionType7: (PlainClass) -> ()
var var_FunctionType8: () -> PlainClass
// CHECK-NOT: @objc var var_FunctionType8: () -> PlainClass
var var_FunctionType9: (PlainStruct) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType9: (PlainStruct) -> ()
var var_FunctionType10: () -> PlainStruct
// CHECK-LABEL: {{^}} var var_FunctionType10: () -> PlainStruct
var var_FunctionType11: (PlainEnum) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType11: (PlainEnum) -> ()
var var_FunctionType12: (PlainProtocol) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType12: (PlainProtocol) -> ()
var var_FunctionType13: (Class_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType13: (Class_ObjC1) -> ()
var var_FunctionType14: (Protocol_Class1) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType14: (Protocol_Class1) -> ()
var var_FunctionType15: (Protocol_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType15: (Protocol_ObjC1) -> ()
var var_FunctionType16: (AnyObject) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType16: (AnyObject) -> ()
var var_FunctionType17: (() -> ()) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType17: (() -> ()) -> ()
var var_FunctionType18: ((Int) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType18: ((Int) -> (), Int) -> ()
var var_FunctionType19: ((String) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType19: ((String) -> (), Int) -> ()
var var_FunctionTypeReturn1: () -> () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn1: () -> () -> ()
@objc var var_FunctionTypeReturn1_: () -> () -> () // no-error
var var_FunctionTypeReturn2: () -> (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn2: () -> (Int) -> ()
@objc var var_FunctionTypeReturn2_: () -> (Int) -> () // no-error
var var_FunctionTypeReturn3: () -> () -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn3: () -> () -> Int
@objc var var_FunctionTypeReturn3_: () -> () -> Int // no-error
var var_FunctionTypeReturn4: () -> (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn4: () -> (String) -> ()
@objc var var_FunctionTypeReturn4_: () -> (String) -> () // no-error
var var_FunctionTypeReturn5: () -> () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn5: () -> () -> String
@objc var var_FunctionTypeReturn5_: () -> () -> String // no-error
var var_BlockFunctionType1: @convention(block) () -> ()
// CHECK-LABEL: @objc var var_BlockFunctionType1: @convention(block) () -> ()
@objc var var_BlockFunctionType1_: @convention(block) () -> () // no-error
var var_ArrayType1: [AnyObject]
// CHECK-LABEL: {{^}} @objc var var_ArrayType1: [AnyObject]
@objc var var_ArrayType1_: [AnyObject] // no-error
var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject]
@objc var var_ArrayType2_: [@convention(block) (AnyObject) -> AnyObject] // no-error
var var_ArrayType3: [PlainStruct]
// CHECK-LABEL: {{^}} var var_ArrayType3: [PlainStruct]
@objc var var_ArrayType3_: [PlainStruct]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType4: [(AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType4: [(AnyObject) -> AnyObject]
@objc var var_ArrayType4_: [(AnyObject) -> AnyObject]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType5: [Protocol_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType5: [Protocol_ObjC1]
@objc var var_ArrayType5_: [Protocol_ObjC1] // no-error
var var_ArrayType6: [Class_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType6: [Class_ObjC1]
@objc var var_ArrayType6_: [Class_ObjC1] // no-error
var var_ArrayType7: [PlainClass]
// CHECK-LABEL: {{^}} var var_ArrayType7: [PlainClass]
@objc var var_ArrayType7_: [PlainClass]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType8: [PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType8: [PlainProtocol]
@objc var var_ArrayType8_: [PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType9: [Protocol_ObjC1 & PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType9: [PlainProtocol & Protocol_ObjC1]
@objc var var_ArrayType9_: [Protocol_ObjC1 & PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
// CHECK-LABEL: {{^}} @objc var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
@objc var var_ArrayType10_: [Protocol_ObjC1 & Protocol_ObjC2]
// no-error
var var_ArrayType11: [Any]
// CHECK-LABEL: @objc var var_ArrayType11: [Any]
@objc var var_ArrayType11_: [Any]
var var_ArrayType13: [Any?]
// CHECK-LABEL: {{^}} var var_ArrayType13: [Any?]
@objc var var_ArrayType13_: [Any?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType15: [AnyObject?]
// CHECK-LABEL: {{^}} var var_ArrayType15: [AnyObject?]
@objc var var_ArrayType15_: [AnyObject?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType16: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType16: {{\[}}[@convention(block) (AnyObject) -> AnyObject]]
@objc var var_ArrayType16_: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
var var_ArrayType17: [[(AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType17: {{\[}}[(AnyObject) -> AnyObject]]
@objc var var_ArrayType17_: [[(AnyObject) -> AnyObject]]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
}
@objc
class ObjCBase {}
class infer_instanceVar2<
GP_Unconstrained,
GP_PlainClass : PlainClass,
GP_PlainProtocol : PlainProtocol,
GP_Class_ObjC : Class_ObjC1,
GP_Protocol_Class : Protocol_Class1,
GP_Protocol_ObjC : Protocol_ObjC1> : ObjCBase {
// CHECK-LABEL: class infer_instanceVar2<{{.*}}> : ObjCBase where {{.*}} {
override init() {}
var var_GP_Unconstrained: GP_Unconstrained
// CHECK-LABEL: {{^}} var var_GP_Unconstrained: GP_Unconstrained
@objc var var_GP_Unconstrained_: GP_Unconstrained
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainClass: GP_PlainClass
// CHECK-LABEL: {{^}} var var_GP_PlainClass: GP_PlainClass
@objc var var_GP_PlainClass_: GP_PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainProtocol: GP_PlainProtocol
// CHECK-LABEL: {{^}} var var_GP_PlainProtocol: GP_PlainProtocol
@objc var var_GP_PlainProtocol_: GP_PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Class_ObjC: GP_Class_ObjC
// CHECK-LABEL: {{^}} var var_GP_Class_ObjC: GP_Class_ObjC
@objc var var_GP_Class_ObjC_: GP_Class_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_Class: GP_Protocol_Class
// CHECK-LABEL: {{^}} var var_GP_Protocol_Class: GP_Protocol_Class
@objc var var_GP_Protocol_Class_: GP_Protocol_Class
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_ObjC: GP_Protocol_ObjC
// CHECK-LABEL: {{^}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC
@objc var var_GP_Protocol_ObjCa: GP_Protocol_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
func func_GP_Unconstrained(a: GP_Unconstrained) {}
// CHECK-LABEL: {{^}} func func_GP_Unconstrained(a: GP_Unconstrained) {
@objc func func_GP_Unconstrained_(a: GP_Unconstrained) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
@objc func func_GP_Unconstrained_() -> GP_Unconstrained {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
@objc func func_GP_Class_ObjC__() -> GP_Class_ObjC {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
}
class infer_instanceVar3 : Class_ObjC1 {
// CHECK-LABEL: @objc class infer_instanceVar3 : Class_ObjC1 {
var v1: Int = 0
// CHECK-LABEL: @objc @_hasInitialValue var v1: Int
}
@objc
protocol infer_instanceVar4 {
// CHECK-LABEL: @objc protocol infer_instanceVar4 {
var v1: Int { get }
// CHECK-LABEL: @objc var v1: Int { get }
}
// @!objc
class infer_instanceVar5 {
// CHECK-LABEL: {{^}}class infer_instanceVar5 {
@objc
var intstanceVar1: Int {
// CHECK: @objc var intstanceVar1: Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
class infer_staticVar1 {
// CHECK-LABEL: @objc class infer_staticVar1 {
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
// CHECK: @objc @_hasInitialValue class var staticVar1: Int
}
// @!objc
class infer_subscript1 {
// CHECK-LABEL: class infer_subscript1
@objc
subscript(i: Int) -> Int {
// CHECK: @objc subscript(i: Int) -> Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
protocol infer_throughConformanceProto1 {
// CHECK-LABEL: @objc protocol infer_throughConformanceProto1 {
func funcObjC1()
var varObjC1: Int { get }
var varObjC2: Int { get set }
// CHECK: @objc func funcObjC1()
// CHECK: @objc var varObjC1: Int { get }
// CHECK: @objc var varObjC2: Int { get set }
}
class infer_class1 : PlainClass {}
// CHECK-LABEL: {{^}}class infer_class1 : PlainClass {
class infer_class2 : Class_ObjC1 {}
// CHECK-LABEL: @objc class infer_class2 : Class_ObjC1 {
class infer_class3 : infer_class2 {}
// CHECK-LABEL: @objc class infer_class3 : infer_class2 {
class infer_class4 : Protocol_Class1 {}
// CHECK-LABEL: {{^}}class infer_class4 : Protocol_Class1 {
class infer_class5 : Protocol_ObjC1 {}
// CHECK-LABEL: {{^}}class infer_class5 : Protocol_ObjC1 {
//
// If a protocol conforms to an @objc protocol, this does not infer @objc on
// the protocol itself, or on the newly introduced requirements. Only the
// inherited @objc requirements get @objc.
//
// Same rule applies to classes.
//
protocol infer_protocol1 {
// CHECK-LABEL: {{^}}protocol infer_protocol1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol2 : Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol2 : Protocol_Class1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol3 : Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol3 : Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol5 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
class C {
// Don't crash.
@objc func foo(x: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}}
@IBAction func myAction(sender: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}}
}
//===---
//===--- @IBOutlet implies @objc
//===---
class HasIBOutlet {
// CHECK-LABEL: {{^}}class HasIBOutlet {
init() {}
@IBOutlet weak var goodOutlet: Class_ObjC1!
// CHECK-LABEL: {{^}} @objc @IBOutlet @_implicitly_unwrapped_optional @_hasInitialValue weak var goodOutlet: @sil_weak Class_ObjC1!
@IBOutlet var badOutlet: PlainStruct
// expected-error@-1 {{@IBOutlet property cannot have non-object type 'PlainStruct'}} {{3-13=}}
// expected-error@-2 {{@IBOutlet property has non-optional type 'PlainStruct'}}
// expected-note@-3 {{add '?' to form the optional type 'PlainStruct?'}}
// expected-note@-4 {{add '!' to form an implicitly unwrapped optional}}
// CHECK-LABEL: {{^}} @IBOutlet var badOutlet: PlainStruct
}
//===---
//===--- @IBAction implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBAction {
class HasIBAction {
@IBAction func goodAction(_ sender: AnyObject?) { }
// CHECK: {{^}} @objc @IBAction func goodAction(_ sender: AnyObject?) {
@IBAction func badAction(_ sender: PlainStruct?) { }
// expected-error@-1{{argument to @IBAction method cannot have non-object type 'PlainStruct?'}}
}
//===---
//===--- @IBInspectable implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBInspectable {
class HasIBInspectable {
@IBInspectable var goodProperty: AnyObject?
// CHECK: {{^}} @objc @IBInspectable @_hasInitialValue var goodProperty: AnyObject?
}
//===---
//===--- @GKInspectable implies @objc
//===---
// CHECK-LABEL: {{^}}class HasGKInspectable {
class HasGKInspectable {
@GKInspectable var goodProperty: AnyObject?
// CHECK: {{^}} @objc @GKInspectable @_hasInitialValue var goodProperty: AnyObject?
}
//===---
//===--- @NSManaged implies @objc
//===---
class HasNSManaged {
// CHECK-LABEL: {{^}}class HasNSManaged {
init() {}
@NSManaged
var goodManaged: Class_ObjC1
// CHECK-LABEL: {{^}} @objc @NSManaged dynamic var goodManaged: Class_ObjC1 {
// CHECK-NEXT: {{^}} @objc get
// CHECK-NEXT: {{^}} @objc set
// CHECK-NEXT: {{^}} }
@NSManaged
var badManaged: PlainStruct
// expected-error@-1 {{property cannot be marked @NSManaged because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-error@-3{{'dynamic' property 'badManaged' must also be '@objc'}}
// CHECK-LABEL: {{^}} @NSManaged var badManaged: PlainStruct {
// CHECK-NEXT: {{^}} get
// CHECK-NEXT: {{^}} set
// CHECK-NEXT: {{^}} }
}
//===---
//===--- Pointer argument types
//===---
@objc class TakesCPointers {
// CHECK-LABEL: {{^}}@objc class TakesCPointers {
func constUnsafeMutablePointer(p: UnsafePointer<Int>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointer(p: UnsafePointer<Int>) {
func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {
func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {
func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {}
// CHECK-LABEL: @objc func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {
func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {
func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {
}
// @objc with nullary names
@objc(NSObjC2)
class Class_ObjC2 {
// CHECK-LABEL: @objc(NSObjC2) class Class_ObjC2
@objc(initWithMalice)
init(foo: ()) { }
@objc(initWithIntent)
init(bar _: ()) { }
@objc(initForMurder)
init() { }
@objc(isFoo)
func foo() -> Bool {}
// CHECK-LABEL: @objc(isFoo) func foo() -> Bool {
}
@objc() // expected-error{{expected name within parentheses of @objc attribute}}
class Class_ObjC3 {
}
// @objc with selector names
extension PlainClass {
// CHECK-LABEL: @objc(setFoo:) dynamic func
@objc(setFoo:)
func foo(b: Bool) { }
// CHECK-LABEL: @objc(setWithRed:green:blue:alpha:) dynamic func set
@objc(setWithRed:green:blue:alpha:)
func set(_: Float, green: Float, blue: Float, alpha: Float) { }
// CHECK-LABEL: @objc(createWithRed:green:blue:alpha:) dynamic class func createWith
@objc(createWithRed:green blue:alpha)
class func createWithRed(_: Float, green: Float, blue: Float, alpha: Float) { }
// expected-error@-2{{missing ':' after selector piece in @objc attribute}}{{28-28=:}}
// expected-error@-3{{missing ':' after selector piece in @objc attribute}}{{39-39=:}}
// CHECK-LABEL: @objc(::) dynamic func badlyNamed
@objc(::)
func badlyNamed(_: Int, y: Int) {}
}
@objc(Class:) // expected-error{{'@objc' class must have a simple name}}{{12-13=}}
class BadClass1 { }
@objc(Protocol:) // expected-error{{'@objc' protocol must have a simple name}}{{15-16=}}
protocol BadProto1 { }
@objc(Enum:) // expected-error{{'@objc' enum must have a simple name}}{{11-12=}}
enum BadEnum1: Int { case X }
@objc
enum BadEnum2: Int {
@objc(X:) // expected-error{{'@objc' enum case must have a simple name}}{{10-11=}}
case X
}
class BadClass2 {
@objc(realDealloc) // expected-error{{'@objc' deinitializer cannot have a name}}
deinit { }
@objc(badprop:foo:wibble:) // expected-error{{'@objc' property must have a simple name}}{{16-28=}}
var badprop: Int = 5
@objc(foo) // expected-error{{'@objc' subscript cannot have a name; did you mean to put the name on the getter or setter?}}
subscript (i: Int) -> Int {
get {
return i
}
}
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam(x: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam2(_: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters}}
func noArgNamesTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 2 parameters}}
func oneArgNameTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 0 parameters}}
func oneArgNameNoParams() { }
@objc(foo:) // expected-error{{'@objc' initializer name provides one argument name, but initializer has 0 parameters}}
init() { }
var _prop = 5
@objc var prop: Int {
@objc(property) get { return _prop }
@objc(setProperty:) set { _prop = newValue }
}
var prop2: Int {
@objc(property) get { return _prop } // expected-error{{'@objc' getter for non-'@objc' property}}
@objc(setProperty:) set { _prop = newValue } // expected-error{{'@objc' setter for non-'@objc' property}}
}
var prop3: Int {
@objc(setProperty:) didSet { } // expected-error{{observing accessors are not allowed to be marked @objc}} {{5-25=}}
}
@objc
subscript (c: Class_ObjC1) -> Class_ObjC1 {
@objc(getAtClass:) get {
return c
}
@objc(setAtClass:class:) set {
}
}
}
// Swift overrides that aren't also @objc overrides.
class Super {
@objc(renamedFoo)
var foo: Int { get { return 3 } } // expected-note 2{{overridden declaration is here}}
@objc func process(i: Int) -> Int { } // expected-note {{overriding '@objc' method 'process(i:)' here}}
}
class Sub1 : Super {
@objc(foo) // expected-error{{Objective-C property has a different name from the property it overrides ('foo' vs. 'renamedFoo')}}{{9-12=renamedFoo}}
override var foo: Int { get { return 5 } }
override func process(i: Int?) -> Int { } // expected-error{{method cannot be an @objc override because the type of the parameter cannot be represented in Objective-C}}
}
class Sub2 : Super {
@objc
override var foo: Int { get { return 5 } }
}
class Sub3 : Super {
override var foo: Int { get { return 5 } }
}
class Sub4 : Super {
@objc(renamedFoo)
override var foo: Int { get { return 5 } }
}
class Sub5 : Super {
@objc(wrongFoo) // expected-error{{Objective-C property has a different name from the property it overrides ('wrongFoo' vs. 'renamedFoo')}} {{9-17=renamedFoo}}
override var foo: Int { get { return 5 } }
}
enum NotObjCEnum { case X }
struct NotObjCStruct {}
// Closure arguments can only be @objc if their parameters and returns are.
// CHECK-LABEL: @objc class ClosureArguments
@objc class ClosureArguments {
// CHECK: @objc func foo
@objc func foo(f: (Int) -> ()) {}
// CHECK: @objc func bar
@objc func bar(f: (NotObjCEnum) -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func bas
@objc func bas(f: (NotObjCEnum) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zim
@objc func zim(f: () -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zang
@objc func zang(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
@objc func zangZang(f: (Int...) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func fooImplicit
func fooImplicit(f: (Int) -> ()) {}
// CHECK: {{^}} func barImplicit
func barImplicit(f: (NotObjCEnum) -> NotObjCStruct) {}
// CHECK: {{^}} func basImplicit
func basImplicit(f: (NotObjCEnum) -> ()) {}
// CHECK: {{^}} func zimImplicit
func zimImplicit(f: () -> NotObjCStruct) {}
// CHECK: {{^}} func zangImplicit
func zangImplicit(f: (NotObjCEnum, NotObjCStruct) -> ()) {}
// CHECK: {{^}} func zangZangImplicit
func zangZangImplicit(f: (Int...) -> ()) {}
}
typealias GoodBlock = @convention(block) (Int) -> ()
typealias BadBlock = @convention(block) (NotObjCEnum) -> () // expected-error{{'(NotObjCEnum) -> ()' is not representable in Objective-C, so it cannot be used with '@convention(block)'}}
@objc class AccessControl {
// CHECK: @objc func foo
func foo() {}
// CHECK: {{^}} private func bar
private func bar() {}
// CHECK: @objc private func baz
@objc private func baz() {}
}
//===--- Ban @objc +load methods
class Load1 {
// Okay: not @objc
class func load() { }
class func alloc() {}
class func allocWithZone(_: Int) {}
class func initialize() {}
}
@objc class Load2 {
class func load() { } // expected-error{{method 'load()' defines Objective-C class method 'load', which is not permitted by Swift}}
class func alloc() {} // expected-error{{method 'alloc()' defines Objective-C class method 'alloc', which is not permitted by Swift}}
class func allocWithZone(_: Int) {} // expected-error{{method 'allocWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
class func initialize() {} // expected-error{{method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}}
}
@objc class Load3 {
class var load: Load3 {
get { return Load3() } // expected-error{{getter for 'load' defines Objective-C class method 'load', which is not permitted by Swift}}
set { }
}
@objc(alloc) class var prop: Int { return 0 } // expected-error{{getter for 'prop' defines Objective-C class method 'alloc', which is not permitted by Swift}}
@objc(allocWithZone:) class func fooWithZone(_: Int) {} // expected-error{{method 'fooWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
@objc(initialize) class func barnitialize() {} // expected-error{{method 'barnitialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}}
}
// Members of protocol extensions cannot be @objc
extension PlainProtocol {
@objc var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
@objc var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
// Don't infer @objc for extensions of @objc protocols.
// CHECK: {{^}} var propertyOK: Int
var propertyOK: Int { return 5 }
}
//===---
//===--- Error handling
//===---
class ClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
@objc func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
@objc func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
@objc func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
@objc func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: @objc init(degrees: Double) throws
@objc init(degrees: Double) throws { }
// Errors
@objc func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type 'Class_ObjC1?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsOptionalArray() throws -> [String]? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type '[String]?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsInt() throws -> Int { return 0 } // expected-error{{throwing method cannot be marked @objc because it returns a value of type 'Int'; return 'Void' or a type that bridges to an Objective-C class}}
@objc func methodAcceptsThrowingFunc(fn: (String) throws -> Int) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{throwing function types cannot be represented in Objective-C}}
@objc init?(radians: Double) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc init!(string: String) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc func fooWithErrorEnum1(x: ErrorEnum) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{non-'@objc' enums cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorEnum2(x: ErrorEnum)
func fooWithErrorEnum2(x: ErrorEnum) {}
@objc func fooWithErrorProtocolComposition1(x: Error & Protocol_ObjC1) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{protocol-constrained type containing 'Error' cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1)
func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1) { }
}
// CHECK-DUMP-LABEL: class_decl{{.*}}"ImplicitClassThrows1"
@objc class ImplicitClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
// CHECK-DUMP: func_decl{{.*}}"methodReturnsVoid()"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
// CHECK-DUMP: func_decl{{.*}}"methodReturnsObjCClass()" {{.*}}foreign_error=NilResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: {{^}} func methodReturnsOptionalObjCClass() throws -> Class_ObjC1?
func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil }
// CHECK: @objc func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int)
// CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int) throws { }
// CHECK: @objc init(degrees: Double) throws
// CHECK-DUMP: constructor_decl{{.*}}"init(degrees:)"{{.*}}foreign_error=NilResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
init(degrees: Double) throws { }
// CHECK: {{^}} func methodReturnsBridgedValueType() throws -> NSRange
func methodReturnsBridgedValueType() throws -> NSRange { return NSRange() }
@objc func methodReturnsBridgedValueType2() throws -> NSRange {
return NSRange()
}
// expected-error@-3{{throwing method cannot be marked @objc because it returns a value of type 'NSRange' (aka '_NSRange'); return 'Void' or a type that bridges to an Objective-C class}}
// CHECK: {{^}} @objc func methodReturnsError() throws -> Error
func methodReturnsError() throws -> Error { return ErrorEnum.failed }
// CHECK: @objc func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int)
func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int) {
func add(x: Int) -> (Int) -> Int {
return { x + $0 }
}
}
}
// CHECK-DUMP-LABEL: class_decl{{.*}}"SubclassImplicitClassThrows1"
@objc class SubclassImplicitClassThrows1 : ImplicitClassThrows1 {
// CHECK: @objc override func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping ((Int) -> Int), fn3: @escaping ((Int) -> Int))
// CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: (@escaping (Int) -> Int), fn3: (@escaping (Int) -> Int)) throws { }
}
class ThrowsRedecl1 {
@objc func method1(_ x: Int, error: Class_ObjC1) { } // expected-note{{declared here}}
@objc func method1(_ x: Int) throws { } // expected-error{{with Objective-C selector 'method1:error:'}}
@objc func method2AndReturnError(_ x: Int) { } // expected-note{{declared here}}
@objc func method2() throws { } // expected-error{{with Objective-C selector 'method2AndReturnError:'}}
@objc func method3(_ x: Int, error: Int, closure: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc func method3(_ x: Int, closure: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'method3:error:closure:'}}
@objc(initAndReturnError:) func initMethod1(error: Int) { } // expected-note{{declared here}}
@objc init() throws { } // expected-error{{with Objective-C selector 'initAndReturnError:'}}
@objc(initWithString:error:) func initMethod2(string: String, error: Int) { } // expected-note{{declared here}}
@objc init(string: String) throws { } // expected-error{{with Objective-C selector 'initWithString:error:'}}
@objc(initAndReturnError:fn:) func initMethod3(error: Int, fn: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc init(fn: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'initAndReturnError:fn:'}}
}
class ThrowsObjCName {
@objc(method4:closure:error:) func method4(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method5AndReturnError:x:closure:) func method5(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method6) func method6() throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has one parameter (the error parameter)}}
@objc(method7) func method7(x: Int) throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has 2 parameters (including the error parameter)}}
// CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method8:fn1:error:fn2:)
func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method9AndReturnError:s:fn1:fn2:)
func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
class SubclassThrowsObjCName : ThrowsObjCName {
// CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
@objc protocol ProtocolThrowsObjCName {
@objc optional func doThing(_ x: String) throws -> String // expected-note{{requirement 'doThing' declared here}}
}
class ConformsToProtocolThrowsObjCName1 : ProtocolThrowsObjCName {
@objc func doThing(_ x: String) throws -> String { return x } // okay
}
class ConformsToProtocolThrowsObjCName2 : ProtocolThrowsObjCName {
@objc func doThing(_ x: Int) throws -> String { return "" }
// expected-warning@-1{{instance method 'doThing' nearly matches optional requirement 'doThing' of protocol 'ProtocolThrowsObjCName'}}
// expected-note@-2{{move 'doThing' to an extension to silence this warning}}
// expected-note@-3{{make 'doThing' private to silence this warning}}{{9-9=private }}
// expected-note@-4{{candidate has non-matching type '(Int) throws -> String'}}
}
@objc class DictionaryTest {
// CHECK-LABEL: @objc func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>)
func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
// CHECK-LABEL: @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>)
@objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
func func_dictionary2a(x: Dictionary<String, Int>) { }
@objc func func_dictionary2b(x: Dictionary<String, Int>) { }
}
@objc extension PlainClass {
// CHECK-LABEL: @objc final func objc_ext_objc_okay(_: Int) {
final func objc_ext_objc_okay(_: Int) { }
final func objc_ext_objc_not_okay(_: PlainStruct) { }
// expected-error@-1{{method cannot be in an @objc extension of a class (without @nonobjc) because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// CHECK-LABEL: {{^}} @nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) {
@nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) { }
}
@objc class ObjC_Class1 : Hashable {
func hash(into hasher: inout Hasher) {}
}
func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool {
return true
}
// CHECK-LABEL: @objc class OperatorInClass
@objc class OperatorInClass {
// CHECK: {{^}} static func == (lhs: OperatorInClass, rhs: OperatorInClass) -> Bool
static func ==(lhs: OperatorInClass, rhs: OperatorInClass) -> Bool {
return true
}
// CHECK: {{^}} @objc static func + (lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass
@objc static func +(lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass { // expected-error {{operator methods cannot be declared @objc}}
return lhs
}
} // CHECK: {{^}$}}
@objc protocol OperatorInProtocol {
static func +(lhs: Self, rhs: Self) -> Self // expected-error {{@objc protocols must not have operator requirements}}
}
class AdoptsOperatorInProtocol : OperatorInProtocol {
static func +(lhs: AdoptsOperatorInProtocol, rhs: AdoptsOperatorInProtocol) -> Self {}
// expected-error@-1 {{operator methods cannot be declared @objc}}
}
//===--- @objc inference for witnesses
@objc protocol InferFromProtocol {
@objc(inferFromProtoMethod1:)
optional func method1(value: Int)
}
// Infer when in the same declaration context.
// CHECK-LABEL: ClassInfersFromProtocol1
class ClassInfersFromProtocol1 : InferFromProtocol{
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
// Infer when in a different declaration context of the same class.
// CHECK-LABEL: ClassInfersFromProtocol2a
class ClassInfersFromProtocol2a {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
extension ClassInfersFromProtocol2a : InferFromProtocol { }
// Infer when in a different declaration context of the same class.
class ClassInfersFromProtocol2b : InferFromProtocol { }
// CHECK-LABEL: ClassInfersFromProtocol2b
extension ClassInfersFromProtocol2b {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
// Don't infer when there is a signature mismatch.
// CHECK-LABEL: ClassInfersFromProtocol3
class ClassInfersFromProtocol3 : InferFromProtocol {
}
extension ClassInfersFromProtocol3 {
// CHECK: {{^}} func method1(value: String)
func method1(value: String) { }
}
// Inference for subclasses.
class SuperclassImplementsProtocol : InferFromProtocol { }
class SubclassInfersFromProtocol1 : SuperclassImplementsProtocol {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
class SubclassInfersFromProtocol2 : SuperclassImplementsProtocol {
}
extension SubclassInfersFromProtocol2 {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
@objc class NeverReturningMethod {
@objc func doesNotReturn() -> Never {}
}
// SR-5025
class User: NSObject {
}
@objc extension User {
var name: String {
get {
return "No name"
}
set {
// Nothing
}
}
var other: String {
unsafeAddress { // expected-error{{addressors are not allowed to be marked @objc}}
}
}
}
// 'dynamic' methods cannot be @inlinable.
class BadClass {
@inlinable @objc dynamic func badMethod1() {}
// expected-error@-1 {{'@inlinable' attribute cannot be applied to 'dynamic' declarations}}
}
@objc
protocol ObjCProtocolWithWeakProperty {
weak var weakProp: AnyObject? { get set } // okay
}
@objc
protocol ObjCProtocolWithUnownedProperty {
unowned var unownedProp: AnyObject { get set } // okay
}
// rdar://problem/46699152: errors about read/modify accessors being implicitly
// marked @objc.
@objc class MyObjCClass: NSObject {}
@objc
extension MyObjCClass {
@objc
static var objCVarInObjCExtension: Bool {
get {
return true
}
set {}
}
}
| apache-2.0 | b42c299b082795f6fdd7c5111b48a5cf | 39.654358 | 350 | 0.703593 | 3.899349 | false | false | false | false |
zisko/swift | tools/SwiftSyntax/Syntax.swift | 1 | 8415 | //===-------------------- Syntax.swift - Syntax Protocol ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
/// A Syntax node represents a tree of nodes with tokens at the leaves.
/// Each node has accessors for its known children, and allows efficient
/// iteration over the children through its `children` property.
public protocol Syntax:
CustomStringConvertible, TextOutputStreamable {}
internal protocol _SyntaxBase: Syntax {
/// The type of sequence containing the indices of present children.
typealias PresentChildIndicesSequence =
LazyFilterSequence<Range<Int>>
/// The root of the tree this node is currently in.
var _root: SyntaxData { get } // Must be of type SyntaxData
/// The data backing this node.
/// - note: This is unowned, because the reference to the root data keeps it
/// alive. This means there is an implicit relationship -- the data
/// property must be a descendent of the root. This relationship must
/// be preserved in all circumstances where Syntax nodes are created.
var _data: SyntaxData { get }
#if DEBUG
func validate()
#endif
}
extension _SyntaxBase {
public func validate() {
// This is for implementers to override to perform structural validation.
}
}
extension Syntax {
var data: SyntaxData {
guard let base = self as? _SyntaxBase else {
fatalError("only first-class syntax nodes can conform to Syntax")
}
return base._data
}
var _root: SyntaxData {
guard let base = self as? _SyntaxBase else {
fatalError("only first-class syntax nodes can conform to Syntax")
}
return base._root
}
/// Access the raw syntax assuming the node is a Syntax.
var raw: RawSyntax {
return data.raw
}
/// An iterator over children of this node.
public var children: SyntaxChildren {
return SyntaxChildren(node: self)
}
/// Whether or not this node it marked as `present`.
public var isPresent: Bool {
return raw.presence == .present
}
/// Whether or not this node it marked as `missing`.
public var isMissing: Bool {
return raw.presence == .missing
}
/// Whether or not this node represents an Expression.
public var isExpr: Bool {
return raw.kind.isExpr
}
/// Whether or not this node represents a Declaration.
public var isDecl: Bool {
return raw.kind.isDecl
}
/// Whether or not this node represents a Statement.
public var isStmt: Bool {
return raw.kind.isStmt
}
/// Whether or not this node represents a Type.
public var isType: Bool {
return raw.kind.isType
}
/// Whether or not this node represents a Pattern.
public var isPattern: Bool {
return raw.kind.isPattern
}
/// The parent of this syntax node, or `nil` if this node is the root.
public var parent: Syntax? {
guard let parentData = data.parent else { return nil }
return makeSyntax(root: _root, data: parentData)
}
/// The index of this node in the parent's children.
public var indexInParent: Int {
return data.indexInParent
}
/// The root of the tree in which this node resides.
public var root: Syntax {
return makeSyntax(root: _root, data: _root)
}
/// The sequence of indices that correspond to child nodes that are not
/// missing.
///
/// This property is an implementation detail of `SyntaxChildren`.
internal var presentChildIndices: _SyntaxBase.PresentChildIndicesSequence {
return raw.layout.indices.lazy.filter {
self.raw.layout[$0]?.isPresent == true
}
}
/// Gets the child at the provided index in this node's children.
/// - Parameter index: The index of the child node you're looking for.
/// - Returns: A Syntax node for the provided child, or `nil` if there
/// is not a child at that index in the node.
public func child(at index: Int) -> Syntax? {
guard raw.layout.indices.contains(index) else { return nil }
guard let childData = data.cachedChild(at: index) else { return nil }
return makeSyntax(root: _root, data: childData)
}
/// A source-accurate description of this node.
public var description: String {
var s = ""
self.write(to: &s)
return s
}
/// Prints the raw value of this node to the provided stream.
/// - Parameter stream: The stream to which to print the raw tree.
public func write<Target>(to target: inout Target)
where Target: TextOutputStream {
data.raw.write(to: &target)
}
}
/// Determines if two nodes are equal to each other.
public func ==(lhs: Syntax, rhs: Syntax) -> Bool {
return lhs.data === rhs.data
}
/// MARK: - Nodes
/// A Syntax node representing a single token.
public struct TokenSyntax: _SyntaxBase, Hashable {
let _root: SyntaxData
unowned let _data: SyntaxData
/// Creates a Syntax node from the provided root and data.
internal init(root: SyntaxData, data: SyntaxData) {
self._root = root
self._data = data
#if DEBUG
validate()
#endif
}
/// The text of the token as written in the source code.
public var text: String {
return tokenKind.text
}
public func withKind(_ tokenKind: TokenKind) -> TokenSyntax {
guard case let .token(_, leadingTrivia, trailingTrivia, presence) = raw else {
fatalError("TokenSyntax must have token as its raw")
}
let (root, newData) = data.replacingSelf(.token(tokenKind, leadingTrivia,
trailingTrivia, presence))
return TokenSyntax(root: root, data: newData)
}
/// Returns a new TokenSyntax with its leading trivia replaced
/// by the provided trivia.
public func withLeadingTrivia(_ leadingTrivia: Trivia) -> TokenSyntax {
guard case let .token(kind, _, trailingTrivia, presence) = raw else {
fatalError("TokenSyntax must have token as its raw")
}
let (root, newData) = data.replacingSelf(.token(kind, leadingTrivia,
trailingTrivia, presence))
return TokenSyntax(root: root, data: newData)
}
/// Returns a new TokenSyntax with its trailing trivia replaced
/// by the provided trivia.
public func withTrailingTrivia(_ trailingTrivia: Trivia) -> TokenSyntax {
guard case let .token(kind, leadingTrivia, _, presence) = raw else {
fatalError("TokenSyntax must have token as its raw")
}
let (root, newData) = data.replacingSelf(.token(kind, leadingTrivia,
trailingTrivia, presence))
return TokenSyntax(root: root, data: newData)
}
/// Returns a new TokenSyntax with its leading trivia removed.
public func withoutLeadingTrivia() -> TokenSyntax {
return withLeadingTrivia([])
}
/// Returns a new TokenSyntax with its trailing trivia removed.
public func withoutTrailingTrivia() -> TokenSyntax {
return withTrailingTrivia([])
}
/// Returns a new TokenSyntax with all trivia removed.
public func withoutTrivia() -> TokenSyntax {
return withoutLeadingTrivia().withoutTrailingTrivia()
}
/// The leading trivia (spaces, newlines, etc.) associated with this token.
public var leadingTrivia: Trivia {
guard case .token(_, let leadingTrivia, _, _) = raw else {
fatalError("TokenSyntax must have token as its raw")
}
return leadingTrivia
}
/// The trailing trivia (spaces, newlines, etc.) associated with this token.
public var trailingTrivia: Trivia {
guard case .token(_, _, let trailingTrivia, _) = raw else {
fatalError("TokenSyntax must have token as its raw")
}
return trailingTrivia
}
/// The kind of token this node represents.
public var tokenKind: TokenKind {
guard case .token(let kind, _, _, _) = raw else {
fatalError("TokenSyntax must have token as its raw")
}
return kind
}
public static func ==(lhs: TokenSyntax, rhs: TokenSyntax) -> Bool {
return lhs._data === rhs._data
}
public var hashValue: Int {
return ObjectIdentifier(_data).hashValue
}
}
| apache-2.0 | f3952f18fdf5989c8999d19ffc8ce22c | 31.365385 | 82 | 0.666904 | 4.459459 | false | false | false | false |
mozilla-mobile/firefox-ios | Tests/ClientTests/SyncStatusResolverTests.swift | 2 | 3612 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
@testable import Client
@testable import Sync
import Shared
import Storage
import XCTest
private class RandomError: MaybeErrorType {
var description = "random_error"
}
class SyncStatusResolverTests: XCTestCase {
private func mockStatsForCollection(collection: String) -> SyncEngineStatsSession {
return SyncEngineStatsSession(collection: collection)
}
func testAllCompleted() {
let results: EngineResults = [
("tabs", .completed(mockStatsForCollection(collection: "tabs"))),
("clients", .completed(mockStatsForCollection(collection: "clients")))
]
let maybeResults = Maybe(success: results)
let resolver = SyncStatusResolver(engineResults: maybeResults)
XCTAssertTrue(resolver.resolveResults() == SyncDisplayState.good)
}
func testAllCompletedExceptOneDisabledRemotely() {
let results: EngineResults = [
("tabs", .completed(mockStatsForCollection(collection: "tabs"))),
("clients", .notStarted(.engineRemotelyNotEnabled(collection: "clients")))
]
let maybeResults = Maybe(success: results)
let resolver = SyncStatusResolver(engineResults: maybeResults)
XCTAssertTrue(resolver.resolveResults() == SyncDisplayState.good)
}
func testAllCompletedExceptNotStartedBecauseNoAccount() {
let results: EngineResults = [
("tabs", .completed(mockStatsForCollection(collection: "tabs"))),
("clients", .notStarted(.noAccount))
]
let maybeResults = Maybe(success: results)
let resolver = SyncStatusResolver(engineResults: maybeResults)
XCTAssertTrue(resolver.resolveResults() == SyncDisplayState.warning(message: .FirefoxSyncOfflineTitle))
}
func testAllCompletedExceptNotStartedBecauseOffline() {
let results: EngineResults = [
("tabs", .completed(mockStatsForCollection(collection: "tabs"))),
("clients", .notStarted(.offline))
]
let maybeResults = Maybe(success: results)
let resolver = SyncStatusResolver(engineResults: maybeResults)
XCTAssertTrue(resolver.resolveResults() == SyncDisplayState.bad(message: .FirefoxSyncOfflineTitle))
}
func testOfflineAndNoAccount() {
let results: EngineResults = [
("tabs", .notStarted(.noAccount)),
("clients", .notStarted(.offline))
]
let maybeResults = Maybe(success: results)
let resolver = SyncStatusResolver(engineResults: maybeResults)
XCTAssertTrue(resolver.resolveResults() == SyncDisplayState.bad(message: .FirefoxSyncOfflineTitle))
}
func testAllPartial() {
let results: EngineResults = [
("tabs", .partial(SyncEngineStatsSession(collection: "tabs"))),
("clients", .partial(SyncEngineStatsSession(collection: "clients")))
]
let maybeResults = Maybe(success: results)
let resolver = SyncStatusResolver(engineResults: maybeResults)
XCTAssertTrue(resolver.resolveResults() == SyncDisplayState.good)
}
func testRandomFailure() {
let maybeResults: Maybe<EngineResults> = Maybe(failure: RandomError())
let resolver = SyncStatusResolver(engineResults: maybeResults)
let expected = SyncDisplayState.bad(message: nil)
XCTAssertTrue(resolver.resolveResults() == expected)
}
}
| mpl-2.0 | 57b8da49db7ce9eb8650796db69efcbb | 37.021053 | 111 | 0.680509 | 4.995851 | false | true | false | false |
koogawa/FoursquareAPIClient | Example/FoursquareAPIClient/Model/FoursquareManager.swift | 1 | 2395 | //
// FoursquareManager.swift
// VenueMap
//
// Created by koogawa on 2015/07/21.
// Copyright (c) 2015 Kosuke Ogawa. All rights reserved.
//
import UIKit
import MapKit
class FoursquareManager: NSObject {
var accessToken: String!
var venues: [Venue] = []
class func sharedManager() -> FoursquareManager {
struct Static {
static let instance = FoursquareManager()
}
return Static.instance
}
func searchVenuesWithCoordinate(_ coordinate: CLLocationCoordinate2D, completion: ((Error?) -> ())?) {
let client = FoursquareAPIClient(accessToken: accessToken)
let parameter: [String: String] = [
"ll": "\(coordinate.latitude),\(coordinate.longitude)",
];
client.request(path: "venues/search", parameter: parameter) {
[weak self] result in
switch result {
case let .success(data):
let decoder: JSONDecoder = JSONDecoder()
do {
let response = try decoder.decode(Response<SearchResponse>.self, from: data)
self?.venues = response.response.venues
completion?(nil)
} catch {
completion?(error)
}
case let .failure(error):
completion?(error)
}
}
}
func checkinWithVenueId(_ venueId: String, location: CLLocation, completion: ((Checkin?, Error?) -> ())?) {
let client = FoursquareAPIClient(accessToken: accessToken)
let parameter: [String: String] = [
"venueId": venueId,
"ll": "\(location.coordinate.latitude),\(location.coordinate.longitude)",
"alt": "\(location.altitude)",
];
client.request(path: "checkins/add", method: .post, parameter: parameter) {
result in
switch result {
case let .success(data):
let decoder: JSONDecoder = JSONDecoder()
do {
let response = try decoder.decode(Response<CheckinResponse>.self, from: data)
completion?(response.response.checkin, nil)
} catch {
completion?(nil, error)
}
case let .failure(error):
completion?(nil, error)
}
}
}
}
| mit | 78e71fc6935503f0662d01daf9d7ae08 | 30.103896 | 111 | 0.538622 | 4.989583 | false | false | false | false |
mojidabckuu/activerecord | ActiveRecord/AR/Adapters/Adapter.swift | 1 | 2004 | //
// Adapter.swift
// ActiveRecord
//
// Created by Vlad Gorbenko on 4/21/16.
// Copyright © 2016 Vlad Gorbenko. All rights reserved.
//
import Foundation
public enum DBError: ErrorType {
case OpenDatabase(message: String)
case Prepare(message: String)
case Step(message: String)
case Bind(message: String)
case Statement(message: String)
}
public class Adapter {
public enum Type: String {
case SQLite = "SQLite"
}
public static var current: Adapter!
public static func adapter(settings: [String: Any]) -> Adapter {
let type = Type(rawValue: settings["adapter"] as! String)!
switch type {
case .SQLite: Adapter.current = SQLiteAdapter(settings: settings)
}
return Adapter.current
}
var columnTypes: [String : Table.Column.DBType] {
return ["text" : .String,
"int" : .Int,
"date" : .Date,
"real" : .Decimal,
"blob" : .Raw]
}
var persistedColumnTypes: [Table.Column.DBType : String] { return [:] }
public var connection: Connection!
private var settings: [String: Any]?
init(settings: [String: Any]) {
self.settings = settings
self.connection = self.connect()
}
public func indexes() -> Array<String> {
return Array<String>()
}
//MARK: - Tables
public func tables() -> Array<String> {
return Array<String>()
}
public func structure(table: String) -> Dictionary<String, Table.Column> {
return [:]
}
//MARK: - Utils
public func connect() -> Connection {
do {
let dbName = self.settings?["name"] as! String
return try Connection(dbName)
} catch {
print(error)
fatalError("Closing application due to db connection error...")
}
}
public func disconnect() {
self.connection.close()
}
} | mit | e2304997abd65b293bd40c9dc2d2a7c3 | 24.05 | 78 | 0.565652 | 4.335498 | false | false | false | false |
DevaLee/LYCSwiftDemo | LYCSwiftDemo/Classes/live/View/LYCRoomViewController.swift | 1 | 7572 | //
// LiveViewController.swift
// XMGTV
//
// Created by apple on 16/11/9.
// Copyright © 2016年 coderwhy. All rights reserved.
//
import UIKit
import Kingfisher
fileprivate let kChatToolViewHeight : CGFloat = 44.0
class LYCRoomViewController: UIViewController , LYCEmitterProtocol {
// MARK: 控件属性
@IBOutlet weak var bgImageView: UIImageView!
fileprivate var timer : Timer?
fileprivate lazy var chatToolsView : LYCChatToolView = LYCChatToolView.loadNibAble()
fileprivate lazy var chatContainerView : LYCChatContainerView = LYCChatContainerView.loadNibAble()
fileprivate lazy var giftView : LYCGifView = {
let rect = CGRect(x: 0, y: kScreenHeight, width: kScreenWidth, height: 280)
let gifView = LYCGifView(frame:rect)
gifView.deleage = self
return gifView
}()
fileprivate lazy var chatScoket : YCSocket = {
let chatSocket = YCSocket(addr: "192.168.0.108", port: 8788)
if chatSocket.connectServer() {
chatSocket.startReadMsg()
}
chatSocket.delegate = self;
return chatSocket;
}()
// MARK: 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
addObserver()
chatScoket.sendJoinRoom()
}
deinit {
chatScoket.sendLeaveRoom()
print(" room deinit" )
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: animated)
}
}
// MARK:- 设置UI界面内容
extension LYCRoomViewController {
fileprivate func setupUI() {
setupChatContainerView()
setupBlurView()
setupBottomView()
setupGifView()
}
//设置聊天框
private func setupChatContainerView(){
chatContainerView.frame = CGRect(x: 0, y: self.view.frame.height - 200 - 44 , width: kScreenWidth, height: 200)
chatContainerView.backgroundColor = UIColor.clear
view.addSubview(chatContainerView);
}
// 设置毛玻璃
private func setupBlurView() {
let blur = UIBlurEffect(style: .dark)
let blurView = UIVisualEffectView(effect: blur)
blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
blurView.frame = bgImageView.bounds
bgImageView.addSubview(blurView)
}
// 设置顶部聊天框
private func setupBottomView() {
chatToolsView.frame = CGRect(x: 0, y: view.bounds.height, width: view.bounds.width , height:kChatToolViewHeight )
chatToolsView.autoresizingMask = [.flexibleTopMargin,.flexibleWidth]
chatToolsView.delegate = self
view.addSubview(chatToolsView)
}
// 设置礼物界面
private func setupGifView(){
LYCGifViewModel.shareInstance.loadGifData(finishCallBack: {
self.view.addSubview(self.giftView)
self.view.bringSubview(toFront: self.giftView)
})
}
}
extension LYCRoomViewController {
fileprivate func addObserver() {
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillChangeFrame (_:)) , name: .UIKeyboardWillChangeFrame, object: nil)
}
}
// MARK:- 事件监听
extension LYCRoomViewController {
@IBAction func exitBtnClick() {
timer?.invalidate()
timer = nil
chatScoket.sendLeaveRoom()
_ = navigationController?.popViewController(animated: true)
}
@IBAction func bottomMenuClick(_ sender: UIButton) {
switch sender.tag {
case 0:
chatToolsView.chatTextFiled.becomeFirstResponder()
case 1:
print("点击了分享")
case 2:
let gifViewY = kScreenHeight - giftView.frame.height
UIView.animate(withDuration: 0.5, animations: {
self.giftView.frame.origin.y = gifViewY
})
case 3:
print("点击了更多")
case 4:
sender.isSelected = !sender.isSelected
sender.isSelected ? addEmitter(point: CGPoint(x: sender.center.x, y: UIScreen.main.bounds.size.height - sender.center.y)) : stopEmitter()
default:
fatalError("未处理按钮")
}
}
//
@objc fileprivate func emotionButtonClick(_ sender : UIButton){
sender.isSelected = !sender.isSelected
print("…………………………")
}
@objc fileprivate func keyBoardWillChangeFrame (_ notify : Notification){
chatToolsView.sendButton.isEnabled = true
let userInfo = notify.userInfo as! Dictionary<String, Any>
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
let value = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue
let keyBoardFrame = value.cgRectValue
let chatToolY = keyBoardFrame.minY - kChatToolViewHeight
UIView.animate(withDuration: duration) {
self.chatToolsView.frame.origin.y = chatToolY
self.chatContainerView.frame.origin.y = chatToolY - self.chatContainerView.frame.height
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.chatToolsView.chatTextFiled.resignFirstResponder()
UIView.animate(withDuration: 0.5) {
self.chatToolsView.frame.origin.y = kScreenHeight
self.giftView.frame.origin.y = kScreenHeight
}
}
}
//MARK:-LYCChatToolViewDelegate 聊天框代理
extension LYCRoomViewController : LYCChatToolViewDelegate{
func chatToolView(_ chatToolView: LYCChatToolView, message: String) {
chatScoket.sendTextMessage(textMsg: message)
}
}
//MARK:-LYCGifView 发送礼物回调
extension LYCRoomViewController : LYCGifViewDelegate{
func gitView(_ gifView: LYCGifView, collectionView: UICollectionView, didSelectRowAtIndex indexPath: IndexPath, gifModel: LYCGifModel) {
chatScoket.sendGif(gifName: gifModel.subject, gifUrl: gifModel.img, gifNum: "1")
self.giftView.frame.origin.y = kScreenHeight
}
}
//MARK:- YCSocketDelegate socket消息代理
extension LYCRoomViewController : YCSocketDelegate{
func socket(_ socket: YCSocket, joinRoom userInfo: UserInfo) {
let attrSting = LYCMAttributStingExtension.userJoinLeaveRoom(userName: userInfo.name, isJoinRoom: true)
chatContainerView.addAttributeStringReloadData(attrSting: attrSting)
}
func socket(_ socket: YCSocket, leaveRoom userInfo: UserInfo) {
let attrSting = LYCMAttributStingExtension.userJoinLeaveRoom(userName: userInfo.name, isJoinRoom: false)
chatContainerView.addAttributeStringReloadData(attrSting: attrSting)
}
func socket(_ socket: YCSocket, chatMsg: TextMessage) {
let attrSting = LYCMAttributStingExtension.userSendMsg(userName: chatMsg.user.name, chatMsg: chatMsg.text)
chatContainerView.addAttributeStringReloadData(attrSting: attrSting)
}
func socket(_ socket: YCSocket, sendGif gif: GiftMessage) {
let attrSting = LYCMAttributStingExtension.sendGif(userName: gif.user.name, gifUrl: gif.giftUrl, gifName: gif.giftname)
chatContainerView.addAttributeStringReloadData(attrSting: attrSting)
}
}
| mit | d31139b3d5ce6db8bc9f4b4ae7bff420 | 33.593458 | 151 | 0.668243 | 4.541718 | false | false | false | false |
Johnykutty/SwiftLint | Source/SwiftLintFramework/Models/Command.swift | 2 | 3890 | //
// Command.swift
// SwiftLint
//
// Created by JP Simard on 8/29/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
#if !os(Linux)
private extension Scanner {
func scanUpToString(_ string: String) -> String? {
var result: NSString? = nil
let success = scanUpTo(string, into: &result)
if success {
return result?.bridge()
}
return nil
}
func scanString(string: String) -> String? {
var result: NSString? = nil
let success = scanString(string, into: &result)
if success {
return result?.bridge()
}
return nil
}
}
#endif
public struct Command {
public enum Action: String {
case enable
case disable
fileprivate func inverse() -> Action {
switch self {
case .enable: return .disable
case .disable: return .enable
}
}
}
public enum Modifier: String {
case previous
case this
case next
}
internal let action: Action
internal let ruleIdentifiers: [String]
internal let line: Int
internal let character: Int?
private let modifier: Modifier?
public init(action: Action, ruleIdentifiers: [String], line: Int = 0,
character: Int? = nil, modifier: Modifier? = nil) {
self.action = action
self.ruleIdentifiers = ruleIdentifiers
self.line = line
self.character = character
self.modifier = modifier
}
public init?(string: NSString, range: NSRange) {
let scanner = Scanner(string: string.substring(with: range))
_ = scanner.scanString(string: "swiftlint:")
guard let actionAndModifierString = scanner.scanUpToString(" ") else {
return nil
}
let actionAndModifierScanner = Scanner(string: actionAndModifierString)
guard let actionString = actionAndModifierScanner.scanUpToString(":"),
let action = Action(rawValue: actionString),
let lineAndCharacter = string.lineAndCharacter(forCharacterOffset: NSMaxRange(range))
else {
return nil
}
self.action = action
ruleIdentifiers = scanner.string.bridge()
.substring(from: scanner.scanLocation + 1)
.components(separatedBy: .whitespaces)
line = lineAndCharacter.line
character = lineAndCharacter.character
let hasModifier = actionAndModifierScanner.scanString(string: ":") != nil
// Modifier
if hasModifier {
let modifierString = actionAndModifierScanner.string.bridge()
.substring(from: actionAndModifierScanner.scanLocation)
modifier = Modifier(rawValue: modifierString)
} else {
modifier = nil
}
}
internal func expand() -> [Command] {
guard let modifier = modifier else {
return [self]
}
switch modifier {
case .previous:
return [
Command(action: action, ruleIdentifiers: ruleIdentifiers, line: line - 1),
Command(action: action.inverse(), ruleIdentifiers: ruleIdentifiers, line: line - 1,
character: Int.max)
]
case .this:
return [
Command(action: action, ruleIdentifiers: ruleIdentifiers, line: line),
Command(action: action.inverse(), ruleIdentifiers: ruleIdentifiers, line: line,
character: Int.max)
]
case .next:
return [
Command(action: action, ruleIdentifiers: ruleIdentifiers, line: line + 1),
Command(action: action.inverse(), ruleIdentifiers: ruleIdentifiers, line: line + 1,
character: Int.max)
]
}
}
}
| mit | 949a7b3566b19bafedcf70999a8e5251 | 30.362903 | 99 | 0.580098 | 4.94155 | false | false | false | false |
gouyz/GYZBaking | baking/Classes/Tool/3rdLib/ScrollPageView/SegmentStyle.swift | 1 | 4461 | //
// SegmentStyle.swift
// ScrollViewController
//
// Created by jasnig on 16/4/13.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
/// 通知使用示例
/**
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self
, selector: #selector(self.didSelectIndex(_:)), name: ScrollPageViewDidShowThePageNotification, object: nil)
}
func didSelectIndex(noti: NSNotification) {
let userInfo = noti.userInfo!
//注意键名是currentIndex
print(userInfo["currentIndex"])
}
特别注意的是如果你的控制器是使用的storyBoard初始化, 务必重写这个初始化方法中注册通知监听者, 如果在viewDidLoad中注册,在第一次的时候将不会接受到通知
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.didSelectIndex(_:)), name: ScrollPageViewDidShowThePageNotification, object: nil)
}
func didSelectIndex(noti: NSNotification) {
let userInfo = noti.userInfo!
//注意键名是currentIndex
print(userInfo["currentIndex"])
}
*/
/// 这个是发布当前显示的index的下标, 从 0 开始 注意, 通知的字典中的键名是 currentIndex
public let ScrollPageViewDidShowThePageNotification = "ScrollPageViewDidShowThePageNotification"
public struct SegmentStyle {
/// 是否显示遮盖
public var showCover = false
/// 是否显示下划线
public var showLine = false
/// 是否缩放文字
public var scaleTitle = false
/// 是否可以滚动标题
public var scrollTitle = true
/// 是否颜色渐变
public var gradualChangeTitleColor = false
/// 是否显示附加的按钮
public var showExtraButton = false
/// 点击title切换内容的时候是否有动画 默认为true
public var changeContentAnimated = true
public var extraBtnBackgroundImageName: String?
/// 下面的滚动条的高度 默认2
public var scrollLineHeight: CGFloat = 2
/// 下面的滚动条的颜色
public var scrollLineColor = UIColor.brown
/// 遮盖的背景颜色
public var coverBackgroundColor = UIColor.lightGray
/// 遮盖圆角
public var coverCornerRadius: CGFloat = 14.0
/// cover的高度 默认28
public var coverHeight: CGFloat = 28.0
/// 文字间的间隔 默认15
public var titleMargin: CGFloat = 15
/// 文字 字体 默认14.0
public var titleFont = UIFont.systemFont(ofSize: 14.0)
/// 放大倍数 默认1.3
public var titleBigScale: CGFloat = 1.3
/// 默认倍数 不可修改
let titleOriginalScale: CGFloat = 1.0
/// 文字正常状态颜色 请使用RGB空间的颜色值!! 如果提供的不是RGB空间的颜色值就可能crash
public var normalTitleColor = UIColor(red: 51.0/255.0, green: 53.0/255.0, blue: 75/255.0, alpha: 1.0)
/// 文字选中状态颜色 请使用RGB空间的颜色值!! 如果提供的不是RGB空间的颜色值就可能crash
public var selectedTitleColor = UIColor(red: 255.0/255.0, green: 0.0/255.0, blue: 121/255.0, alpha: 1.0)
/// 是否显示角标
public var showBadge = false
public init() {
}
}
| mit | 6172b419cc1df4bb148c5e7a2c0daf2c | 32.824561 | 162 | 0.72251 | 3.867603 | false | false | false | false |
oceanfive/swift | swift_two/swift_two/Classes/View(controller)/Home/HYHomeTableCell.swift | 1 | 2283 | //
// HYHomeTableCell.swift
// swift_two
//
// Created by ocean on 16/6/20.
// Copyright © 2016年 ocean. All rights reserved.
//
import UIKit
class HYHomeTableCell: UITableViewCell, HYStatusToolBarViewDelegate {
//MARK: - 这里注意不要和父类有相同的属性名称,否则会冲突
let statusContentView = HYStatusContentView()
let toolBarView = HYStatusToolBarView()
var statusFrame = HYStatusesFrame(){
willSet(newValue){
// self.frame = newValue.frame!
statusContentView.contentViewFrame = newValue.contentFrame!
toolBarView.frame = newValue.toolBarFrame!
toolBarView.status = newValue.status
// setNeedsLayout()
}
}
class func homeTableCell(tableView: UITableView) -> HYHomeTableCell {
//MARK: - 这里在oc中可以不需要进行类型转换,但是在swift中需要进行类型转换,即父类向子类进行类型转换
var cell = tableView.dequeueReusableCellWithIdentifier(kHomeTableCellIdentifier) as? HYHomeTableCell
if cell == nil {
cell = HYHomeTableCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: kHomeTableCellIdentifier)
// cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: kHomeTableCellIdentifier)
}
return cell!
}
//MARK: - 重写实例化方法
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
// Super.init isn't called before returning from initializer
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(statusContentView)
addSubview(toolBarView)
toolBarView.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func statusToolBarRepostsButtonDidClick() {
print("点击转发按钮")
}
func statusToolBarCommentsButtonDidClick() {
print("点击转发按钮")
}
func statusToolBarAttitudesButtonDidClick() {
print("点击转发按钮")
}
}
| mit | be693e653b66fe7927ddf7e76d5c890e | 24.950617 | 117 | 0.625119 | 4.934272 | false | false | false | false |
GagSquad/SwiftCommonUtil | CommonUtil/CommonUtil/Base/BaseCoreData.swift | 1 | 6072 | //
// BaseCoreData.swift
// CommonUtil
//
// Created by lijunjie on 15/12/7.
// Copyright © 2015年 lijunjie. All rights reserved.
//
import Foundation
import CoreData
public class BaseCoreData {
private var PSC: NSPersistentStoreCoordinator?
private var persistentStoreCoordinator: NSPersistentStoreCoordinator? {
get {
if managedObjectModel == nil {
return nil
}
if PSC != nil {
return PSC
}
let databasePath = self.getPath()
let storeURL = NSURL.fileURLWithPath(databasePath)
PSC = NSPersistentStoreCoordinator.init(managedObjectModel:managedObjectModel!)
do {
try persistentStore = PSC?.addPersistentStoreWithType(storeType, configuration: nil, URL: storeURL, options: nil)
} catch {
print("Unresolved error")
abort()
}
if persistentStore == nil {
print("Unresolved error")
abort()
}
return PSC
}
set {
self.persistentStoreCoordinator = newValue
}
}
private var MOM: NSManagedObjectModel?
private var managedObjectModel: NSManagedObjectModel? {
get {
if modelFileName.isEmpty {
return nil
}
if MOM != nil {
return MOM
}
let rag = modelFileName.rangeOfString(".momd")
var copymodFileName = modelFileName
if let r = rag {
copymodFileName = modelFileName.substringToIndex(r.endIndex)
}
let modelURL = NSBundle.mainBundle().URLForResource(copymodFileName, withExtension: "momd")
MOM = NSManagedObjectModel(contentsOfURL: modelURL!)
return MOM
}
set {
MOM = newValue
}
}
public var managedObjectContext: NSManagedObjectContext?
private var persistentStore: NSPersistentStore?
private var modelFileName: String = ""
private var savePath: String = ""
private var saveName: String = ""
private var storeType: String = ""
public init(modelFileName: String, savePath: String, saveName: String, storeType: String) {
self.modelFileName = modelFileName
self.saveName = saveName
self.savePath = savePath
self.storeType = storeType
self.initManagedObjectContext()
}
public func cleanUp() {
persistentStoreCoordinator = nil
managedObjectModel = nil
managedObjectContext = nil
persistentStore = nil
}
public func initManagedObjectContext() {
if managedObjectModel == nil {
return
}
if persistentStoreCoordinator == nil {
return
}
if managedObjectContext == nil {
managedObjectContext = NSManagedObjectContext.init(concurrencyType: .PrivateQueueConcurrencyType)
managedObjectContext?.persistentStoreCoordinator = persistentStoreCoordinator
managedObjectContext?.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
}
}
private func getPath() -> String {
let fileMgr: NSFileManager = NSFileManager.defaultManager()
if !fileMgr.fileExistsAtPath(savePath) {
do {
try fileMgr.createDirectoryAtPath(savePath, withIntermediateDirectories: true, attributes: nil)
} catch {
print("创建文件失败!")
}
}
return (savePath as NSString).stringByAppendingPathComponent(saveName)
}
public func performBlock(block: () -> Void) {
let moc = managedObjectContext
moc?.performBlock(block)
}
public func performBlock(block: (moc: NSManagedObjectContext) -> Void, complete: () -> Void) {
let moc = managedObjectContext
moc?.performBlock({ () -> Void in
block(moc: moc!)
dispatch_async(dispatch_get_main_queue(), complete)
})
}
public func safelySaveContextMOC() {
self.managedObjectContext?.performBlockAndWait({ () -> Void in
self.saveContextMOC()
})
}
public func unsafelySaveContextMOC() {
self.managedObjectContext?.performBlock({ () -> Void in
self.saveContextMOC()
})
}
private func saveContextMOC() {
self.saveContext(self.managedObjectContext!)
}
private func saveContext(savedMoc:NSManagedObjectContext) -> Bool {
var contextToSave:NSManagedObjectContext? = savedMoc
while (contextToSave != nil) {
var success = false
do {
let s: NSSet = (contextToSave?.insertedObjects)! as NSSet
try contextToSave?.obtainPermanentIDsForObjects(s.allObjects as! [NSManagedObject])
} catch {
print("保存失败!!!")
return false
}
if contextToSave?.hasChanges == true {
do {
try contextToSave?.save()
success = true
} catch {
print("Saving of managed object context failed")
success = false
}
} else {
success = true
}
if success == false {
return false
}
if contextToSave!.parentContext == nil && contextToSave!.persistentStoreCoordinator == nil {
print("Reached the end of the chain of nested managed object contexts without encountering a persistent store coordinator. Objects are not fully persisted.")
return false
}
contextToSave = contextToSave?.parentContext
}
return true
}
}
| gpl-2.0 | 0dbb5e1edc0f1d47bbb1515798561ee1 | 31.304813 | 173 | 0.559676 | 6.028942 | false | false | false | false |
mmrmmlrr/ExamMaster | Pods/ModelsTreeKit/ModelsTreeKit/Classes/SessionController/GlobalEvent.swift | 2 | 865 | //
// GlobalEvent.swift
// ModelsTreeKit
//
// Created by aleksey on 28.02.16.
// Copyright © 2016 aleksey chernish. All rights reserved.
//
public protocol GlobalEventName {
var rawValue: String { get }
}
public func ==(lhs: GlobalEventName, rhs: GlobalEventName) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public struct GlobalEvent {
public var name: GlobalEventName
public var object: Any?
public var userInfo: [String: Any]
public init(name: GlobalEventName, object: Any? = nil, userInfo: [String: Any] = [:]) {
self.name = name
self.object = object
self.userInfo = userInfo
}
public var hashValue: Int {
return name.rawValue.hashValue
}
}
extension GlobalEvent: Equatable, Hashable {}
public func ==(lhs: GlobalEvent, rhs: GlobalEvent) -> Bool {
return lhs.name.rawValue == rhs.name.rawValue
} | mit | dfad4e968f4aa38168f30ba3c5b77887 | 20.097561 | 89 | 0.681713 | 3.756522 | false | false | false | false |
teambition/CardStyleTableView | CardStyleTableView/CardStyleTableViewCell.swift | 1 | 6896 | //
// CardStyleTableViewCell.swift
// CardStyleTableView
//
// Created by Xin Hong on 16/1/20.
// Copyright © 2016年 Teambition. All rights reserved.
//
import UIKit
extension UITableViewCell {
// MARK: - Properties
fileprivate var tableView: UITableView? {
get {
let container = objc_getAssociatedObject(self, &AssociatedKeys.cardStyleTableViewCellTableView) as? WeakObjectContainer
return container?.object as? UITableView
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.cardStyleTableViewCellTableView, WeakObjectContainer(object: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
updateFrame()
}
}
fileprivate var indexPath: IndexPath? {
guard let tableView = tableView else {
return nil
}
return tableView.indexPath(for: self) ?? tableView.indexPathForRow(at: center)
}
fileprivate var indexPathLocation: (isFirstRowInSection: Bool, isLastRowInSection: Bool) {
guard let tableView = tableView, let indexPath = indexPath else {
return (false, false)
}
let isFirstRowInSection = indexPath.row == 0
let isLastRowInSection = indexPath.row == tableView.numberOfRows(inSection: indexPath.section) - 1
return (isFirstRowInSection, isLastRowInSection)
}
// MARK: - Initialize
internal class func cardStyle_swizzle() {
if self != UITableViewCell.self {
return
}
cardStyle_swizzleTableViewCellLayoutSubviews
cardStyle_swizzleTableViewCellDidMoveToSuperview
}
// MARK: - Method swizzling
@objc func cardStyle_tableViewCellSwizzledLayoutSubviews() {
cardStyle_tableViewCellSwizzledLayoutSubviews()
updateFrame()
setRoundingCorners()
}
@objc func cardStyle_tableViewCellSwizzledDidMoveToSuperview() {
cardStyle_tableViewCellSwizzledDidMoveToSuperview()
tableView = nil
if let tableView = superview as? UITableView {
self.tableView = tableView
} else if let tableView = superview?.superview as? UITableView {
self.tableView = tableView
}
}
fileprivate class func cardStyle_swizzleMethod(for aClass: AnyClass, originalSelector: Selector, swizzledSelector: Selector) {
guard let originalMethod = class_getInstanceMethod(aClass, originalSelector), let swizzledMethod = class_getInstanceMethod(aClass, swizzledSelector) else {
return
}
let didAddMethod = class_addMethod(aClass, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(aClass, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
fileprivate static let cardStyle_swizzleTableViewCellLayoutSubviews: () = {
let originalSelector = TableViewCellSelectors.layoutSubviews
let swizzledSelector = TableViewCellSelectors.swizzledLayoutSubviews
cardStyle_swizzleMethod(for: UITableViewCell.self, originalSelector: originalSelector, swizzledSelector: swizzledSelector)
print("cardStyle_swizzleTableViewCellLayoutSubviews")
}()
fileprivate static let cardStyle_swizzleTableViewCellDidMoveToSuperview: () = {
let originalSelector = TableViewCellSelectors.didMoveToSuperview
let swizzledSelector = TableViewCellSelectors.swizzledDidMoveToSuperview
cardStyle_swizzleMethod(for: UITableViewCell.self, originalSelector: originalSelector, swizzledSelector: swizzledSelector)
print("cardStyle_swizzleTableViewCellDidMoveToSuperview")
}()
// MARK: - Helper
fileprivate func updateFrame() {
guard let tableView = tableView, tableView.style == .grouped && tableView.cardStyleSource != nil else {
return
}
guard let leftPadding = tableView.leftPadding, let rightPadding = tableView.rightPadding else {
return
}
var needsLayout = false
if frame.origin.x != leftPadding {
frame.origin.x = leftPadding
needsLayout = true
}
if frame.width != tableView.frame.width - leftPadding - rightPadding {
frame.size.width = tableView.frame.width - leftPadding - rightPadding
needsLayout = true
}
if #available(iOS 10.0, *), needsLayout {
layoutIfNeeded()
}
}
fileprivate func setRoundingCorners() {
guard let tableView = tableView, let indexPath = indexPath, tableView.style == .grouped && tableView.cardStyleSource != nil else {
layer.mask = nil
return
}
var roundingCorners = tableView.cardStyleSource?.roundingCornersForCard(inSection: indexPath.section) ?? UIRectCorner.allCorners
guard let cornerRadius = tableView.cardStyleSource?.cornerRadiusForCardStyleTableView(), roundingCorners != [] else {
layer.mask = nil
return
}
let maskLayer = CAShapeLayer()
let maskRect = bounds
maskLayer.frame = maskRect
let cornerRadii = CGSize(width: cornerRadius, height: cornerRadius)
switch indexPathLocation {
case (true, true):
let maskPath = UIBezierPath(roundedRect: maskRect, byRoundingCorners: roundingCorners, cornerRadii: cornerRadii)
maskLayer.path = maskPath.cgPath
layer.mask = maskLayer
case (true, false):
let firstRowCorners: UIRectCorner = {
if roundingCorners == .allCorners {
return [.topLeft, .topRight]
} else {
roundingCorners.remove(.bottomLeft)
roundingCorners.remove(.bottomRight)
return roundingCorners
}
}()
let maskPath = UIBezierPath(roundedRect: maskRect, byRoundingCorners: firstRowCorners, cornerRadii: cornerRadii)
maskLayer.path = maskPath.cgPath
layer.mask = maskLayer
case (false, true):
let lastRowCorners: UIRectCorner = {
if roundingCorners == .allCorners {
return [.bottomLeft, .bottomRight]
} else {
roundingCorners.remove(.topLeft)
roundingCorners.remove(.topRight)
return roundingCorners
}
}()
let maskPath = UIBezierPath(roundedRect: maskRect, byRoundingCorners: lastRowCorners, cornerRadii: cornerRadii)
maskLayer.path = maskPath.cgPath
layer.mask = maskLayer
default:
layer.mask = nil
}
}
}
| mit | c9fd0ecb357bb3321347617937448b16 | 39.309942 | 166 | 0.652691 | 5.831641 | false | false | false | false |
uvmlrc/osx-languageselection | LanguageSelection/ViewController.swift | 1 | 3495 | //
// ViewController.swift
// LanguageSelection
//
// Created by Scott Martindale on 11/26/2014.
// Copyright (c) 2014 Scott Martindale. All rights reserved.
//
import Cocoa
import Foundation
class ViewController: NSViewController {
@IBAction func setEnglish(sender: AnyObject) {
setLanguage("English")
}
@IBAction func setChinese(sender: AnyObject) {
setLanguage("Chinese")
}
@IBAction func setFrench(sender: AnyObject) {
setLanguage("French")
}
@IBAction func setGerman(sender: AnyObject) {
setLanguage("German")
}
@IBAction func setItalian(sender: AnyObject) {
setLanguage("Italian")
}
@IBAction func setJapanese(sender: AnyObject) {
setLanguage("Japanese")
}
@IBAction func setRussian(sender: AnyObject) {
setLanguage("Russian")
}
@IBAction func setSpanish(sender: AnyObject) {
setLanguage("Spanish")
}
func setLanguage(languageName: String) {
let task = NSTask()
task.launchPath = "/usr/bin/defaults"
if languageName == "English" {
println(languageName)
task.arguments = ["write", "NSGlobalDomain", "AppleLanguages", "-array", "en"]
} else if languageName == "Chinese" {
println(languageName)
task.arguments = ["write", "NSGlobalDomain", "AppleLanguages", "-array", "zh-Hans", "en"]
} else if languageName == "French" {
println(languageName)
task.arguments = ["write", "NSGlobalDomain", "AppleLanguages", "-array", "fr", "en"]
} else if languageName == "German" {
println(languageName)
task.arguments = ["write", "NSGlobalDomain", "AppleLanguages", "-array", "de", "en"]
} else if languageName == "Italian" {
println(languageName)
task.arguments = ["write", "NSGlobalDomain", "AppleLanguages", "-array", "it", "en"]
} else if languageName == "Japanese" {
println(languageName)
task.arguments = ["write", "NSGlobalDomain", "AppleLanguages", "-array", "ja", "en"]
} else if languageName == "Russian" {
println(languageName)
task.arguments = ["write", "NSGlobalDomain", "AppleLanguages", "-array", "ru", "en"]
} else if languageName == "Spanish" {
println(languageName)
task.arguments = ["write", "NSGlobalDomain", "AppleLanguages", "-array", "es-MX", "en"]
}
// Set System Language
let pipe = NSPipe()
task.standardOutput = pipe
task.launch()
//Kill Apps in English
killApps()
//Kill Self
killApp()
}
func killApps() {
let task = NSTask()
task.launchPath = "/usr/bin/killall"
task.arguments = ["Finder"]
task.arguments = ["Dock"]
// Kill Finder and Dock so that it reloads in target language.
let pipe = NSPipe()
task.standardOutput = pipe
task.launch()
}
func killApp() {
//Quit App
NSApplication.sharedApplication().terminate(self)
}
override func viewDidLoad() {
super.viewDidLoad()
println("loaded")
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
| mit | f81b110cb92e7491fd4d72786a14e3db | 30.205357 | 101 | 0.568526 | 4.604743 | false | false | false | false |
itechline/bonodom_new | SlideMenuControllerSwift/LoginUtil.swift | 1 | 7650 | //
// LoginUtil.swift
// Bonodom
//
// Created by Attila Dán on 2016. 06. 08..
// Copyright © 2016. Itechline. All rights reserved.
//
//
// RestApiUtil.swift
// Bonodom
//
// Created by Attila Dán on 2016. 06. 06..
// Copyright © 2016. Itechline. All rights reserved.
//
import SwiftyJSON
class LoginUtil: NSObject {
static let sharedInstance = LoginUtil()
let baseURL = "https://bonodom.com/api/"
func getTokenValidator(onCompletion: (JSON) -> Void) {
let token = [ "token", SettingUtil.sharedInstance.getToken()]
let tokenpost = token.joinWithSeparator("=")
let route = baseURL + "token_validator"
/*makeHTTPGetRequest(route, onCompletion: { json, err in
onCompletion(json as JSON)
})*/
makeHTTPPostRequest(route, body: tokenpost, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func doLogin(email: String, password: String, onCompletion: (JSON) -> Void) {
let mail = [ "email", email]
let mailPost = mail.joinWithSeparator("=")
let pass = [ "pass", password]
let passPost = pass.joinWithSeparator("=")
let pa = [ mailPost, passPost]
let postbody = pa.joinWithSeparator("&")
let route = baseURL + "do_login"
makeHTTPPostRequest(route, body: postbody, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func doLogout(onCompletion: (JSON) -> Void) {
let token = [ "token", SettingUtil.sharedInstance.getToken()]
let tokenpost = token.joinWithSeparator("=")
let route = baseURL + "do_logout"
makeHTTPPostRequest(route, body: tokenpost, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func doRegistration(email: String, password: String, vezeteknev: String, keresztnev: String,
tipus: String, onCompletion: (JSON) -> Void) {
let fel_vezeteknev = [ "fel_vezeteknev", vezeteknev]
let fel_vezeteknev_post = fel_vezeteknev.joinWithSeparator("=")
let fel_keresztnev = [ "fel_keresztnev", keresztnev]
let fel_keresztnev_post = fel_keresztnev.joinWithSeparator("=")
let fel_email = [ "fel_email", email]
let fel_email_post = fel_email.joinWithSeparator("=")
let fel_jelszo = [ "fel_jelszo", password]
let fel_jelszo_post = fel_jelszo.joinWithSeparator("=")
let fel_mobilszam = [ "fel_mobilszam", "0"]
let fel_mobilszam_post = fel_mobilszam.joinWithSeparator("=")
let fel_tipus = [ "fel_tipus", tipus]
let fel_tipus_post = fel_tipus.joinWithSeparator("=")
let fel_status = [ "fel_status", "1"]
let fel_status_post = fel_status.joinWithSeparator("=")
let pa = [ fel_vezeteknev_post, fel_keresztnev_post,
fel_email_post, fel_jelszo_post, fel_mobilszam_post,
fel_tipus_post, fel_status_post]
let postbody = pa.joinWithSeparator("&")
let route = baseURL + "reg"
makeHTTPPostRequest(route, body: postbody, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func doUpdateReg(lat: String, lng: String, mobile: String ,onCompletion: (JSON) -> Void) {
let token = [ "token", SettingUtil.sharedInstance.getToken()]
let token_post = token.joinWithSeparator("=")
let lat = [ "fel_lat", lat]
let lat_post = lat.joinWithSeparator("=")
let lng = [ "fel_lng", lng]
let lng_post = lng.joinWithSeparator("=")
let mobil = [ "fel_mobilszam", mobile]
let mobil_post = mobil.joinWithSeparator("=")
let pa = [ token_post, lat_post, lng_post, mobil_post]
let postbody = pa.joinWithSeparator("&")
let route = baseURL + "updatereg"
makeHTTPPostRequest(route, body: postbody, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func doUpdateProfile(vezeteknev: String, keresztnev: String, mobile: String, jelsz: String ,onCompletion: (JSON) -> Void) {
let token = [ "token", SettingUtil.sharedInstance.getToken()]
let token_post = token.joinWithSeparator("=")
let vez = [ "fel_vezeteknev", vezeteknev]
let vez_post = vez.joinWithSeparator("=")
let ker = [ "fel_keresztnev", keresztnev]
let ker_post = ker.joinWithSeparator("=")
let mobil = [ "fel_mobilszam", mobile]
let mobil_post = mobil.joinWithSeparator("=")
let jelszo = [ "fel_jelszo", jelsz]
let jelszo_post = jelszo.joinWithSeparator("=")
let pa = [ token_post, vez_post, ker_post, mobil_post, jelszo_post]
let postbody = pa.joinWithSeparator("&")
let route = baseURL + "update_profile"
makeHTTPPostRequest(route, body: postbody, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func getProfile(onCompletion: (JSON) -> Void) {
let token = [ "token", SettingUtil.sharedInstance.getToken()]
let token_post = token.joinWithSeparator("=")
let route = baseURL + "get_profile"
makeHTTPPostRequest(route, body: token_post, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
// MARK: Perform a GET Request
private func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
onCompletion(json, error)
} else {
onCompletion(nil, error)
}
})
task.resume()
}
// MARK: Perform a POST Request
private func makeHTTPPostRequest(path: String, body: String, onCompletion: ServiceResponse) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
// Set the method to POST
request.HTTPMethod = "POST"
//request.addValue("608f44981dd5241547605947c1dc38e0", forHTTPHeaderField: "token");
do {
// Set the POST body for the request
//let jsonBody = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted)
//let asdf = try NSData(body)
//request.HTTPBody = jsonBody
//let post:NSString = "token=608f44981dd5241547605947c1dc38e0"
print(body)
let postData:NSData = body.dataUsingEncoding(NSUTF8StringEncoding)!
request.HTTPBody = postData
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
onCompletion(json, nil)
} else {
onCompletion(nil, error)
}
})
task.resume()
} catch {
// Create your personal error
onCompletion(nil, nil)
}
}
}
| mit | c915e1ae51c9fc962f72d74150eb0b89 | 34.896714 | 127 | 0.572979 | 4.169029 | false | false | false | false |
Adorkable/Eunomia | Source/Core/UtilityExtensions/Views/UICollectionView+Utility.swift | 1 | 1934 | //
// UICollectionView+Utility.swift
// Allergy Abroad -> Eunomia
//
// Created by Ian Grossberg on 7/6/18.
// Copyright © 2018 Adorkable. All rights reserved.
//
#if os(iOS)
import UIKit
public extension UICollectionView {
func isLastCellVisible(inSection: Int) -> Bool {
let lastIndexPath = IndexPath(row: self.numberOfItems(inSection: inSection) - 1, section: inSection)
guard let cellAttributes = self.layoutAttributesForItem(at: lastIndexPath) else {
// TODO:
// throw
return false
}
let cellRect = self.convert(cellAttributes.frame, to: self.superview)
var visibleRect = CGRect(
x: self.bounds.origin.x,
y: self.bounds.origin.y,
width: self.bounds.size.width,
height: self.bounds.size.height - self.contentInset.bottom
)
visibleRect = self.convert(visibleRect, to: self.superview)
if visibleRect.intersects(cellRect) || visibleRect.contains(cellRect) {
return true
}
return false
}
func isLastCellFullyVisible(inSection: Int) -> Bool {
let lastIndexPath = IndexPath(row: self.numberOfItems(inSection: inSection) - 1, section: inSection)
guard let cellAttributes = self.layoutAttributesForItem(at: lastIndexPath) else {
// TODO:
// throw
return false
}
let cellRect = self.convert(cellAttributes.frame, to: self.superview)
var visibleRect = CGRect(
x: self.bounds.origin.x,
y: self.bounds.origin.y,
width: self.bounds.size.width,
height: self.bounds.size.height - self.contentInset.bottom
)
visibleRect = self.convert(visibleRect, to: self.superview)
if visibleRect.contains(cellRect) {
return true
}
return false
}
}
#endif
| mit | 444c4de5a4d7b654eb4f1456137d4169 | 30.688525 | 108 | 0.608381 | 4.474537 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChatMessageAccessoryView.swift | 1 | 10020 | //
// ChatMessageAccessoryView.swift
// Telegram
//
// Created by keepcoder on 05/10/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import Postbox
class ChatMessageAccessoryView: Control {
private let textView:TextView = TextView()
private let backgroundView = View()
private var maxWidth: CGFloat = 0
private let unread = View()
private var stringValue: String = ""
private let progress: RadialProgressView = RadialProgressView(theme: RadialProgressTheme(backgroundColor: .clear, foregroundColor: .white, cancelFetchingIcon: stopFetchStreamableControl), twist: true, size: NSMakeSize(24, 24))
private let bufferingIndicator: ProgressIndicator = ProgressIndicator(frame: NSMakeRect(0, 0, 10, 10))
private let download: ImageButton = ImageButton(frame: NSMakeRect(0, 0, 24, 24))
private var status: MediaResourceStatus?
private var isStreamable: Bool = true
private var isCompact: Bool = false
private var imageView: ImageView?
var soundOffOnImage: CGImage? {
didSet {
if let soundOffOnImage = soundOffOnImage {
if imageView == nil {
imageView = ImageView()
imageView?.animates = true
addSubview(imageView!)
}
imageView?.image = soundOffOnImage
imageView?.sizeToFit()
} else {
imageView?.removeFromSuperview()
imageView = nil
}
}
}
private let progressCap: View = View()
var isUnread: Bool = false
override func draw(_ layer: CALayer, in ctx: CGContext) {
}
override func layout() {
super.layout()
download.centerY(x: 6)
progress.centerY(x: 6)
backgroundView.frame = bounds
bufferingIndicator.centerY(x: frame.width - bufferingIndicator.frame.width - 7)
if let imageView = imageView {
imageView.centerY(x: frame.width - imageView.frame.width - 6)
}
if let textLayout = textView.textLayout {
var rect = focus(textLayout.layoutSize)
rect.origin.x = 6
if hasStremingControls {
rect.origin.x += download.frame.width + 6
}
if backingScaleFactor == 2 {
rect.origin.y += 0.5
} else {
rect.origin.y += 1
}
textView.frame = rect
unread.centerY(x: rect.maxX + 2)
}
}
var hasStremingControls: Bool {
return !download.isHidden || !progress.isHidden
}
private var fetch:(()->Void)?
private var cancelFetch:(()->Void)?
private var click:(()->Void)?
private var isVideoMessage: Bool = false
func updateText(_ text: String, maxWidth: CGFloat, status: MediaResourceStatus?, isStreamable: Bool, isCompact: Bool = false, soundOffOnImage: CGImage? = nil, isBuffering: Bool = false, isUnread: Bool = false, animated: Bool = false, isVideoMessage: Bool = false, fetch: @escaping()-> Void = { }, cancelFetch: @escaping()-> Void = { }, click: @escaping()-> Void = { }) -> Void {
let animated = animated && self.isCompact != isCompact
let updatedText = TextViewLayout(.initialize(string: isStreamable && !isCompact ? text.components(separatedBy: ", ").joined(separator: "\n") : text, color: isVideoMessage ? theme.chatServiceItemTextColor : .white, font: .normal(10.0)), maximumNumberOfLines: isStreamable && !isCompact ? 2 : 1, truncationType: .end, alwaysStaticItems: true) //TextNode.layoutText(maybeNode: textNode, .initialize(string: isStreamable ? text.components(separatedBy: ", ").joined(separator: "\n") : text, color: isVideoMessage ? theme.chatServiceItemTextColor : .white, font: .normal(10.0)), nil, isStreamable && !isCompact ? 2 : 1, .end, NSMakeSize(maxWidth, 20), nil, false, .left)
updatedText.measure(width: maxWidth)
textView.update(updatedText)
backgroundView.backgroundColor = isVideoMessage ? theme.chatServiceItemColor : .blackTransparent
self.isStreamable = isStreamable
self.status = status
self.stringValue = text
self.maxWidth = maxWidth
self.fetch = fetch
self.isCompact = isCompact
self.cancelFetch = cancelFetch
self.click = click
self.soundOffOnImage = soundOffOnImage
self.isUnread = isUnread
self.bufferingIndicator.isHidden = !isBuffering
self.unread.isHidden = !isUnread
if let status = status, isStreamable {
download.set(image: isCompact ? theme.icons.videoCompactFetching : theme.icons.streamingVideoDownload, for: .Normal)
switch status {
case .Remote:
progress.isHidden = true
download.isHidden = false
case .Local:
progress.isHidden = true
download.isHidden = true
case let .Fetching(_, progress), let .Paused(progress):
self.progress.state = !isCompact ? .Fetching(progress: progress, force: false) : .None
self.progress.isHidden = isCompact
download.isHidden = !isCompact
download.set(image: isCompact ? theme.icons.compactStreamingFetchingCancel : theme.icons.streamingVideoDownload, for: .Normal)
}
if isCompact {
download.setFrameSize(10, 10)
} else {
download.setFrameSize(28, 28)
}
} else {
progress.isHidden = true
download.isHidden = true
progress.state = .None
}
let newSize = NSMakeSize(min(max(soundOffOnImage != nil ? 30 : updatedText.layoutSize.width, updatedText.layoutSize.width) + 12 + (isUnread ? 8 : 0) + (hasStremingControls ? download.frame.width + 6 : 0) + (soundOffOnImage != nil ? soundOffOnImage!.backingSize.width + 2 : 0) + (isBuffering ? bufferingIndicator.frame.width + 4 : 0), maxWidth), hasStremingControls && !isCompact ? 36 : updatedText.layoutSize.height + 6)
change(size: newSize, animated: animated)
backgroundView.change(size: newSize, animated: animated)
backgroundView.layer?.cornerRadius = isStreamable ? 8 : newSize.height / 2
var rect = focus(updatedText.layoutSize)
rect.origin.x = 6
if hasStremingControls {
rect.origin.x += download.frame.width + 6
}
if backingScaleFactor == 2 {
rect.origin.y += 0.5
}
textView.change(pos: rect.origin, animated: animated)
if animated, let layer = backgroundView.layer {
let cornerAnimation = CABasicAnimation(keyPath: "cornerRadius")
cornerAnimation.timingFunction = CAMediaTimingFunction(name: .easeOut)
cornerAnimation.fromValue = layer.presentation()?.cornerRadius ?? layer.cornerRadius
cornerAnimation.toValue = isStreamable ? 8 : newSize.height / 2
cornerAnimation.duration = 0.2
layer.add(cornerAnimation, forKey: "cornerRadius")
}
needsLayout = true
}
override func copy() -> Any {
let view = ChatMessageAccessoryView(frame: frame)
view.updateText(self.stringValue, maxWidth: self.maxWidth, status: self.status, isStreamable: self.isStreamable, isCompact: self.isCompact)
return view
}
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
unread.setFrameSize(NSMakeSize(6, 6))
unread.layer?.cornerRadius = 3
unread.backgroundColor = isVideoMessage ? theme.chatServiceItemTextColor : .white
textView.isSelectable = false
textView.userInteractionEnabled = false
textView.disableBackgroundDrawing = true
addSubview(backgroundView)
addSubview(textView)
addSubview(progress)
addSubview(download)
addSubview(unread)
bufferingIndicator.background = .clear
bufferingIndicator.progressColor = isVideoMessage ? theme.chatServiceItemTextColor : .white
bufferingIndicator.layer?.cornerRadius = bufferingIndicator.frame.height / 2
// bufferingIndicator.lineWidth = 1.0
bufferingIndicator.isHidden = true
progress.isHidden = true
download.isHidden = true
download.autohighlight = false
progress.fetchControls = FetchControls(fetch: { [weak self] in
self?.cancelFetch?()
})
progressCap.layer?.borderColor = NSColor.white.withAlphaComponent(0.3).cgColor
progressCap.layer?.borderWidth = 2.0
progressCap.frame = NSMakeRect(2, 2, progress.frame.width - 4, progress.frame.height - 4)
progressCap.layer?.cornerRadius = progressCap.frame.width / 2
progress.addSubview(progressCap)
addSubview(bufferingIndicator)
download.set(handler: { [weak self] _ in
guard let `self` = self, let status = self.status else {return}
switch status {
case .Remote:
self.fetch?()
case .Fetching:
self.cancelFetch?()
default:
break
}
}, for: .Click)
set(handler: { [weak self] _ in
guard let `self` = self, let status = self.status else {return}
switch status {
case .Remote:
self.fetch?()
case .Fetching:
self.cancelFetch?()
default:
self.click?()
}
}, for: .Click)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-2.0 | a0ae927aae6e0b721c1225aed39e4b92 | 37.984436 | 672 | 0.60505 | 4.89448 | false | false | false | false |
Bijiabo/F-Client-iOS | F/F/Views/PublicCells/TextFieldTableViewCell.swift | 1 | 1811 | //
// TextFieldTableViewCell.swift
// RegisterAndLogIn
//
// Created by huchunbo on 15/10/26.
// Copyright © 2015年 TIDELAB. All rights reserved.
//
import UIKit
class TextFieldTableViewCell: PublicTableViewCell, UITextFieldDelegate {
override func awakeFromNib() {
super.awakeFromNib()
contentView.backgroundColor = UIColor.whiteColor()
let viewDict = [
"contentView": contentView
]
contentView.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-contentMarginLeft-[contentView]-contentMarginRight-|", options: NSLayoutFormatOptions(rawValue: 0) , metrics: ViewConstants.cellMetrics , views: viewDict)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-contentMarginTop-[contentView]-contentMarginBottom-|", options: NSLayoutFormatOptions(rawValue: 0) , metrics: ViewConstants.cellMetrics, views: viewDict)
addConstraints(horizontalConstraints)
addConstraints(verticalConstraints)
contentView.layer.cornerRadius = ViewConstants.cellCornerRadius
contentView.clipsToBounds = true
selectionStyle = UITableViewCellSelectionStyle.None
backgroundColor = UIColor.clearColor()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func textFieldDidBeginEditing(textField: UITextField) {
delegate?.activeTextField = textField
}
func textFieldDidEndEditing(textField: UITextField) {
delegate?.updateInputDataById(id, data: textField.text)
}
}
| gpl-2.0 | 391386ac8993345fdcdf9d3b79a9b0c8 | 34.45098 | 242 | 0.704646 | 5.889251 | false | false | false | false |
ITzTravelInTime/TINU | TINU/CreationProcess.swift | 1 | 4406 | /*
TINU, the open tool to create bootable macOS installers.
Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import AppKit
//TODO: Make this accept the multiple additional parameters init somehow
protocol CreationProcessSection {
var ref: CreationProcess { get }
init(reference: CreationProcess)
}
protocol UIRepresentable {
var displayName: String { get }
var icon: NSImage? { get }
var genericIcon: NSImage? { get }
var app: InstallerAppInfo? { get }
var part: Part? { get }
var size: UInt64 { get }
var path: String? { get }
}
protocol CreationProcessFSObject{
associatedtype T: UIRepresentable
var current: T! { get set }
var path: String! { get }
}
public class CreationProcess{
static var shared = CreationProcess()
required init(){
options = OptionsManager(reference: self)
app = InstallerAppManager(reference: self)
disk = DiskInfo(reference: self)
}
var maker : InstallMediaCreationManager! = nil
let process: Management = Management()
var disk : DiskInfo! = nil
var app : InstallerAppManager! = nil
var options: OptionsManager! = nil
internal var storedInstallerAppExecutableName: String! = nil
internal var storedExecutableName: String! = nil
func checkProcessReadySate(_ useDriveIcon: inout Bool) -> Bool {
if let sa = app.path{
print("Check installer app")
if !FileManager.default.directoryExists(atPath: sa){
print("Missing installer app in the specified directory")
return false
}
print("Installaer app that will be used is: " + sa)
}else{
print("Missing installer in memory")
return false
}
//InstallMediaCreationManager.shared.OtherOptionsBeforeformat(canFormat: &canFormat, useAPFS: &apfs)
if options.execution.canFormat{
print("A drive has been selected or a partition that needs format")
useDriveIcon = true
print("Everything is ready to start the installer creation process")
return true
}
print("Getting drive info about the used volume")
guard let s = disk.current.path else{
print("The selected volume mount point is empty")
return false
}
if FileManager.default.directoryExists(atPath: s){
print("Mount point: \(s)")
print("Everything is ready to start the installer creation process")
return true
}
guard let sb = disk.bSDDrive else{
print("Can't get the device id!!")
return false
}
guard let sd = sb.mountPoint() else{
print("Can't get the mount point!!")
return false
}
disk.current.path = sd
print("Corrected the name of the target volume")
print("Mount point: \(sd)")
print("Everything is ready to start the installer creation process")
return true
}
public var installMac: Bool = false{
didSet{
storedInstallerAppExecutableName = nil
storedExecutableName = nil
}
}
//this variable returns the name of the current executable used by the app
public var installerAppProcessExecutableName: String{
if let stored = storedInstallerAppExecutableName{
return stored
}
if installMac{
storedInstallerAppExecutableName = "startosinstall"
}
if #available(macOS 10.10, *){ if #available(macOS 10.11, *){ } else{
if app.info.supports(version: 17) ?? false{
storedInstallerAppExecutableName = "createinstallmedia_yosemite"
}
}}
storedInstallerAppExecutableName = storedInstallerAppExecutableName ?? "createinstallmedia"
return storedInstallerAppExecutableName!
}
public var executableName: String{
if let exec = storedExecutableName{
return exec
}
storedExecutableName = (app.current.status == .legacy) ? "asr" : installerAppProcessExecutableName
return storedExecutableName!
}
}
typealias cvm = CreationProcess
| gpl-2.0 | b4d325d92eb87bb71321c78b1b9bf81b | 26.36646 | 102 | 0.729914 | 3.827976 | false | false | false | false |
ITzTravelInTime/TINU | TINU/ChoseDriveViewController.swift | 1 | 12383 | /*
TINU, the open tool to create bootable macOS installers.
Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import Cocoa
class ChoseDriveViewController: ShadowViewController, ViewID {
let id: String = "ChoseDriveViewController"
@IBOutlet weak var scoller: HorizontalScrollview!
@IBOutlet weak var ok: NSButton!
@IBOutlet weak var spinner: NSProgressIndicator!
private var itemOriginY: CGFloat = 0
private let spacerID = "spacer"
private var empty: Bool = false{
didSet{
if self.empty{
scoller.drawsBackground = false
scoller.borderType = .noBorder
ok.title = TextManager.getViewString(context: self, stringID: "nextButtonFail")
ok.image = NSImage(named: NSImage.stopProgressTemplateName)
ok.isEnabled = true
return
}
//viewDidSetVibrantLook()
if let document = scoller.documentView{
if document.identifier?.rawValue == spacerID{
document.frame = NSRect(x: 0, y: 0, width: self.scoller.frame.width - 2, height: self.scoller.frame.height - 2)
if let content = document.subviews.first{
content.frame.origin = NSPoint(x: document.frame.width / 2 - content.frame.width / 2, y: 0)
}
self.scoller.documentView = document
}
}
ok.title = TextManager.getViewString(context: self, stringID: "nextButton")
ok.image = NSImage(named: NSImage.goRightTemplateName)
ok.isEnabled = false
if !look.isRecovery() {
scoller.drawsBackground = false
scoller.borderType = .noBorder
}else{
scoller.drawsBackground = true
scoller.borderType = .bezelBorder
}
}
}
@IBAction func refresh(_ sender: Any) {
updateDrives()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
//"Choose the Drive or the Partition to turn into a macOS Installer"
self.setTitleLabel(text: TextManager.getViewString(context: self, stringID: "title"))
self.showTitleLabel()
ok.title = TextManager.getViewString(context: self, stringID: "nextButton")
if !look.isRecovery(){
scoller.frame = CGRect.init(x: 0, y: scoller.frame.origin.y, width: self.view.frame.width, height: scoller.frame.height)
scoller.drawsBackground = false
scoller.borderType = .noBorder
}else{
scoller.frame = CGRect.init(x: 20, y: scoller.frame.origin.y, width: self.view.frame.width - 40, height: scoller.frame.height)
scoller.drawsBackground = true
scoller.borderType = .bezelBorder
}
/*
if sharedInstallMac{
titleLabel.stringValue = "Choose a drive or a partition to install macOS on"
}*/
self.scoller.scrollerStyle = .legacy
updateDrives()
}
func makeAndDisplayItem(_ item: CreationProcess.DiskInfo.DriveListItem, _ to: inout [DriveView]){
let man = FileManager.default
DispatchQueue.main.sync {
if item.partition != nil{
let d = item.partition!
let drivei = DriveView(frame: NSRect(x: 0, y: itemOriginY, width: DriveView.itemSize.width, height: DriveView.itemSize.height))
drivei.isEnabled = (item.state == .ok)
let prt = Part(bsdName: d.DeviceIdentifier, fileSystem: .other, isGUID: true, hasEFI: true, size: d.Size, isDrive: false, path: d.mountPoint, support: item.state)
prt.tmDisk = man.fileExists(atPath: d.mountPoint! + "/tmbootpicker.efi") || man.directoryExists(atPath: d.mountPoint! + "/Backups.backupdb")
log(" Item type: \(prt.isDrive ? "Drive" : "Partition")")
log(" Item display name is: \(prt.displayName)")
drivei.current = prt as UIRepresentable
to.append(drivei)
return
}
let d = item.disk
let drivei = DriveView(frame: NSRect(x: 0, y: itemOriginY, width: DriveView.itemSize.width, height: DriveView.itemSize.height))
drivei.isEnabled = (item.state == .ok)
let prt = Part(bsdName: d.DeviceIdentifier.driveID, fileSystem: .other, isGUID: d.content == .gUID, hasEFI: d.hasEFIPartition(), size: d.Size, isDrive: true, path: d.mountPoint, support: item.state)
prt.apfsBDSName = d.DeviceIdentifier
log(" Item type: \(prt.isDrive ? "Drive" : "Partition")")
log(" Item display name is: \(prt.displayName)")
drivei.current = prt as UIRepresentable
to.append(drivei)
}
}
private func updateDrives(){
print("--- Detectin usable drives and volumes")
self.scoller.isHidden = true
self.spinner.isHidden = false
self.spinner.startAnimation(self)
scoller.documentView = NSView()
print("Preparation for detection started")
ok.isEnabled = false
self.hideFailureImage()
self.hideFailureLabel()
self.hideFailureButtons()
//let man = FileManager.default
//Re-initialize the current disk
cvm.shared.disk = cvm.DiskInfo(reference: cvm.shared.disk.ref)
self.ok.isEnabled = false
itemOriginY = ((self.scoller.frame.height - 17) / 2) - (DriveView.itemSize.height / 2)
print("Preparation for detection finished")
//this code just does interpretation of the diskutil list -plist command
DispatchQueue.global(qos: .background).async {
print("Actual detection thread started")
var drives = [DriveView]()
/*
for item in cvm.shared.disk.getUsableDriveListNew() ?? []{
self.makeAndDisplayItem(item, &drives)
}
*/
for item in cvm.shared.disk.getUsableDriveListAll() ?? []{
self.makeAndDisplayItem(item, &drives)
}
DispatchQueue.main.sync {
self.scoller.hasVerticalScroller = false
let res = simulateNoUsableDrives ? true : (drives.count == 0)
self.empty = res
let set = res || Recovery.status
self.topView.isHidden = set
self.bottomView.isHidden = set
self.leftView.isHidden = set
self.rightView.isHidden = set
if res{
//fail :(
self.scoller.isHidden = true
if self.failureLabel == nil || self.failureImageView == nil || self.failureButtons.isEmpty{
self.defaultFailureImage()
//TextManager.getViewString(context: self, stringID: "agreeButtonFail")
self.setFailureLabel(text: TextManager.getViewString(context: self, stringID: "failureText"))
self.addFailureButton(buttonTitle: TextManager.getViewString(context: self, stringID: "failureButton"), target: self, selector: #selector(ChoseDriveViewController.openDetectStorageSuggestions), image: NSImage(named: NSImage.infoName))
}
self.showFailureImage()
self.showFailureLabel()
self.showFailureButtons()
}else{
let content = NSView(frame: NSRect(x: 0, y: 0, width: 0, height: self.scoller.frame.size.height - 17))
content.backgroundColor = NSColor.transparent
self.scoller.hasHorizontalScroller = true
var temp: CGFloat = 20
for d in drives{
d.frame.origin.x = temp
temp += d.frame.width + (( look != .recovery ) ? 15 : 0)
content.addSubview(d)
d.draw(d.bounds)
}
content.frame.size.width = temp + ((look != .recovery) ? 5 : 20)
//TODO: this is not ok for resizable windows
if content.frame.size.width < self.scoller.frame.width{
let spacer = NSView(frame: NSRect(x: 0, y: 0, width: self.scoller.frame.width - 2, height: self.scoller.frame.height - 2))
spacer.backgroundColor = NSColor.transparent
spacer.identifier = NSUserInterfaceItemIdentifier(rawValue: self.spacerID)
content.frame.origin = NSPoint(x: spacer.frame.width / 2 - content.frame.width / 2, y: 15 / 2)
spacer.addSubview(content)
self.scoller.documentView = spacer
spacer.draw(spacer.bounds)
}else{
self.scoller.documentView = content
content.draw(content.bounds)
}
if let documentView = self.scoller.documentView{
documentView.scroll(NSPoint.init(x: 0, y: documentView.bounds.size.height))
self.scoller.automaticallyAdjustsContentInsets = true
}
self.scoller.usesPredominantAxisScrolling = true
}
self.scoller.isHidden = false
self.spinner.isHidden = true
self.spinner.stopAnimation(self)
}
}
}
private var tmpWin: GenericViewController!
@objc func openDetectStorageSuggestions(){
//tmpWin = nil
tmpWin = UIManager.shared.storyboard.instantiateController(withIdentifier: "DriveDetectionInfoVC") as? GenericViewController
if tmpWin != nil{
self.presentAsSheet(tmpWin)
}
}
@IBAction func goBack(_ sender: Any) {
if UIManager.shared.showLicense{
let _ = swapCurrentViewController("License")
}else{
let _ = swapCurrentViewController("Info")
}
tmpWin = nil
}
@IBAction func next(_ sender: Any) {
if !empty{
let parseList = ["{diskName}" : cvm.shared.disk.current.driveName, "{partitionName}" : cvm.shared.disk.current.displayName]
if cvm.shared.disk.warnForTimeMachine{
if !dialogGenericWithManagerBool(self, name: "formatDialogTimeMachine", parseList: parseList){
return
}
}
if cvm.shared.disk.shouldErase{
if !dialogGenericWithManagerBool(self, name: "formatDialog", parseList: parseList){
return
}
}
tmpWin = nil
let _ = swapCurrentViewController("ChoseApp")
}else{
NSApplication.shared.terminate(sender)
}
}
/*
private func checkDriveSize(_ cc: [ArraySlice<String>], _ isDrive: Bool) -> Bool{
var c = cc
c.remove(at: c.count - 1)
var sz: UInt64 = 0
if c.count == 1{
let f: String = (c.last?.last!)!
var cl = c.last!
cl.remove(at: cl.index(before: cl.endIndex))
let ff: String = cl.last!
c.removeAll()
c.append([ff, f])
}
if var n = c.last?.first{
if isDrive{
n.remove(at: n.startIndex)
}else{
let s = String(describing: n.first)
if s == "*" || s == "+"{
print(" volume size is not fixed, skipping it")
return false
}
}
if let s = UInt64(n){
sz = s
}
}
if let n = c.last?.last{
switch n{
case "KB":
sz *= get1024Pow(exp: 1)
break
case "MB":
sz *= get1024Pow(exp: 2)
break
case "GB":
sz *= get1024Pow(exp: 3)
break
case "TB":
sz *= get1024Pow(exp: 4)
break
case "PB":
sz *= get1024Pow(exp: 5)
break
default:
if isDrive{
print(" this drive has an unknown size unit, skipping this drive")
}else{
print(" volume size unit unkown, skipping this volume")
}
return false
}
}
var minSize: UInt64 = 7 * get1024Pow(exp: 3) // 7 gb
if sharedInstallMac{
minSize = 20 * get1024Pow(exp: 3) // 20 gb
}
//if we are in a testing situation, size of the drive is not so much important
if simulateCreateinstallmediaFail != nil{
minSize = get1024Pow(exp: 3) // 1 gb
}
if sz <= minSize{
if isDrive{
print(" this drive is too small to be used for a macOS installer, skipping this drive")
}else{
print(" this volume is too small for a macOS installer")
}
return false
}
return true
}
private func get1024Pow(exp: Float) -> UInt64{
return UInt64(pow(1024.0, exp))
}*/
}
| gpl-2.0 | 5cfc98f5a4487c4dfc56ee3cce269cbc | 29.128954 | 240 | 0.632642 | 3.725331 | false | false | false | false |
feiin/VPNOn | VPNOnWatchKitExtension/GlanceController.swift | 20 | 2124 | //
// GlanceController.swift
// VPN On WatchKit Extension
//
// Created by Lex Tang on 3/30/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import WatchKit
import Foundation
import VPNOnKit
class GlanceController: VPNInterfaceController {
@IBOutlet weak var tableView: WKInterfaceTable!
override func willActivate() {
super.willActivate()
loadVPNs()
}
func loadVPNs() {
if vpns.count > 0 {
self.tableView.setNumberOfRows(vpns.count, withRowType: "VPNRow")
for i in 0...vpns.count-1 {
if let row = self.tableView.rowControllerAtIndex(i) as! VPNRowInGlance? {
let vpn = vpns[i]
if let countryCode = vpn.countryCode {
row.flag.setImageNamed(countryCode)
} else {
row.flag.setImageNamed("unknow")
}
row.titleLabel.setText(vpn.title)
row.latency = LTPingQueue.sharedQueue.latencyForHostname(vpn.server)
let connected = Bool(VPNManager.sharedManager.status == .Connected && vpn.ID == selectedID)
let backgroundColor = connected ? UIColor(red:0, green:0.6, blue:1, alpha:1) : UIColor(white: 1.0, alpha: 0.2)
row.group.setBackgroundColor(backgroundColor)
}
}
} else {
self.tableView.setNumberOfRows(1, withRowType: "HintRow")
}
}
// MARK: - Notification
func pingDidUpdate(notification: NSNotification) {
loadVPNs()
}
func coreDataDidSave(notification: NSNotification) {
VPNDataManager.sharedManager.managedObjectContext?.mergeChangesFromContextDidSaveNotification(notification)
loadVPNs()
}
func VPNStatusDidChange(notification: NSNotification?) {
loadVPNs()
if VPNManager.sharedManager.status == .Disconnected {
LTPingQueue.sharedQueue.restartPing()
}
}
}
| mit | caeed704c7702a93084b09bd314afdb9 | 30.235294 | 130 | 0.572505 | 4.905312 | false | false | false | false |
rduan8/Aerial | Aerial/Source/Models/ManifestLoader.swift | 1 | 3651 | //
// ManifestLoader.swift
// Aerial
//
// Created by John Coates on 10/28/15.
// Copyright © 2015 John Coates. All rights reserved.
//
import Foundation
import ScreenSaver
typealias manifestLoadCallback = ([AerialVideo]) -> (Void);
class ManifestLoader {
static let instance:ManifestLoader = ManifestLoader();
let defaults:NSUserDefaults = ScreenSaverDefaults(forModuleWithName: "com.JohnCoates.Aerial")! as ScreenSaverDefaults
var callbacks = [manifestLoadCallback]();
var loadedManifest = [AerialVideo]();
var playedVideos = [AerialVideo]();
func addCallback(callback:manifestLoadCallback) {
if (loadedManifest.count > 0) {
callback(loadedManifest);
}
else {
callbacks.append(callback);
}
}
func randomVideo() -> AerialVideo? {
let shuffled = loadedManifest.shuffle();
for video in shuffled {
let possible = defaults.objectForKey(video.id);
if let possible = possible as? NSNumber {
if possible.boolValue == false {
continue;
}
}
return video;
}
// nothing available??? return first thing we find
return shuffled.first;
}
init() {
// start loading right away!
let completionHandler = { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if let error = error {
NSLog("Aerial Error Loading Manifest: \(error)");
return;
}
guard let data = data else {
NSLog("Couldn't load manifest!");
return;
}
var videos = [AerialVideo]();
do {
let batches = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! Array<NSDictionary>;
for batch:NSDictionary in batches {
let assets = batch["assets"] as! Array<NSDictionary>;
for item in assets {
let url = item["url"] as! String;
let name = item["accessibilityLabel"] as! String;
let timeOfDay = item["timeOfDay"] as! String;
let id = item["id"] as! String;
let type = item["type"] as! String;
if (type != "video") {
continue;
}
let video = AerialVideo(id: id, name: name, type: type, timeOfDay: timeOfDay, url: url);
videos.append(video)
}
}
self.loadedManifest = videos;
// callbacks
for callback in self.callbacks {
callback(videos);
}
self.callbacks.removeAll()
}
catch {
NSLog("Aerial: Error retrieving content listing.");
return;
}
};
let url = NSURL(string: "http://a1.phobos.apple.com/us/r1000/000/Features/atv/AutumnResources/videos/entries.json");
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler:completionHandler);
task.resume();
}
} | mit | 26b41cbae405568346d5f10b54f4f517 | 32.190909 | 149 | 0.482466 | 5.738994 | false | false | false | false |
devand123/cordova-plugin-opentok | src/ios/VideoView.swift | 1 | 2084 | //
// VideoViewController.swift
// roller
//
// Created by Devin Andrews on 12/16/14.
//
//
import Foundation
import UIKit
import AVFoundation
@objc(Video) public class Video : NSObject {
var captureSession = AVCaptureSession()
var previewLayer : AVCaptureVideoPreviewLayer?
var captureDevice : AVCaptureDevice?
var previousInput : AVCaptureDeviceInput?
public func getVideo(view: UIView) {
let devices = AVCaptureDevice.devices()
for device in devices {
if(device.hasMediaType(AVMediaTypeVideo)) {
if(device.position == AVCaptureDevicePosition.Back) {
captureDevice = device as? AVCaptureDevice
}
}
}
if captureDevice != nil {
var err : NSError? = nil
previousInput = AVCaptureDeviceInput(device: captureDevice, error: &err)
captureSession.addInput(previousInput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.name = "VideoView"
view.layer.insertSublayer(previewLayer, atIndex: 0)
previewLayer?.frame = view.layer.frame
var bounds:CGRect = view.layer.bounds
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer?.bounds = bounds
previewLayer?.position = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds))
println(captureSession)
captureSession.startRunning()
}
}
public func stopRunning() {
var err : NSError? = nil
println("stopRunning() called")
println(captureSession.running)
captureSession.removeInput(previousInput)
// captureSession.stopRunning()
// captureSession.stopRunning()
// captureSession.startRunning()
if err != nil {
println("Error occurred on stopRunning()")
}
}
} | mit | aa99999496fba977292c30bbae23e175 | 30.119403 | 94 | 0.590691 | 5.971347 | false | false | false | false |
helenmasters/elephantObjectStorage | Sources/Application/Application.swift | 1 | 1404 | import Foundation
import Kitura
import LoggerAPI
import Configuration
import CloudFoundryConfig
import SwiftMetrics
import SwiftMetricsDash
import BluemixObjectStorage
public let router = Router()
public let manager = ConfigurationManager()
public var port: Int = 8080
internal var objectStorage: ObjectStorage?
public func initialize() throws {
manager.load(file: "config.json", relativeFrom: .project)
.load(.environmentVariables)
port = manager.port
let sm = try SwiftMetrics()
let _ = try SwiftMetricsDash(swiftMetricsInstance : sm, endpoint: router)
let objectStorageService = try manager.getObjectStorageService(name: "elephant-Object-Storage-e7a3")
objectStorage = ObjectStorage(service: objectStorageService)
try objectStorage?.connectSync(service: objectStorageService)
objectStorage!.retrieveContainersList { (error, containers) in
if let error = error {
print("retrieve containers list error :: \(error)")
} else {
print("retrieve containers list success :: \(containers?.description)")
}
}
router.all("/*", middleware: BodyParser())
router.all("/", middleware: StaticFileServer())
initializeSwaggerRoute(path: ConfigurationManager.BasePath.project.path + "/definitions/elephant.yaml")
initializeProductRoutes()
}
public func run() throws {
Kitura.addHTTPServer(onPort: port, with: router)
Kitura.run()
}
| mit | 50e1eb8b67121bc0a040cdd0c2994bee | 28.87234 | 107 | 0.747863 | 4.32 | false | true | false | false |
Tim77277/WizardUIKit | WizardUIKit/DatePicker.swift | 1 | 2522 | /**********************************************************
MIT License
WizardUIKit
Copyright (c) 2016 Wei-Ting Lin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***********************************************************/
import UIKit
public struct WizardDatePickerAlert {
public var titleLabel: WizardLabel
public var todayButton: WizardButton
public var doneButton: WizardButton
public var animation: WizardAnimation
public var picker: WizardDatePicker
public var backgroundColor: UIColor
public init() {
backgroundColor = .white
titleLabel = WizardLabel(text: "Title", textColor: .black, font: UIFont.boldSystemFont(ofSize: 18))
doneButton = WizardButton(text: "Done", textColor: UIColor.WizardBlueColor(), backgroundColor: .clear, cornerRadius: 0)
todayButton = WizardButton(text: "Today", textColor: UIColor.WizardBlueColor(), backgroundColor: .clear, cornerRadius: 0)
animation = WizardAnimation(direction: .slideUp, duration: 0.3)
picker = WizardDatePicker()
}
public init(backgroundColor: UIColor, titleLabel: WizardLabel, todayButton: WizardButton, doneButton: WizardButton, picker: WizardDatePicker, animation: WizardAnimation) {
self.backgroundColor = backgroundColor
self.titleLabel = titleLabel
self.todayButton = todayButton
self.doneButton = doneButton
self.animation = animation
self.picker = picker
}
}
| mit | 07f7b6536a9e4b307cbe064b88780225 | 45.703704 | 176 | 0.698255 | 5.126016 | false | false | false | false |
alexcomu/swift3-tutorial | 02-swift-introduction/objectOrientedProgramming.playground/Contents.swift | 1 | 1979 | //: Playground - noun: a place where people can play
import UIKit
class Person{
var firstname = "Alex"
var lastname = "Comu"
private var _age = 0
var age: Int{
return _age
}
func setAge(newAge: Int) {
self._age = newAge
}
var fullname: String{
return "\(firstname) \(lastname) is \(age)"
}
}
var alex = Person()
print(alex.fullname)
alex.setAge(newAge: 27)
print(alex.fullname)
func changeAgeFromObject(person: Person, age: Int){
person.setAge(newAge: age)
}
changeAgeFromObject(person: alex, age: 30)
print(alex.fullname)
// ****************************************** //
// Inheritance
class Sport{
var name = "basic name"
init(){
print("I'm sport class")
}
func someRandomFunc(){
}
}
class Football: Sport{
// override the init class to change the name
override init(){
super.init() // call my father init method
print("I'm football class")
name = "football"
}
// adding new vars
var teams = [String]()
override func someRandomFunc() {
print("Do something different..")
}
}
var football = Football()
// ****************************************** //
// Polymorphism
/*
// bad way
class Rectangle{
var area: Double?
func calculateArea(length: Double, width: Double){
area = length * width
}
}
class Triangle{
var area: Double?
func calculateArea(base: Double, height: Double){
area = base * height / 2
}
}
*/
// this is the good way
class Shape{
var area: Double?
func calculateArea(valA: Double, valB: Double){
// do nothing
}
}
class Triangle: Shape{
override func calculateArea(valA: Double, valB: Double) {
area = (valA * valB) / 2
}
}
class Rectangle: Shape{
override func calculateArea(valA: Double, valB: Double) {
area = (valA * valB)
}
}
| mit | 6d369c8dae0b2831e7b6a5ba5fd0f268 | 15.221311 | 61 | 0.553815 | 3.813102 | false | false | false | false |
danielsaidi/KeyboardKit | Sources/KeyboardKit/UIKit/Gestures/UIRepeatingGestureRecognizer.swift | 1 | 3712 | //
// UIRepeatingGestureRecognizer.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2019-05-30.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import UIKit
/**
This gesture recognizer will trigger a certain action, once
after an `initialDelay` and repeating every `repeatInterval`
until the user releases her/his finger. It's a good gesture
for some actions, like `backspace`.
This gesture does not cancel any other gestures, so you can
use it together with taps and long presses.
*/
open class UIRepeatingGestureRecognizer: UIGestureRecognizer {
// MARK: - Initialization
public init(
initialDelay: TimeInterval = 0.8,
repeatInterval: TimeInterval = 0.1,
action: @escaping () -> Void) {
self.action = action
self.initialDelay = initialDelay
self.repeatInterval = repeatInterval
super.init(target: nil, action: nil)
self.delegate = self
}
// MARK: - Properties
private let action: () -> Void
private let initialDelay: TimeInterval
private var isActive = false
private let repeatInterval: TimeInterval
internal var timer: Timer?
// MARK: - State
open override var state: UIGestureRecognizer.State {
didSet {
switch state {
case .began: startGesture()
case .cancelled, .ended, .failed: stopGesture()
case .changed, .possible: break
@unknown default: break
}
}
}
// MARK: - Touch Handling
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
state = .began
}
open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
if state == .cancelled { return }
if state == .ended { return }
if state == .failed { return }
state = .changed
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesCancelled(touches, with: event)
state = .cancelled
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesEnded(touches, with: event)
state = .ended
}
// MARK: - Internal Functions
func delay(seconds: TimeInterval, function: @escaping () -> Void) {
let milliseconds = Int(seconds * 1000)
let interval: DispatchTimeInterval = .milliseconds(milliseconds)
DispatchQueue.main.asyncAfter(deadline: .now() + interval, execute: function)
}
func startGesture() {
isActive = true
delay(seconds: initialDelay) { [weak self] in
guard self?.isActive == true else { return }
self?.action()
self?.startTimer()
}
}
func stopGesture() {
isActive = false
timer?.invalidate()
timer = nil
}
}
// MARK: - Private Functions
private extension UIRepeatingGestureRecognizer {
func startTimer() {
timer = Timer.scheduledTimer(withTimeInterval: repeatInterval, repeats: true) { [weak self] timer in
guard self?.isActive == true else { return timer.invalidate() }
self?.action()
}
}
}
// MARK: - UIGestureRecognizerDelegate
extension UIRepeatingGestureRecognizer: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| mit | 4e88e701708e6dbd29927fb77265e359 | 27.328244 | 164 | 0.625977 | 5.021651 | false | false | false | false |
calebkleveter/BluetoothKit | Source/BKRemotePeer.swift | 2 | 2553 | //
// BluetoothKit
//
// Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public protocol BKRemotePeerDelegate: class {
/**
Called when the remote peer sent data.
- parameter remotePeripheral: The remote peripheral that sent the data.
- parameter data: The data it sent.
*/
func remotePeer(_ remotePeer: BKRemotePeer, didSendArbitraryData data: Data)
}
public func == (lhs: BKRemotePeer, rhs: BKRemotePeer) -> Bool {
return (lhs.identifier == rhs.identifier)
}
public class BKRemotePeer: Equatable {
/// A unique identifier for the peer, derived from the underlying CBCentral or CBPeripheral object, or set manually.
public let identifier: UUID
public weak var delegate: BKRemotePeerDelegate?
internal var configuration: BKConfiguration?
private var data: Data?
init(identifier: UUID) {
self.identifier = identifier
}
internal var maximumUpdateValueLength: Int {
return 20
}
internal func handleReceivedData(_ receivedData: Data) {
if receivedData == configuration!.endOfDataMark {
if let finalData = data {
delegate?.remotePeer(self, didSendArbitraryData: finalData)
}
data = nil
return
}
if self.data != nil {
self.data?.append(receivedData)
return
}
self.data = receivedData
}
}
| mit | ad5d5f7c750ec4b194fffba3413c944e | 33.972603 | 120 | 0.695652 | 4.650273 | false | false | false | false |
xiaowen707447083/startDemo | LanouCProject/LanouCProject/src/zhihu/ZhiHuDetailController.swift | 1 | 2307 | //
// ZhiHuDetailController.swift
// LanouCProject
//
// Created by lanou on 15/8/22.
// Copyright (c) 2015年 lanou3g. All rights reserved.
//
import UIKit
class ZhiHuDetailController: MyBaseViewController {
var urlStr:String!
override func viewDidLoad() {
super.viewDidLoad()
var webView:UIWebView = UIWebView(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height))
self.view.addSubview(webView)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
var htmlData:NSData = NSData(contentsOfURL:NSURL(string:self.urlStr)!)!
var xpathParser:TFHpple = TFHpple(HTMLData:htmlData)
var aArray:NSArray = xpathParser.searchWithXPathQuery("//div")
var result:String!
if aArray.count>0 {
for var i=0;i<aArray.count;i++ {
var aElement:TFHppleElement = aArray[i] as TFHppleElement
var dic = aElement.attributes
if ( dic["class"] != nil ){
if dic["class"]as String == "main-wrap content-wrap"{
var width = self.view.frame.size.width
result = aElement.raw.stringByReplacingOccurrencesOfString("<img", withString: "<img width=\"\(width)\"")
//有些小图 <img class="avatar"
result = aElement.raw.stringByReplacingOccurrencesOfString("<img width=\"\(width)\" class=\"avatar\"", withString: "<img class=\"avatar\"")
// println(result)
}
}
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// self.requestData()//请求数据
webView.loadHTMLString(result, baseURL: nil)
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | dcfbccdc6f76b6d6d99a09e6ae949234 | 31.7 | 167 | 0.505024 | 5.109375 | false | false | false | false |
the-grid/Disc | DiscTests/Models/ScopeSpec.swift | 1 | 2985 | import Argo
import Disc
import Nimble
import Ogra
import Quick
class ScopeSpec: QuickSpec {
override func spec() {
describe("raw values") {
describe("balance") {
it("should have the correct raw value") {
expect(Scope.Balance.rawValue).to(equal("balance"))
}
}
describe("content management") {
it("should have the correct raw value") {
expect(Scope.ContentManagement.rawValue).to(equal("content_management"))
}
}
describe("content management") {
it("should have the correct raw value") {
expect(Scope.CTAManagement.rawValue).to(equal("cta_management"))
}
}
describe("GitHub (public)") {
it("should have the correct raw value") {
expect(Scope.GitHubPublic.rawValue).to(equal("github"))
}
}
describe("GitHub (private)") {
it("should have the correct raw value") {
expect(Scope.GitHubPrivate.rawValue).to(equal("github_private"))
}
}
describe("payment") {
it("should have the correct raw value") {
expect(Scope.Payment.rawValue).to(equal("payment"))
}
}
describe("share") {
it("should have the correct raw value") {
expect(Scope.Share.rawValue).to(equal("share"))
}
}
describe("update profile") {
it("should have the correct raw value") {
expect(Scope.UpdateProfile.rawValue).to(equal("update_profile"))
}
}
describe("website management") {
it("should have the correct raw value") {
expect(Scope.WebsiteManagement.rawValue).to(equal("website_management"))
}
}
}
describe("decoding") {
it("should produce a Scope") {
let rawValue = "update_profile"
let json = JSON.String(rawValue)
guard let decoded = Scope.decode(json).value else {
return XCTFail("Unable to decode JSON: \(json)")
}
let scope = Scope(rawValue: rawValue)
expect(decoded).to(equal(scope))
}
}
describe("encoding") {
it("should produce JSON") {
let rawValue = "update_profile"
let scope = Scope(rawValue: rawValue)
let encoded = scope.encode()
let json = JSON.String(rawValue)
expect(encoded).to(equal(json))
}
}
}
}
| mit | b9086fc0c4ef4b7bdcff2e3d0473e36d | 33.310345 | 92 | 0.457956 | 5.477064 | false | false | false | false |
KPRSN/Lr-backup | Lr backup/PreferencesViewController.swift | 1 | 2606 | //
// PreferencesViewController.swift
// Lr backup
//
// Created by Karl Persson on 2015-08-11.
// Copyright (c) 2015 Karl Persson. All rights reserved.
//
import Cocoa
class PreferencesViewController: NSViewController {
var enableSSH: Int! {
didSet {
if enableSSH > 0 {
host.enabled = true
user.enabled = true
hostDesc.textColor = NSColor.blackColor()
userDesc.textColor = NSColor.blackColor()
}
else {
host.enabled = false
user.enabled = false
hostDesc.textColor = NSColor.grayColor()
userDesc.textColor = NSColor.grayColor()
}
}
}
@IBOutlet weak var source: NSTextField!
@IBOutlet weak var destination: NSTextField!
@IBOutlet weak var ssh: NSButton!
@IBOutlet weak var host: NSTextField!
@IBOutlet weak var user: NSTextField!
@IBOutlet weak var lrpreviews: NSButton!
@IBOutlet weak var hiddenFiles: NSButton!
@IBOutlet weak var compression: NSButton!
@IBOutlet weak var hostDesc: NSTextField!
@IBOutlet weak var userDesc: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
loadDefaults()
}
// Load default settings
func loadDefaults() {
source.stringValue = Defaults.source!
destination.stringValue = Defaults.destination!
ssh.state = Int(Defaults.ssh!)
host.stringValue = Defaults.host!
user.stringValue = Defaults.user!
lrpreviews.state = Int(Defaults.lrpreviews!)
hiddenFiles.state = Int(Defaults.hiddenFiles!)
compression.state = Int(Defaults.compression!)
enableSSH = ssh.state
}
// Save default settings
func saveDefaults() {
// Reset last backup date if source, destination or host have been changed
if (Defaults.source != source.stringValue ||
Defaults.destination != destination.stringValue ||
Defaults.ssh != Bool(ssh.state) ||
Defaults.host != host.stringValue ||
Defaults.user != user.stringValue) {
Defaults.lastBackup = nil
}
Defaults.source = source.stringValue
Defaults.destination = destination.stringValue
Defaults.ssh = Bool(ssh.state)
Defaults.host = host.stringValue
Defaults.user = user.stringValue
Defaults.lrpreviews = Bool(lrpreviews.state)
Defaults.hiddenFiles = Bool(hiddenFiles.state)
Defaults.compression = Bool(compression.state)
}
@IBAction func sshClicked(sender: NSButton?) {
enableSSH = ssh.state
}
@IBAction func sshHelp(sender: NSButton?) {
// Open up a help website for setting up SSH authentication
NSWorkspace.sharedWorkspace().openURL(NSURL(string: "https://www.digitalocean.com/community/tutorials/ssh-essentials-working-with-ssh-servers-clients-and-keys")!)
}
}
| mit | 6ef0b2de00ba6ecf90e7b4bcff830927 | 27.021505 | 164 | 0.722563 | 3.728183 | false | false | false | false |
andrew-anlu/TLImageSpring-swift | Example/TLImageSpring/CustomTableView.swift | 1 | 1905 | //
// CustomTableView.swift
// TLImageSpring
//
// Created by Andrew on 2017/1/6.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import UIKit
class CustomTableView: UITableView,UITableViewDelegate,UITableViewDataSource {
var arrayData = ["Normal loading style"]
public var navigationController:UINavigationController?
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.delegate = self
self.dataSource = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil{
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
}
cell?.textLabel?.text = arrayData[indexPath.item]
cell?.accessoryType = .disclosureIndicator
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let normalVc = NormalController()
self.navigationController?.pushViewController(normalVc, animated: true)
}
}
| mit | b7602df70a13aa238e35f82372c7217c | 26.565217 | 100 | 0.64511 | 5.225275 | false | false | false | false |
gribozavr/swift | test/attr/attr_escaping.swift | 2 | 9647 | // RUN: %target-typecheck-verify-swift -swift-version 4
@escaping var fn : () -> Int = { 4 } // expected-error {{attribute can only be applied to types, not declarations}}
func paramDeclEscaping(@escaping fn: (Int) -> Void) {} // expected-error {{attribute can only be applied to types, not declarations}}
func wrongParamType(a: @escaping Int) {} // expected-error {{@escaping attribute only applies to function types}}
func conflictingAttrs(_ fn: @noescape @escaping () -> Int) {} // expected-error {{unknown attribute 'noescape'}}
func takesEscaping(_ fn: @escaping () -> Int) {} // ok
func callEscapingWithNoEscape(_ fn: () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }}
takesEscaping(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
// This is a non-escaping use:
let _ = fn
}
typealias IntSugar = Int
func callSugared(_ fn: () -> IntSugar) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{24-24=@escaping }}
takesEscaping(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
struct StoresClosure {
var closure : () -> Int
init(_ fn: () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{14-14=@escaping }}
closure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
}
func arrayPack(_ fn: () -> Int) -> [() -> Int] {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{24-24=@escaping }}
return [fn] // expected-error{{using non-escaping parameter 'fn' in a context expecting an @escaping closure}}
}
func dictPack(_ fn: () -> Int) -> [String: () -> Int] {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{23-23=@escaping }}
return ["ultimate answer": fn] // expected-error{{using non-escaping parameter 'fn' in a context expecting an @escaping closure}}
}
func arrayPack(_ fn: @escaping () -> Int, _ fn2 : () -> Int) -> [() -> Int] {
// expected-note@-1{{parameter 'fn2' is implicitly non-escaping}} {{53-53=@escaping }}
return [fn, fn2] // expected-error{{using non-escaping parameter 'fn2' in a context expecting an @escaping closure}}
}
}
func takesEscapingBlock(_ fn: @escaping @convention(block) () -> Void) {
fn()
}
func callEscapingWithNoEscapeBlock(_ fn: () -> Void) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{42-42=@escaping }}
takesEscapingBlock(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
func takesEscapingAutoclosure(_ fn: @autoclosure @escaping () -> Int) {}
func callEscapingAutoclosureWithNoEscape(_ fn: () -> Int) {
takesEscapingAutoclosure(1+1)
}
let foo: @escaping (Int) -> Int // expected-error{{@escaping attribute may only be used in function parameter position}} {{10-20=}}
struct GenericStruct<T> {}
func misuseEscaping(_ a: @escaping Int) {} // expected-error{{@escaping attribute only applies to function types}} {{26-36=}}
func misuseEscaping(_ a: (@escaping Int)?) {} // expected-error{{@escaping attribute only applies to function types}} {{27-36=}}
func misuseEscaping(opt a: @escaping ((Int) -> Int)?) {} // expected-error{{@escaping attribute only applies to function types}} {{28-38=}}
// expected-note@-1{{closure is already escaping in optional type argument}}
func misuseEscaping(_ a: (@escaping (Int) -> Int)?) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-36=}}
// expected-note@-1{{closure is already escaping in optional type argument}}
func misuseEscaping(nest a: (((@escaping (Int) -> Int))?)) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{32-41=}}
// expected-note@-1{{closure is already escaping in optional type argument}}
func misuseEscaping(iuo a: (@escaping (Int) -> Int)!) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{29-38=}}
// expected-note@-1{{closure is already escaping in optional type argument}}
func misuseEscaping(_ a: Optional<@escaping (Int) -> Int>, _ b: Int) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{35-44=}}
func misuseEscaping(_ a: (@escaping (Int) -> Int, Int)) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-36=}}
func misuseEscaping(_ a: [@escaping (Int) -> Int]) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-36=}}
func misuseEscaping(_ a: [@escaping (Int) -> Int]?) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-36=}}
func misuseEscaping(_ a: [Int : @escaping (Int) -> Int]) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{33-43=}}
func misuseEscaping(_ a: GenericStruct<@escaping (Int) -> Int>) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{40-49=}}
func takesEscapingGeneric<T>(_ fn: @escaping () -> T) {}
func callEscapingGeneric<T>(_ fn: () -> T) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{35-35=@escaping }}
takesEscapingGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
class Super {}
class Sub: Super {}
func takesEscapingSuper(_ fn: @escaping () -> Super) {}
func callEscapingSuper(_ fn: () -> Sub) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{30-30=@escaping }}
takesEscapingSuper(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
func takesEscapingSuperGeneric<T: Super>(_ fn: @escaping () -> T) {}
func callEscapingSuperGeneric(_ fn: () -> Sub) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }}
takesEscapingSuperGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
func callEscapingSuperGeneric<T: Sub>(_ fn: () -> T) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{45-45=@escaping }}
takesEscapingSuperGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
func testModuloOptionalness() {
var iuoClosure: (() -> Void)! = nil
func setIUOClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{28-28=@escaping }}
iuoClosure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
}
var iuoClosureExplicit: (() -> Void)!
func setExplicitIUOClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{36-36=@escaping }}
iuoClosureExplicit = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
}
var deepOptionalClosure: (() -> Void)???
func setDeepOptionalClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }}
deepOptionalClosure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
}
}
// Check that functions in vararg position are @escaping
func takesEscapingFunction(fn: @escaping () -> ()) {}
func takesArrayOfFunctions(array: [() -> ()]) {}
func takesVarargsOfFunctions(fns: () -> ()...) {
takesArrayOfFunctions(array: fns)
for fn in fns {
takesEscapingFunction(fn: fn)
}
}
func takesVarargsOfFunctionsExplicitEscaping(fns: @escaping () -> ()...) {} // expected-error{{@escaping attribute may only be used in function parameter position}}
func takesNoEscapeFunction(fn: () -> ()) { // expected-note {{parameter 'fn' is implicitly non-escaping}}
takesVarargsOfFunctions(fns: fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
class FooClass {
var stored : Optional<(()->Int)->Void> = nil
var computed : (()->Int)->Void {
get { return stored! }
set(newValue) { stored = newValue } // ok
}
var computedEscaping : (@escaping ()->Int)->Void {
get { return stored! }
set(newValue) { stored = newValue } // expected-error{{assigning non-escaping parameter 'newValue' to an @escaping closure}}
// expected-note@-1 {{parameter 'newValue' is implicitly non-escaping}}
}
}
// A call of a closure literal should be non-escaping
func takesInOut(y: inout Int) {
_ = {
y += 1 // no-error
}()
_ = ({
y += 1 // no-error
})()
_ = { () in
y += 1 // no-error
}()
_ = ({ () in
y += 1 // no-error
})()
_ = { () -> () in
y += 1 // no-error
}()
_ = ({ () -> () in
y += 1 // no-error
})()
}
class HasIVarCaptures {
var x: Int = 0
func method() {
_ = {
x += 1 // no-error
}()
_ = ({
x += 1 // no-error
})()
_ = { () in
x += 1 // no-error
}()
_ = ({ () in
x += 1 // no-error
})()
_ = { () -> () in
x += 1 // no-error
}()
_ = ({ () -> () in
x += 1 // no-error
})()
}
}
// https://bugs.swift.org/browse/SR-9760
protocol SR_9760 {
typealias F = () -> Void
typealias G<T> = (T) -> Void
func foo<T>(_: T, _: @escaping F) // Ok
func bar<T>(_: @escaping G<T>) // Ok
}
extension SR_9760 {
func fiz<T>(_: T, _: @escaping F) {} // Ok
func baz<T>(_: @escaping G<T>) {} // Ok
}
// SR-9178
func foo<T>(_ x: @escaping T) {} // expected-error 1{{@escaping attribute only applies to function types}}
| apache-2.0 | 38c820f306af7f233e2034be159d7429 | 40.761905 | 171 | 0.653156 | 3.752236 | false | false | false | false |
ta2yak/loqui | loqui/Models/ReplyChats.swift | 1 | 1667 | //
// Room.swift
// loqui
//
// Created by Kawasaki Tatsuya on 2017/07/13.
// Copyright © 2017年 Kawasaki Tatsuya. All rights reserved.
//
import Alamofire
import ObjectMapper
import AlamofireObjectMapper
import Firebase
import RxSwift
import PromiseKit
class ReplyChats: Mappable{
var author:String = ""
var lastMessage:String = ""
var roomId:String = ""
var text:String = ""
var title:String = ""
var unread:Bool = false
var users:[String] = []
required init() {}
required init?(map: Map) {}
// Mappable
func mapping(map: Map) {
author <- map["author"]
lastMessage <- map["lastMessage"]
roomId <- map["roomId"]
text <- map["text"]
title <- map["title"]
unread <- map["unread"]
users <- map["users"]
}
static func fetch(uid:String) -> Promise<[ReplyChats]> {
return Promise<[ReplyChats]> { resolve, reject in
let ref = Database.database().reference().child("reply-chats").child(uid)
ref.observeSingleEvent(of: .value, with: { (snapshots) in
var replyChats = [ReplyChats]()
snapshots.children.forEach({ (snapshot) in
if let json = (snapshot as! DataSnapshot).value as? [String : AnyObject] {
guard let chat = Mapper<ReplyChats>().map(JSON: json) else { return }
replyChats.append(chat)
}
})
resolve(replyChats)
}, withCancel: { (error) in
})
}
}
}
| mit | b5abe7fe0da419c7b8d18e508dfdc555 | 25.412698 | 94 | 0.528846 | 4.622222 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 1.playgroundbook/Contents/Chapters/Document7.playgroundchapter/Pages/Exercise4.playgroundpage/Sources/SetUp.swift | 1 | 5195 | //
// SetUp.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import Foundation
// MARK: Globals
let world: GridWorld = loadGridWorld(named: "7.7")
let actor = Actor()
public func playgroundPrologue() {
placeActor()
placeItems()
// Must be called in `playgroundPrologue()` to update with the current page contents.
registerAssessment(world, assessment: assessmentPoint)
//// ----
// Any items added or removed after this call will be animated.
finalizeWorldBuilding(for: world)
//// ----
}
// Called from LiveView.swift to initially set the LiveView.
public func presentWorld() {
setUpLiveViewWith(world)
}
// MARK: Epilogue
public func playgroundEpilogue() {
sendCommands(for: world)
}
func placeActor() {
world.place(actor, facing: east, at: Coordinate(column: 0, row: 0))
}
func placeItems() {
let items = [
Coordinate(column: 1, row: 2),
Coordinate(column: 1, row: 5),
Coordinate(column: 2, row: 3),
Coordinate(column: 2, row: 4),
Coordinate(column: 3, row: 4),
Coordinate(column: 3, row: 2),
Coordinate(column: 5, row: 5),
Coordinate(column: 5, row: 0),
]
world.placeGems(at: items)
}
func placeBlocks() {
let obstacles = [
Coordinate(column: 0, row: 1),
Coordinate(column: 1, row: 1),
Coordinate(column: 2, row: 1),
Coordinate(column: 3, row: 1),
Coordinate(column: 4, row: 1),
Coordinate(column: 6, row: 1),
Coordinate(column: 6, row: 2),
Coordinate(column: 6, row: 3),
Coordinate(column: 6, row: 4),
Coordinate(column: 6, row: 5),
Coordinate(column: 4, row: 3),
Coordinate(column: 4, row: 4),
]
world.removeNodes(at: obstacles)
world.placeWater(at: obstacles)
let tiers = [
Coordinate(column: 2, row: 0),
Coordinate(column: 3, row: 0),
Coordinate(column: 4, row: 0),
Coordinate(column: 5, row: 0),
Coordinate(column: 6, row: 0),
Coordinate(column: 5, row: 2),
Coordinate(column: 5, row: 3),
Coordinate(column: 5, row: 4),
Coordinate(column: 5, row: 5),
Coordinate(column: 5, row: 2),
Coordinate(column: 5, row: 3),
Coordinate(column: 5, row: 4),
Coordinate(column: 5, row: 5),
Coordinate(column: 5, row: 1),
Coordinate(column: 0, row: 5),
Coordinate(column: 1, row: 5),
Coordinate(column: 2, row: 5),
Coordinate(column: 3, row: 5),
Coordinate(column: 0, row: 5),
Coordinate(column: 1, row: 5),
Coordinate(column: 2, row: 5),
Coordinate(column: 3, row: 5),
Coordinate(column: 4, row: 5),
Coordinate(column: 0, row: 5),
Coordinate(column: 1, row: 5),
Coordinate(column: 2, row: 5),
Coordinate(column: 3, row: 5),
Coordinate(column: 4, row: 5),
Coordinate(column: 0, row: 4),
Coordinate(column: 0, row: 3),
Coordinate(column: 0, row: 3),
Coordinate(column: 0, row: 4),
Coordinate(column: 0, row: 2),
Coordinate(column: 1, row: 4),
Coordinate(column: 1, row: 3),
Coordinate(column: 1, row: 2),
Coordinate(column: 0, row: 4),
Coordinate(column: 0, row: 3),
Coordinate(column: 0, row: 2),
Coordinate(column: 0, row: 2),
Coordinate(column: 1, row: 4),
Coordinate(column: 1, row: 3),
Coordinate(column: 1, row: 2),
Coordinate(column: 2, row: 2),
Coordinate(column: 3, row: 2),
Coordinate(column: 4, row: 2),
]
world.placeBlocks(at: tiers)
world.place(Stair(), facing: west, at: Coordinate(column: 1, row: 0))
world.place(Stair(), at: Coordinate(column: 5, row: 1))
world.place(Stair(), at: Coordinate(column: 1, row: 4))
world.place(Stair(), facing: east, at: Coordinate(column: 4, row: 5))
world.place(Stair(), facing: east, at: Coordinate(column: 2, row: 2))
world.place(Stair(), facing: north, at: Coordinate(column: 3, row: 3))
}
| mit | 863278acc176f33f61f1b4b4bd251915 | 35.584507 | 89 | 0.459865 | 4.463058 | false | false | false | false |
ahcode0919/swift-design-patterns | swift-design-patterns/unit-tests/Structural/DecoratorTests.swift | 1 | 1545 | //
// DecoratorTests.swift
// unit-tests
//
// Created by Aaron Hinton on 10/29/17.
// Copyright © 2017 No Name Software. All rights reserved.
//
import XCTest
class DecoratorTests: XCTestCase {
func testVehicleDecorator() {
let vehicle = Vehicle(vehicleType: .car, bumper: .standard, towingPackage: true, wheels: .touring(size: ._250mm))
let decoratedVehicle = VehicleDecorator(decoratedVehicle: vehicle)
XCTAssertEqual(vehicle.bumper, decoratedVehicle.bumper)
XCTAssertEqual(vehicle.towingPackage, decoratedVehicle.towingPackage)
XCTAssertEqual(vehicle.vehicleType, decoratedVehicle.vehicleType)
XCTAssertEqual(vehicle.wheels, decoratedVehicle.wheels)
}
func testTowingPackageDecorator() {
let car = Vehicle(vehicleType: .car, bumper: .standard, towingPackage: false, wheels: .touring(size: ._250mm))
let truck = Vehicle(vehicleType: .truck, bumper: .standard, towingPackage: false, wheels: .offroad(size: ._250mm))
let decoratedCar = CarInstallTowingPackageDecorator(decoratedVehicle: car)
let decoratedTruck = TruckInstallTowingPackageDecorator(decoratedVehicle: truck)
decoratedCar.installTowingPackage()
decoratedTruck.installTowingPackage()
XCTAssertEqual(decoratedCar.bumper, .standardWithHitch)
XCTAssertTrue(decoratedCar.towingPackage ?? false)
XCTAssertEqual(decoratedTruck.bumper, .heavyDuty)
XCTAssertTrue(decoratedTruck.towingPackage ?? false)
}
}
| mit | 3851655e7e04c8f5262daf1493c2683f | 41.888889 | 122 | 0.716969 | 4.195652 | false | true | false | false |
almas-dev/APMAlertController | Pod/Classes/APMAlertAnimation.swift | 1 | 3002 | //
// Created by Xander on 04.03.16.
//
import UIKit
class APMAlertAnimation: NSObject, UIViewControllerAnimatedTransitioning {
let presenting: Bool
init(presenting: Bool) {
self.presenting = presenting
}
func transitionDuration(using _: UIViewControllerContextTransitioning?) -> TimeInterval {
return presenting ? 0.5 : 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
presenting ? presentAnimateTransition(transitionContext) : dismissAnimateTransition(transitionContext)
}
func presentAnimateTransition(_ transitionContext: UIViewControllerContextTransitioning) {
if let alertController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? APMAlertController {
let containerView = transitionContext.containerView
alertController.view.backgroundColor = UIColor.clear
alertController.alertView.alpha = 0.0
alertController.alertView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
containerView.addSubview(alertController.view)
UIView.animate(withDuration: 0.33,
animations: {
alertController.view.backgroundColor = UIColor(white: 0, alpha: 0.4)
alertController.alertView.alpha = 1.0
alertController.alertView.transform = CGAffineTransform(scaleX: 1.05, y: 1.05)
},
completion: { finished in
UIView.animate(withDuration: 0.2,
animations: {
alertController.alertView.transform = CGAffineTransform.identity
},
completion: { finished in
if finished {
transitionContext.completeTransition(true)
}
})
})
}
}
func dismissAnimateTransition(_ transitionContext: UIViewControllerContextTransitioning) {
if let alertController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? APMAlertController {
UIView.animate(withDuration: 0.33,
animations: {
alertController.view.backgroundColor = UIColor.clear
alertController.alertView.alpha = 0.0
alertController.alertView.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
},
completion: { _ in
transitionContext.completeTransition(true)
})
}
}
}
| mit | bfc2e145e22a463e886f66846bb363c7 | 45.184615 | 141 | 0.547302 | 7.014019 | false | false | false | false |
noppoMan/swifty-libuv | Sources/DNSWrap.swift | 1 | 3489 | //
// DNSWrap.swift
// SwiftyLibuv
//
// Created by Yuki Takei on 6/12/16.
//
//
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
import CLibUv
/**
Result struct for DNS.getAddrInfo
*/
public struct AddrInfo {
/**
ipv4/6 hostname
*/
public let host: String
/**
Service Name or Port
*/
public let service: String
init(host: String, service: String){
self.host = host
self.service = service
}
}
private struct DnsContext {
let completion: ((Void) throws -> [AddrInfo]) -> Void
}
// TODO Should implement with uv_queue_work or uv_getnameinfo
func sockaddr_description(addr: UnsafePointer<sockaddr>, length: UInt32) -> AddrInfo? {
var host : String?
var service : String?
var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
var serviceBuffer = [CChar](repeating: 0, count: Int(NI_MAXSERV))
let r = getnameinfo(
addr,
length,
&hostBuffer,
socklen_t(hostBuffer.count),
&serviceBuffer,
socklen_t(serviceBuffer.count),
NI_NUMERICHOST | NI_NUMERICSERV
)
if r == 0 {
host = String(validatingUTF8: hostBuffer)
service = String(validatingUTF8: serviceBuffer)
}
if let h = host, let s = service {
return AddrInfo(host: h, service: s)
}
return nil
}
extension addrinfo {
func walk(_ f: (addrinfo) -> Void) -> Void {
f(self)
if self.ai_next != nil {
self.ai_next.pointee.walk(f)
}
}
}
func getaddrinfo_cb(req: UnsafeMutablePointer<uv_getaddrinfo_t>?, status: Int32, res: UnsafeMutablePointer<addrinfo>?){
guard let req = req, let res = res else {
return
}
let context: DnsContext = releaseVoidPointer(req.pointee.data)
defer {
freeaddrinfo(res)
dealloc(req)
}
if status < 0 {
return context.completion {
throw UVError.rawUvError(code: status)
}
}
var addrInfos = [AddrInfo]()
res.pointee.walk {
if $0.ai_next != nil {
let addrInfo = sockaddr_description(addr: $0.ai_addr, length: $0.ai_addrlen)
if let ai = addrInfo {
addrInfos.append(ai)
}
}
}
context.completion {
addrInfos
}
}
/**
DNS utility
*/
public class DNS {
/**
Asynchronous getaddrinfo(3)
- parameter loop: Event loop
- parameter fqdn: The fqdn to resolve
- parameter port: The port number(String) to resolve
*/
public static func getAddrInfo(loop: Loop = Loop.defaultLoop, fqdn: String, port: String? = nil, completion: @escaping ((Void) throws -> [AddrInfo]) -> Void){
let req = UnsafeMutablePointer<uv_getaddrinfo_t>.allocate(capacity: MemoryLayout<uv_getaddrinfo_t>.size)
let context = DnsContext(completion: completion)
req.pointee.data = retainedVoidPointer(context)
let r: Int32
if let port = port {
r = uv_getaddrinfo(loop.loopPtr, req, getaddrinfo_cb, fqdn, port, nil)
} else {
r = uv_getaddrinfo(loop.loopPtr, req, getaddrinfo_cb, fqdn, nil, nil)
}
if r < 0 {
defer {
dealloc(req)
}
completion {
throw UVError.rawUvError(code: r)
}
}
}
}
| mit | 52a86576d3a16852e097a4489cd63e4f | 21.803922 | 162 | 0.561192 | 3.907055 | false | false | false | false |
VadimPavlov/Swifty | Sources/Swifty/ios/CoreData/Primitives.swift | 1 | 1806 | //
// Primitives.swift
// Swifty
//
// Created by Vadim Pavlov on 10/20/17.
// Copyright © 2017 Vadym Pavlov. All rights reserved.
//
import CoreData
public protocol Primitives: AnyObject {
associatedtype PrimitiveKey: RawRepresentable
}
public extension Primitives where Self: NSManagedObject, PrimitiveKey.RawValue == String {
subscript<O>(key: PrimitiveKey) -> O? {
set {
let primitiveKey = key.rawValue
let primitiveValue = newValue
self.willChangeValue(forKey: primitiveKey)
if let value = primitiveValue {
self.setPrimitiveValue(value, forKey: primitiveKey)
} else {
self.setPrimitiveValue(nil, forKey: primitiveKey)
}
self.didChangeValue(forKey: primitiveKey)
}
get {
let primitiveKey = key.rawValue
self.willAccessValue(forKey: primitiveKey)
let primitiveValue = self.primitiveValue(forKey: primitiveKey) as? O
self.didAccessValue(forKey: primitiveKey)
return primitiveValue
}
}
subscript<P: RawRepresentable>(key: PrimitiveKey) -> P? {
set {
let primitiveKey = key.rawValue
let primitiveValue = newValue?.rawValue
self.willChangeValue(forKey: primitiveKey)
self.setPrimitiveValue(primitiveValue, forKey: primitiveKey)
self.didChangeValue(forKey: primitiveKey)
}
get {
let primitiveKey = key.rawValue
self.willAccessValue(forKey: primitiveKey)
let primitiveValue = self.primitiveValue(forKey: primitiveKey) as? P.RawValue
self.didAccessValue(forKey: primitiveKey)
return primitiveValue.flatMap(P.init)
}
}
}
| mit | 368ab6dde965d947db0da2be201e2a50 | 32.425926 | 90 | 0.624377 | 4.826203 | false | false | false | false |
RedRoma/Lexis-Database | LexisDatabase/Regex.swift | 1 | 2189 | //
// Regex.swift
// LexisDatabase
//
// Created by Wellington Moreno on 8/30/16.
// Copyright © 2016 RedRoma, Inc. All rights reserved.
//
import Foundation
import Archeota
struct Regex
{
/**
Matches the actual Latin Words.
For example, Veritate.
*/
static let wordList = "(?<=#)(.*?)(?=\\s{2,})"
/**
Searches for the word's modifiers that tell what the function
of the word is. For example, Verb, Noun, etc.
It also finds secondary modifiers, like gender, and verb transitivity.
*/
static let wordModifiers = "(?<= )(INTRANS|TRANS|ADJ|ADV|CONJ|PREP|ACC|INTERJ|V|N|F|M|PRON|PERS|REFLEX|NOM|ACC|ABL|DAT|GEN|VOC|LOC|DEP|SEMIDEP|PERFDEF|NUM)(?= )"
/**
Matches the dictionary code. This code includes information on the word's origin and use.
*/
static let dictionaryCode = "(?<=\\[)([A-Z]{5})(?=\\])"
/**
Matches the English portion of the word. This phrase includes the entire string term,
which may include multiple definitions and terms.
*/
static let definitionTerms = "(?<=:: )(.*)"
/**
Matches the Verb or Noun's declension. It includes the entire english phrase,
for example, "1st", "2nd", etc.
This also matches for a Verb's Conjugation.
1. Starting with 'N' (noun) or 'V' (verb)
2. Followed by a space
3. Followed by an open parenthesis
4. Followed by a number from 1-5
5. Followed by 2 letters from a-z (eg, 3rd, 2nd, 4th, etc)
6. Ending with a closed parenthesis
*/
static let declension = "(?<=[NV] \\()([1-5][a-z]{2})(?=\\))"
}
//MARK: Regex syntax
infix operator =~
func =~ (string: String, pattern: String) -> [String]
{
let regex: NSRegularExpression
do
{
regex = try NSRegularExpression(pattern: pattern, options: [])
}
catch
{
LOG.error("Pattern is not valid regex: \(error)")
return []
}
let nsString = string as NSString
let results = regex.matches(in: string, options: [], range: NSMakeRange(0, nsString.length))
return results.map() {
nsString.substring(with: $0.range)
}
}
| apache-2.0 | 87d2d96493a1b24373bec7226808c1c1 | 27.415584 | 165 | 0.603291 | 3.727428 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/PhotoLibrary/View/PhotoLibraryLayout.swift | 1 | 2724 | import UIKit
final class PhotoLibraryLayout: UICollectionViewFlowLayout {
private var attributes = [IndexPath: UICollectionViewLayoutAttributes]()
private var contentSize: CGSize = .zero
// MARK: - Constants
private let insets = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 6)
private let cellSpacing = CGFloat(6)
private let numberOfPhotosInRow = 3
// MARK: - PhotoLibraryLayout
func cellSize() -> CGSize {
if let collectionView = collectionView {
let contentWidth = collectionView.bounds.size.width - insets.left - insets.right
let itemWidth = (contentWidth - CGFloat(numberOfPhotosInRow - 1) * cellSpacing) / CGFloat(numberOfPhotosInRow)
return CGSize(width: itemWidth, height: itemWidth)
} else {
return .zero
}
}
// MARK: - UICollectionViewLayout
override var collectionViewContentSize: CGSize {
return contentSize
}
override func prepare() {
guard let collectionView = collectionView else {
contentSize = .zero
attributes = [:]
return
}
attributes.removeAll()
let itemSize = cellSize()
let section = 0
let numberOfItems = collectionView.numberOfItems(inSection: section)
var maxY = CGFloat(0)
for item in 0 ..< numberOfItems {
let row = floor(CGFloat(item) / CGFloat(numberOfPhotosInRow))
let column = CGFloat(item % numberOfPhotosInRow)
let origin = CGPoint(
x: insets.left + column * (itemSize.width + cellSpacing),
y: insets.top + row * (itemSize.height + cellSpacing)
)
let indexPath = IndexPath(item: item, section: section)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(
origin: origin,
size: itemSize
)
maxY = max(maxY, attributes.frame.maxY)
self.attributes[indexPath] = attributes
}
contentSize = CGSize(
width: collectionView.bounds.maxX,
height: maxY
)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return attributes.filter { $1.frame.intersects(rect) }.map { $1 }
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return attributes[indexPath]
}
}
| mit | 8891f8ce24ba2cc7e79d567889a74328 | 31.047059 | 122 | 0.578561 | 5.746835 | false | false | false | false |
thierrybucco/Eureka | Example/Example/ViewController.swift | 1 | 68574 | // ViewController.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Eureka
import CoreLocation
//MARK: HomeViewController
class HomeViewController : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
ImageRow.defaultCellUpdate = { cell, row in
cell.accessoryView?.layer.cornerRadius = 17
cell.accessoryView?.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
}
form +++
Section() {
$0.header = HeaderFooterView<EurekaLogoView>(.class)
}
<<< ButtonRow("Rows") {
$0.title = $0.tag
$0.presentationMode = .segueName(segueName: "RowsExampleViewControllerSegue", onDismiss: nil)
}
<<< ButtonRow("Native iOS Event Form") { row in
row.title = row.tag
row.presentationMode = .segueName(segueName: "NativeEventsFormNavigationControllerSegue", onDismiss:{ vc in vc.dismiss(animated: true) })
}
<<< ButtonRow("Accesory View Navigation") { (row: ButtonRow) in
row.title = row.tag
row.presentationMode = .segueName(segueName: "AccesoryViewControllerSegue", onDismiss: nil)
}
<<< ButtonRow("Custom Cells") { (row: ButtonRow) -> () in
row.title = row.tag
row.presentationMode = .segueName(segueName: "CustomCellsControllerSegue", onDismiss: nil)
}
<<< ButtonRow("Customization of rows with text input") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .segueName(segueName: "FieldCustomizationControllerSegue", onDismiss: nil)
}
<<< ButtonRow("Hidden rows") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .segueName(segueName: "HiddenRowsControllerSegue", onDismiss: nil)
}
<<< ButtonRow("Disabled rows") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .segueName(segueName: "DisabledRowsControllerSegue", onDismiss: nil)
}
<<< ButtonRow("Formatters") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .segueName(segueName: "FormattersControllerSegue", onDismiss: nil)
}
<<< ButtonRow("Inline rows") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .segueName(segueName: "InlineRowsControllerSegue", onDismiss: nil)
}
<<< ButtonRow("List Sections") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .segueName(segueName: "ListSectionsControllerSegue", onDismiss: nil)
}
<<< ButtonRow("Validations") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .segueName(segueName: "ValidationsControllerSegue", onDismiss: nil)
}
<<< ButtonRow("Custom Design") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .segueName(segueName: "CustomDesignControllerSegue", onDismiss: nil)
}
<<< ButtonRow("Multivalued Sections") { (row: ButtonRow) -> Void in
row.title = row.tag
row.presentationMode = .segueName(segueName: "MultivaluedSectionsControllerSegue", onDismiss: nil)
}
+++ Section()
<<< ButtonRow() { (row: ButtonRow) -> Void in
row.title = "About"
}
.onCellSelection { [weak self] (cell, row) in
self?.showAlert()
}
}
@IBAction func showAlert() {
let alertController = UIAlertController(title: "OnCellSelection", message: "Button Row Action", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true)
}
}
//MARK: Emoji
typealias Emoji = String
let 👦🏼 = "👦🏼", 🍐 = "🍐", 💁🏻 = "💁🏻", 🐗 = "🐗", 🐼 = "🐼", 🐻 = "🐻", 🐖 = "🐖", 🐡 = "🐡"
//Mark: RowsExampleViewController
class RowsExampleViewController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
URLRow.defaultCellUpdate = { cell, row in cell.textField.textColor = .blue }
LabelRow.defaultCellUpdate = { cell, row in cell.detailTextLabel?.textColor = .orange }
CheckRow.defaultCellSetup = { cell, row in cell.tintColor = .orange }
DateRow.defaultRowInitializer = { row in row.minimumDate = Date() }
form +++
Section()
<<< LabelRow () {
$0.title = "LabelRow"
$0.value = "tap the row"
}
.onCellSelection { cell, row in
row.title = (row.title ?? "") + " 🇺🇾 "
row.reload() // or row.updateCell()
}
<<< DateRow() { $0.value = Date(); $0.title = "DateRow" }
<<< CheckRow() {
$0.title = "CheckRow"
$0.value = true
}
<<< SwitchRow() {
$0.title = "SwitchRow"
$0.value = true
}
<<< SliderRow() {
$0.title = "SliderRow"
$0.value = 5.0
}
<<< StepperRow() {
$0.title = "StepperRow"
$0.value = 1.0
}
+++ Section("SegmentedRow examples")
<<< SegmentedRow<String>() { $0.options = ["One", "Two", "Three"] }
<<< SegmentedRow<Emoji>(){
$0.title = "Who are you?"
$0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻 ]
$0.value = 🍐
}
<<< SegmentedRow<String>(){
$0.title = "SegmentedRow"
$0.options = ["One", "Two"]
}.cellSetup { cell, row in
cell.imageView?.image = UIImage(named: "plus_image")
}
<<< SegmentedRow<String>(){
$0.options = ["One", "Two", "Three", "Four"]
$0.value = "Three"
}.cellSetup { cell, row in
cell.imageView?.image = UIImage(named: "plus_image")
}
+++ Section("Selectors Rows Examples")
<<< ActionSheetRow<String>() {
$0.title = "ActionSheetRow"
$0.selectorTitle = "Your favourite player?"
$0.options = ["Diego Forlán", "Edinson Cavani", "Diego Lugano", "Luis Suarez"]
$0.value = "Luis Suarez"
}
.onPresent { from, to in
to.popoverPresentationController?.permittedArrowDirections = .up
}
<<< AlertRow<Emoji>() {
$0.title = "AlertRow"
$0.selectorTitle = "Who is there?"
$0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻]
$0.value = 👦🏼
}.onChange { row in
print(row.value ?? "No Value")
}
.onPresent{ _, to in
to.view.tintColor = .purple
}
<<< PushRow<Emoji>() {
$0.title = "PushRow"
$0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻]
$0.value = 👦🏼
$0.selectorTitle = "Choose an Emoji!"
}
<<< PushRow<Emoji>() {
$0.title = "SectionedPushRow"
$0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻]
$0.value = 👦🏼
$0.selectorTitle = "Choose an Emoji!"
}.onPresent { from, to in
to.sectionKeyForValue = { option in
switch option {
case 💁🏻, 👦🏼: return "People"
case 🐗, 🐼, 🐻: return "Animals"
case 🍐: return "Food"
default: return ""
}
}
}
if UIDevice.current.userInterfaceIdiom == .pad {
let section = form.last!
section <<< PopoverSelectorRow<Emoji>() {
$0.title = "PopoverSelectorRow"
$0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻]
$0.value = 💁🏻
$0.selectorTitle = "Choose an Emoji!"
}
}
let section = form.last!
section
<<< LocationRow(){
$0.title = "LocationRow"
$0.value = CLLocation(latitude: -34.91, longitude: -56.1646)
}
<<< ImageRow(){
$0.title = "ImageRow"
}
<<< MultipleSelectorRow<Emoji>() {
$0.title = "MultipleSelectorRow"
$0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻]
$0.value = [👦🏼, 🍐, 🐗]
}
.onPresent { from, to in
to.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: from, action: #selector(RowsExampleViewController.multipleSelectorDone(_:)))
}
<<< MultipleSelectorRow<Emoji>() {
$0.title = "SectionedMultipleSelectorRow"
$0.options = [💁🏻, 🍐, 👦🏼, 🐗, 🐼, 🐻]
$0.value = [👦🏼, 🍐, 🐗]
}
.onPresent { from, to in
to.sectionKeyForValue = { option in
switch option {
case 💁🏻, 👦🏼: return "People"
case 🐗, 🐼, 🐻: return "Animals"
case 🍐: return "Food"
default: return ""
}
}
to.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: from, action: #selector(RowsExampleViewController.multipleSelectorDone(_:)))
}
form +++ Section("Generic picker")
<<< PickerRow<String>("Picker Row") { (row : PickerRow<String>) -> Void in
row.options = []
for i in 1...10{
row.options.append("option \(i)")
}
}
<<< PickerInputRow<String>("Picker Input Row"){
$0.title = "Options"
$0.options = []
for i in 1...10{
$0.options.append("option \(i)")
}
$0.value = $0.options.first
}
+++ Section("FieldRow examples")
<<< TextRow() {
$0.title = "TextRow"
$0.placeholder = "Placeholder"
}
<<< DecimalRow() {
$0.title = "DecimalRow"
$0.value = 5
$0.formatter = DecimalFormatter()
$0.useFormatterDuringInput = true
//$0.useFormatterOnDidBeginEditing = true
}.cellSetup { cell, _ in
cell.textField.keyboardType = .numberPad
}
<<< URLRow() {
$0.title = "URLRow"
$0.value = URL(string: "http://xmartlabs.com")
}
<<< PhoneRow() {
$0.title = "PhoneRow (disabled)"
$0.value = "+598 9898983510"
$0.disabled = true
}
<<< NameRow() {
$0.title = "NameRow"
}
<<< PasswordRow() {
$0.title = "PasswordRow"
$0.value = "password"
}
<<< IntRow() {
$0.title = "IntRow"
$0.value = 2015
}
<<< EmailRow() {
$0.title = "EmailRow"
$0.value = "[email protected]"
}
<<< TwitterRow() {
$0.title = "TwitterRow"
$0.value = "@xmartlabs"
}
<<< AccountRow() {
$0.title = "AccountRow"
$0.placeholder = "Placeholder"
}
<<< ZipCodeRow() {
$0.title = "ZipCodeRow"
$0.placeholder = "90210"
}
}
func multipleSelectorDone(_ item:UIBarButtonItem) {
_ = navigationController?.popViewController(animated: true)
}
}
//MARK: Custom Cells Example
class CustomCellsController : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form +++
Section() {
var header = HeaderFooterView<EurekaLogoViewNib>(.nibFile(name: "EurekaSectionHeader", bundle: nil))
header.onSetupView = { (view, section) -> () in
view.imageView.alpha = 0;
UIView.animate(withDuration: 2.0, animations: { [weak view] in
view?.imageView.alpha = 1
})
view.layer.transform = CATransform3DMakeScale(0.9, 0.9, 1)
UIView.animate(withDuration: 1.0, animations: { [weak view] in
view?.layer.transform = CATransform3DIdentity
})
}
$0.header = header
}
+++ Section("WeekDay cell")
<<< WeekDayRow(){
$0.value = [.monday, .wednesday, .friday]
}
<<< TextFloatLabelRow() {
$0.title = "Float Label Row, type something to see.."
}
<<< IntFloatLabelRow() {
$0.title = "Float Label Row, type something to see.."
}
}
}
//MARK: Field row customization Example
class FieldRowCustomizationController : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form +++
Section(header: "Default field rows", footer: "Rows with title have a right-aligned text field.\nRows without title have a left-aligned text field.\nBut this can be changed...")
<<< NameRow() {
$0.title = "Your name:"
$0.placeholder = "(right alignment)"
}
.cellSetup { cell, row in
cell.imageView?.image = UIImage(named: "plus_image")
}
<<< NameRow() {
$0.placeholder = "Name (left alignment)"
}
.cellSetup { cell, row in
cell.imageView?.image = UIImage(named: "plus_image")
}
+++ Section("Customized Alignment")
<<< NameRow() {
$0.title = "Your name:"
}.cellUpdate { cell, row in
cell.textField.textAlignment = .left
cell.textField.placeholder = "(left alignment)"
}
<<< NameRow().cellUpdate { cell, row in
cell.textField.textAlignment = .right
cell.textField.placeholder = "Name (right alignment)"
}
+++ Section(header: "Customized Text field width", footer: "Eureka allows us to set up a specific UITextField width using textFieldPercentage property. In the section above we have also right aligned the textLabels.")
<<< NameRow() {
$0.title = "Title"
$0.textFieldPercentage = 0.6
$0.placeholder = "textFieldPercentage = 0.6"
}
.cellUpdate {
$1.cell.textField.textAlignment = .left
$1.cell.textLabel?.textAlignment = .right
}
<<< NameRow() {
$0.title = "Another Title"
$0.textFieldPercentage = 0.6
$0.placeholder = "textFieldPercentage = 0.6"
}
.cellUpdate {
$1.cell.textField.textAlignment = .left
$1.cell.textLabel?.textAlignment = .right
}
<<< NameRow() {
$0.title = "One more"
$0.textFieldPercentage = 0.7
$0.placeholder = "textFieldPercentage = 0.7"
}
.cellUpdate {
$1.cell.textField.textAlignment = .left
$1.cell.textLabel?.textAlignment = .right
}
+++ Section("TextAreaRow")
<<< TextAreaRow() {
$0.placeholder = "TextAreaRow"
$0.textAreaHeight = .dynamic(initialTextViewHeight: 110)
}
}
}
//MARK: Navigation Accessory View Example
class NavigationAccessoryController : FormViewController {
var navigationOptionsBackup : RowNavigationOptions?
override func viewDidLoad() {
super.viewDidLoad()
navigationOptions = RowNavigationOptions.Enabled.union(.SkipCanNotBecomeFirstResponderRow)
navigationOptionsBackup = navigationOptions
form = Section(header: "Settings", footer: "These settings change how the navigation accessory view behaves")
<<< SwitchRow("set_none") { [weak self] in
$0.title = "Navigation accessory view"
$0.value = self?.navigationOptions != .Disabled
}.onChange { [weak self] in
if $0.value ?? false {
self?.navigationOptions = self?.navigationOptionsBackup
self?.form.rowBy(tag: "set_disabled")?.baseValue = self?.navigationOptions?.contains(.StopDisabledRow)
self?.form.rowBy(tag: "set_skip")?.baseValue = self?.navigationOptions?.contains(.SkipCanNotBecomeFirstResponderRow)
self?.form.rowBy(tag: "set_disabled")?.updateCell()
self?.form.rowBy(tag: "set_skip")?.updateCell()
}
else {
self?.navigationOptionsBackup = self?.navigationOptions
self?.navigationOptions = .Disabled
}
}
<<< CheckRow("set_disabled") { [weak self] in
$0.title = "Stop at disabled row"
$0.value = self?.navigationOptions?.contains(.StopDisabledRow)
$0.hidden = "$set_none == false" // .Predicate(NSPredicate(format: "$set_none == false"))
}.onChange { [weak self] row in
if row.value ?? false {
self?.navigationOptions = self?.navigationOptions?.union(.StopDisabledRow)
}
else{
self?.navigationOptions = self?.navigationOptions?.subtracting(.StopDisabledRow)
}
}
<<< CheckRow("set_skip") { [weak self] in
$0.title = "Skip non first responder view"
$0.value = self?.navigationOptions?.contains(.SkipCanNotBecomeFirstResponderRow)
$0.hidden = "$set_none == false"
}.onChange { [weak self] row in
if row.value ?? false {
self?.navigationOptions = self?.navigationOptions?.union(.SkipCanNotBecomeFirstResponderRow)
}
else{
self?.navigationOptions = self?.navigationOptions?.subtracting(.SkipCanNotBecomeFirstResponderRow)
}
}
+++
NameRow() { $0.title = "Your name:" }
<<< PasswordRow() { $0.title = "Your password:" }
+++
Section()
<<< SegmentedRow<Emoji>() {
$0.title = "Favourite food:"
$0.options = [🐗, 🐖, 🐡, 🍐]
}
<<< PhoneRow() { $0.title = "Your phone number" }
<<< URLRow() {
$0.title = "Disabled"
$0.disabled = true
}
<<< TextRow() { $0.title = "Your father's name"}
<<< TextRow(){ $0.title = "Your mother's name"}
}
}
//MARK: Native Event Example
class NativeEventNavigationController: UINavigationController, RowControllerType {
var onDismissCallback : ((UIViewController) -> ())?
}
class NativeEventFormViewController : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
initializeForm()
navigationItem.leftBarButtonItem?.target = self
navigationItem.leftBarButtonItem?.action = #selector(NativeEventFormViewController.cancelTapped(_:))
}
private func initializeForm() {
form +++
TextRow("Title").cellSetup { cell, row in
cell.textField.placeholder = row.tag
}
<<< TextRow("Location").cellSetup {
$1.cell.textField.placeholder = $0.row.tag
}
+++
SwitchRow("All-day") {
$0.title = $0.tag
}.onChange { [weak self] row in
let startDate: DateTimeInlineRow! = self?.form.rowBy(tag: "Starts")
let endDate: DateTimeInlineRow! = self?.form.rowBy(tag: "Ends")
if row.value ?? false {
startDate.dateFormatter?.dateStyle = .medium
startDate.dateFormatter?.timeStyle = .none
endDate.dateFormatter?.dateStyle = .medium
endDate.dateFormatter?.timeStyle = .none
}
else {
startDate.dateFormatter?.dateStyle = .short
startDate.dateFormatter?.timeStyle = .short
endDate.dateFormatter?.dateStyle = .short
endDate.dateFormatter?.timeStyle = .short
}
startDate.updateCell()
endDate.updateCell()
startDate.inlineRow?.updateCell()
endDate.inlineRow?.updateCell()
}
<<< DateTimeInlineRow("Starts") {
$0.title = $0.tag
$0.value = Date().addingTimeInterval(60*60*24)
}
.onChange { [weak self] row in
let endRow: DateTimeInlineRow! = self?.form.rowBy(tag: "Ends")
if row.value?.compare(endRow.value!) == .orderedDescending {
endRow.value = Date(timeInterval: 60*60*24, since: row.value!)
endRow.cell!.backgroundColor = .white
endRow.updateCell()
}
}
.onExpandInlineRow { [weak self] cell, row, inlineRow in
inlineRow.cellUpdate() { cell, row in
let allRow: SwitchRow! = self?.form.rowBy(tag: "All-day")
if allRow.value ?? false {
cell.datePicker.datePickerMode = .date
}
else {
cell.datePicker.datePickerMode = .dateAndTime
}
}
let color = cell.detailTextLabel?.textColor
row.onCollapseInlineRow { cell, _, _ in
cell.detailTextLabel?.textColor = color
}
cell.detailTextLabel?.textColor = cell.tintColor
}
<<< DateTimeInlineRow("Ends"){
$0.title = $0.tag
$0.value = Date().addingTimeInterval(60*60*25)
}
.onChange { [weak self] row in
let startRow: DateTimeInlineRow! = self?.form.rowBy(tag: "Starts")
if row.value?.compare(startRow.value!) == .orderedAscending {
row.cell!.backgroundColor = .red
}
else{
row.cell!.backgroundColor = .white
}
row.updateCell()
}
.onExpandInlineRow { [weak self] cell, row, inlineRow in
inlineRow.cellUpdate { cell, dateRow in
let allRow: SwitchRow! = self?.form.rowBy(tag: "All-day")
if allRow.value ?? false {
cell.datePicker.datePickerMode = .date
}
else {
cell.datePicker.datePickerMode = .dateAndTime
}
}
let color = cell.detailTextLabel?.textColor
row.onCollapseInlineRow { cell, _, _ in
cell.detailTextLabel?.textColor = color
}
cell.detailTextLabel?.textColor = cell.tintColor
}
form +++
PushRow<RepeatInterval>("Repeat") {
$0.title = $0.tag
$0.options = RepeatInterval.allValues
$0.value = .Never
}.onPresent({ (_, vc) in
vc.enableDeselection = false
vc.dismissOnSelection = false
})
form +++
PushRow<EventAlert>() {
$0.title = "Alert"
$0.options = EventAlert.allValues
$0.value = .Never
}
.onChange { [weak self] row in
if row.value == .Never {
if let second : PushRow<EventAlert> = self?.form.rowBy(tag: "Another Alert"), let secondIndexPath = second.indexPath {
row.section?.remove(at: secondIndexPath.row)
}
}
else{
guard let _ : PushRow<EventAlert> = self?.form.rowBy(tag: "Another Alert") else {
let second = PushRow<EventAlert>("Another Alert") {
$0.title = $0.tag
$0.value = .Never
$0.options = EventAlert.allValues
}
row.section?.insert(second, at: row.indexPath!.row + 1)
return
}
}
}
form +++
PushRow<EventState>("Show As") {
$0.title = "Show As"
$0.options = EventState.allValues
}
form +++
URLRow("URL") {
$0.placeholder = "URL"
}
<<< TextAreaRow("notes") {
$0.placeholder = "Notes"
$0.textAreaHeight = .dynamic(initialTextViewHeight: 50)
}
}
func cancelTapped(_ barButtonItem: UIBarButtonItem) {
(navigationController as? NativeEventNavigationController)?.onDismissCallback?(self)
}
enum RepeatInterval : String, CustomStringConvertible {
case Never = "Never"
case Every_Day = "Every Day"
case Every_Week = "Every Week"
case Every_2_Weeks = "Every 2 Weeks"
case Every_Month = "Every Month"
case Every_Year = "Every Year"
var description : String { return rawValue }
static let allValues = [Never, Every_Day, Every_Week, Every_2_Weeks, Every_Month, Every_Year]
}
enum EventAlert : String, CustomStringConvertible {
case Never = "None"
case At_time_of_event = "At time of event"
case Five_Minutes = "5 minutes before"
case FifTeen_Minutes = "15 minutes before"
case Half_Hour = "30 minutes before"
case One_Hour = "1 hour before"
case Two_Hour = "2 hours before"
case One_Day = "1 day before"
case Two_Days = "2 days before"
var description : String { return rawValue }
static let allValues = [Never, At_time_of_event, Five_Minutes, FifTeen_Minutes, Half_Hour, One_Hour, Two_Hour, One_Day, Two_Days]
}
enum EventState {
case busy
case free
static let allValues = [busy, free]
}
}
//MARK: HiddenRowsExample
class HiddenRowsExample : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
TextRow.defaultCellUpdate = { cell, row in
cell.textLabel?.font = UIFont.italicSystemFont(ofSize: 12)
}
form = Section("What do you want to talk about:")
<<< SegmentedRow<String>("segments"){
$0.options = ["Sport", "Music", "Films"]
$0.value = "Films"
}
+++ Section(){
$0.tag = "sport_s"
$0.hidden = "$segments != 'Sport'" // .Predicate(NSPredicate(format: "$segments != 'Sport'"))
}
<<< TextRow(){
$0.title = "Which is your favourite soccer player?"
}
<<< TextRow(){
$0.title = "Which is your favourite coach?"
}
<<< TextRow(){
$0.title = "Which is your favourite team?"
}
+++ Section(){
$0.tag = "music_s"
$0.hidden = "$segments != 'Music'"
}
<<< TextRow(){
$0.title = "Which music style do you like most?"
}
<<< TextRow(){
$0.title = "Which is your favourite singer?"
}
<<< TextRow(){
$0.title = "How many CDs have you got?"
}
+++ Section(){
$0.tag = "films_s"
$0.hidden = "$segments != 'Films'"
}
<<< TextRow(){
$0.title = "Which is your favourite actor?"
}
<<< TextRow(){
$0.title = "Which is your favourite film?"
}
+++ Section()
<<< SwitchRow("Show Next Row"){
$0.title = $0.tag
}
<<< SwitchRow("Show Next Section"){
$0.title = $0.tag
$0.hidden = .function(["Show Next Row"], { form -> Bool in
let row: RowOf<Bool>! = form.rowBy(tag: "Show Next Row")
return row.value ?? false == false
})
}
+++ Section(footer: "This section is shown only when 'Show Next Row' switch is enabled"){
$0.hidden = .function(["Show Next Section"], { form -> Bool in
let row: RowOf<Bool>! = form.rowBy(tag: "Show Next Section")
return row.value ?? false == false
})
}
<<< TextRow() {
$0.placeholder = "Gonna dissapear soon!!"
}
}
}
//MARK: DisabledRowsExample
class DisabledRowsExample : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form = Section()
<<< SegmentedRow<String>("segments"){
$0.options = ["Enabled", "Disabled"]
$0.value = "Disabled"
}
<<< TextRow(){
$0.title = "choose enabled, disable above..."
$0.disabled = "$segments = 'Disabled'"
}
<<< SwitchRow("Disable Next Section?"){
$0.title = $0.tag
$0.disabled = "$segments = 'Disabled'"
}
+++ Section()
<<< TextRow() {
$0.title = "Gonna be disabled soon.."
$0.disabled = Eureka.Condition.function(["Disable Next Section?"], { (form) -> Bool in
let row: SwitchRow! = form.rowBy(tag: "Disable Next Section?")
return row.value ?? false
})
}
+++ Section()
<<< SegmentedRow<String>(){
$0.options = ["Always Disabled"]
$0.disabled = true
}
}
}
//MARK: FormatterExample
class FormatterExample : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form +++ Section("Number formatters")
<<< DecimalRow(){
$0.useFormatterDuringInput = true
$0.title = "Currency style"
$0.value = 2015
let formatter = CurrencyFormatter()
formatter.locale = .current
formatter.numberStyle = .currency
$0.formatter = formatter
}
<<< DecimalRow(){
$0.title = "Scientific style"
$0.value = 2015
let formatter = NumberFormatter()
formatter.locale = .current
formatter.numberStyle = .scientific
$0.formatter = formatter
}
<<< IntRow(){
$0.title = "Spell out style"
$0.value = 2015
let formatter = NumberFormatter()
formatter.locale = .current
formatter.numberStyle = .spellOut
$0.formatter = formatter
}
+++ Section("Date formatters")
<<< DateRow(){
$0.title = "Short style"
$0.value = Date()
let formatter = DateFormatter()
formatter.locale = .current
formatter.dateStyle = .short
$0.dateFormatter = formatter
}
<<< DateRow(){
$0.title = "Long style"
$0.value = Date()
let formatter = DateFormatter()
formatter.locale = .current
formatter.dateStyle = .long
$0.dateFormatter = formatter
}
+++ Section("Other formatters")
<<< DecimalRow(){
$0.title = "Energy: Jules to calories"
$0.value = 100.0
let formatter = EnergyFormatter()
$0.formatter = formatter
}
<<< IntRow(){
$0.title = "Weight: Kg to lb"
$0.value = 1000
$0.formatter = MassFormatter()
}
}
class CurrencyFormatter : NumberFormatter, FormatterProtocol {
override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, range rangep: UnsafeMutablePointer<NSRange>?) throws {
guard obj != nil else { return }
let str = string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
obj?.pointee = NSNumber(value: (Double(str) ?? 0.0)/Double(pow(10.0, Double(minimumFractionDigits))))
}
func getNewPosition(forPosition position: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition {
return textInput.position(from: position, offset:((newValue?.characters.count ?? 0) - (oldValue?.characters.count ?? 0))) ?? position
}
}
}
class InlineRowsController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form.inlineRowHideOptions = InlineRowHideOptions.AnotherInlineRowIsShown.union(.FirstResponderChanges)
form
+++ Section("Automatically Hide Inline Rows?")
<<< SwitchRow() {
$0.title = "Hides when another inline row is shown"
$0.value = true
}
.onChange { [weak form] in
if $0.value == true {
form?.inlineRowHideOptions = form?.inlineRowHideOptions?.union(.AnotherInlineRowIsShown)
}
else {
form?.inlineRowHideOptions = form?.inlineRowHideOptions?.subtracting(.AnotherInlineRowIsShown)
}
}
<<< SwitchRow() {
$0.title = "Hides when the First Responder changes"
$0.value = true
}
.onChange { [weak form] in
if $0.value == true {
form?.inlineRowHideOptions = form?.inlineRowHideOptions?.union(.FirstResponderChanges)
}
else {
form?.inlineRowHideOptions = form?.inlineRowHideOptions?.subtracting(.FirstResponderChanges)
}
}
+++ Section()
<<< DateInlineRow() {
$0.title = "DateInlineRow"
$0.value = Date()
}
<<< TimeInlineRow(){
$0.title = "TimeInlineRow"
$0.value = Date()
}
<<< DateTimeInlineRow(){
$0.title = "DateTimeInlineRow"
$0.value = Date()
}
<<< CountDownInlineRow(){
$0.title = "CountDownInlineRow"
var dateComp = DateComponents()
dateComp.hour = 18
dateComp.minute = 33
dateComp.timeZone = TimeZone.current
$0.value = Calendar.current.date(from: dateComp)
}
+++ Section("Generic inline picker")
<<< PickerInlineRow<Date>("PickerInlineRow") { (row : PickerInlineRow<Date>) -> Void in
row.title = row.tag
row.displayValueFor = { (rowValue: Date?) in
return rowValue.map { "Year \(Calendar.current.component(.year, from: $0))" }
}
row.options = []
var date = Date()
for _ in 1...10{
row.options.append(date)
date = date.addingTimeInterval(60*60*24*365)
}
row.value = row.options[0]
}
}
}
class ListSectionsController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
let continents = ["Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America"]
form +++ SelectableSection<ImageCheckRow<String>>() { section in
section.header = HeaderFooterView(title: "Where do you live?")
}
for option in continents {
form.last! <<< ImageCheckRow<String>(option){ lrow in
lrow.title = option
lrow.selectableValue = option
lrow.value = nil
}
}
let oceans = ["Arctic", "Atlantic", "Indian", "Pacific", "Southern"]
form +++ SelectableSection<ImageCheckRow<String>>("And which of the following oceans have you taken a bath in?", selectionType: .multipleSelection)
for option in oceans {
form.last! <<< ImageCheckRow<String>(option){ lrow in
lrow.title = option
lrow.selectableValue = option
lrow.value = nil
}.cellSetup { cell, _ in
cell.trueImage = UIImage(named: "selectedRectangle")!
cell.falseImage = UIImage(named: "unselectedRectangle")!
}
}
}
override func valueHasBeenChanged(for row: BaseRow, oldValue: Any?, newValue: Any?) {
if row.section === form[0] {
print("Single Selection:\((row.section as! SelectableSection<ImageCheckRow<String>>).selectedRow()?.baseValue ?? "No row selected")")
}
else if row.section === form[1] {
print("Mutiple Selection:\((row.section as! SelectableSection<ImageCheckRow<String>>).selectedRows().map({$0.baseValue}))")
}
}
}
class ValidationsController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
LabelRow.defaultCellUpdate = { cell, row in
cell.contentView.backgroundColor = .red
cell.textLabel?.textColor = .white
cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 13)
cell.textLabel?.textAlignment = .right
}
TextRow.defaultCellUpdate = { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
form
+++ Section(header: "Required Rule", footer: "Options: Validates on change")
<<< TextRow() {
$0.title = "Required Rule"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnChange
}
+++ Section(header: "Email Rule, Required Rule", footer: "Options: Validates on change after blurred")
<<< TextRow() {
$0.title = "Email Rule"
$0.add(rule: RuleRequired())
var ruleSet = RuleSet<String>()
ruleSet.add(rule: RuleRequired())
ruleSet.add(rule: RuleEmail())
$0.add(ruleSet: ruleSet)
$0.validationOptions = .validatesOnChangeAfterBlurred
}
+++ Section(header: "URL Rule", footer: "Options: Validates on change")
<<< URLRow() {
$0.title = "URL Rule"
$0.add(rule: RuleURL())
$0.validationOptions = .validatesOnChange
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
+++ Section(header: "MinLength 8 Rule, MaxLength 13 Rule", footer: "Options: Validates on blurred")
<<< PasswordRow() {
$0.title = "Password"
$0.add(rule: RuleMinLength(minLength: 8))
$0.add(rule: RuleMaxLength(maxLength: 13))
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
+++ Section(header: "Should be GreaterThan 2 and SmallerThan 999", footer: "Options: Validates on blurred")
<<< IntRow() {
$0.title = "Range Rule"
$0.add(rule: RuleGreaterThan(min: 2))
$0.add(rule: RuleSmallerThan(max: 999))
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
+++ Section(header: "Match field values", footer: "Options: Validates on blurred")
<<< PasswordRow("password") {
$0.title = "Password"
}
<<< PasswordRow() {
$0.title = "Confirm Password"
$0.add(rule: RuleEqualsToRow(form: form, tag: "password"))
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
+++ Section(header: "More sophisticated validations UX using callbacks", footer: "")
<<< TextRow() {
$0.title = "Required Rule"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnChange
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = validationMsg
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
<<< EmailRow() {
$0.title = "Email Rule"
$0.add(rule: RuleRequired())
$0.add(rule: RuleEmail())
$0.validationOptions = .validatesOnChangeAfterBlurred
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = validationMsg
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
<<< URLRow() {
$0.title = "URL Rule"
$0.add(rule: RuleURL())
$0.validationOptions = .validatesOnChange
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = validationMsg
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
<<< PasswordRow("password2") {
$0.title = "Password"
$0.add(rule: RuleMinLength(minLength: 8))
$0.add(rule: RuleMaxLength(maxLength: 13))
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = validationMsg
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
<<< PasswordRow() {
$0.title = "Confirm Password"
$0.add(rule: RuleEqualsToRow(form: form, tag: "password2"))
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = validationMsg
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
<<< IntRow() {
$0.title = "Range Rule"
$0.add(rule: RuleGreaterThan(min: 2))
$0.add(rule: RuleSmallerThan(max: 999))
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = validationMsg
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
+++ Section()
<<< ButtonRow() {
$0.title = "Tap to force form validation"
}
.onCellSelection { cell, row in
row.section?.form?.validate()
}
}
}
class CustomDesignController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
form +++
Section()
<<< SwitchRow() {
$0.cellProvider = CellProvider<SwitchCell>(nibName: "SwitchCell", bundle: Bundle.main)
$0.cell.height = { 67 }
}
<<< DatePickerRow() {
$0.cellProvider = CellProvider<DatePickerCell>(nibName: "DatePickerCell", bundle: Bundle.main)
$0.cell.height = { 345 }
}
<<< TextRow() {
$0.cellProvider = CellProvider<TextCell>(nibName: "TextCell", bundle: Bundle.main)
$0.cell.height = { 199 }
}
.onChange { row in
if let textView = row.cell.viewWithTag(99) as? UITextView {
textView.text = row.cell.textField.text
}
}
}
}
class MultivaluedSectionsController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Multivalued examples"
form +++
Section("Multivalued examples")
<<< ButtonRow(){
$0.title = "Multivalued Sections"
$0.presentationMode = .segueName(segueName: "MultivaluedControllerSegue", onDismiss: nil)
}
<<< ButtonRow(){
$0.title = "Multivalued Only Reorder"
$0.presentationMode = .segueName(segueName: "MultivaluedOnlyReorderControllerSegue", onDismiss: nil)
}
<<< ButtonRow(){
$0.title = "Multivalued Only Insert"
$0.presentationMode = .segueName(segueName: "MultivaluedOnlyInsertControllerSegue", onDismiss: nil)
}
<<< ButtonRow(){
$0.title = "Multivalued Only Delete"
$0.presentationMode = .segueName(segueName: "MultivaluedOnlyDeleteControllerSegue", onDismiss: nil)
}
}
}
class MultivaluedController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Multivalued Examples"
form +++
MultivaluedSection(multivaluedOptions: [.Reorder, .Insert, .Delete],
header: "Multivalued TextField",
footer: ".Insert multivaluedOption adds the 'Add New Tag' button row as last cell.") {
$0.addButtonProvider = { section in
return ButtonRow(){
$0.title = "Add New Tag"
}.cellUpdate { cell, row in
cell.textLabel?.textAlignment = .left
}
}
$0.multivaluedRowToInsertAt = { index in
return NameRow() {
$0.placeholder = "Tag Name"
}
}
$0 <<< NameRow() {
$0.placeholder = "Tag Name"
}
}
+++
MultivaluedSection(multivaluedOptions: [.Insert, .Delete],
header: "Multivalued ActionSheet Selector example",
footer: ".Insert multivaluedOption adds a 'Add' button row as last cell.") {
$0.multivaluedRowToInsertAt = { index in
return ActionSheetRow<String>{
$0.title = "Tap to select.."
$0.options = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"]
}
}
$0 <<< ActionSheetRow<String> {
$0.title = "Tap to select.."
$0.options = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"]
}
}
+++
MultivaluedSection(multivaluedOptions: [.Insert, .Delete, .Reorder],
header: "Multivalued Push Selector example",
footer: "") {
$0.multivaluedRowToInsertAt = { index in
return PushRow<String>{
$0.title = "Tap to select ;)..at \(index)"
$0.options = ["Option 1", "Option 2", "Option 3"]
}
}
$0 <<< PushRow<String> {
$0.title = "Tap to select ;).."
$0.options = ["Option 1", "Option 2", "Option 3"]
}
}
}
}
class MultivaluedOnlyRearderController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
let secondsPerDay = 24 * 60 * 60
let list = ["Today", "Yesterday", "Before Yesterday"]
form +++
MultivaluedSection(multivaluedOptions: .Reorder,
header: "Reordering Selectors",
footer: "") {
$0 <<< PushRow<String> {
$0.title = "Tap to select ;).."
$0.options = ["Option 1", "Option 2", "Option 3"]
}
<<< PushRow<String> {
$0.title = "Tap to select ;).."
$0.options = ["Option 1", "Option 2", "Option 3"]
}
<<< PushRow<String> {
$0.title = "Tap to select ;).."
$0.options = ["Option 1", "Option 2", "Option 3"]
}
<<< PushRow<String> {
$0.title = "Tap to select ;).."
$0.options = ["Option 1", "Option 2", "Option 3"]
}
}
+++
// Multivalued Section with inline rows - section set up to support only reordering
MultivaluedSection(multivaluedOptions: .Reorder,
header: "Reordering Inline Rows",
footer: "") { section in
list.enumerated().forEach({ offset, string in
let dateInlineRow = DateInlineRow(){
$0.value = Date(timeInterval: Double(-secondsPerDay) * Double(offset), since: Date())
$0.title = string
}
section <<< dateInlineRow
})
}
+++
MultivaluedSection(multivaluedOptions: .Reorder,
header: "Reordering Field Rows",
footer: "")
<<< NameRow {
$0.value = "Martin"
}
<<< NameRow {
$0.value = "Mathias"
}
<<< NameRow {
$0.value = "Agustin"
}
<<< NameRow {
$0.value = "Enrique"
}
}
}
class MultivaluedOnlyInsertController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Multivalued Only Insert"
form +++
MultivaluedSection(multivaluedOptions: .Insert) { sec in
sec.addButtonProvider = { _ in return ButtonRow {
$0.title = "Add Tag"
}.cellUpdate { cell, row in
cell.textLabel?.textAlignment = .left
}
}
sec.multivaluedRowToInsertAt = { index in
return TextRow {
$0.placeholder = "Tag Name"
}
}
sec.showInsertIconInAddButton = false
}
+++
MultivaluedSection(multivaluedOptions: .Insert, header: "Insert With Inline Cells") {
$0.multivaluedRowToInsertAt = { index in
return DateInlineRow {
$0.title = "Date"
$0.value = Date()
}
}
}
}
}
class MultivaluedOnlyDeleteController: FormViewController {
@IBOutlet weak var editButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
tableView.isEditing = false
let nameList = ["family", "male", "female", "client"]
let section = MultivaluedSection(multivaluedOptions: .Delete, footer: "you can swipe to delete when table.isEditing = false (Not Editing)")
for tag in nameList {
section <<< TextRow {
$0.placeholder = "Tag Name"
$0.value = tag
}
}
let section2 = MultivaluedSection(multivaluedOptions: .Delete, footer: "")
for _ in 1..<4 {
section2 <<< PickerInlineRow<String> {
$0.title = "Tap to select"
$0.value = "client"
$0.options = nameList
}
}
editButton.title = tableView.isEditing ? "Done" : "Edit"
editButton.target = self
editButton.action = #selector(editPressed(sender:))
form +++
section
+++
section2
}
func editPressed(sender: UIBarButtonItem){
tableView.setEditing(!tableView.isEditing, animated: true)
editButton.title = tableView.isEditing ? "Done" : "Edit"
}
}
class EurekaLogoViewNib: UIView {
@IBOutlet weak var imageView: UIImageView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class EurekaLogoView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
let imageView = UIImageView(image: UIImage(named: "Eureka"))
imageView.frame = CGRect(x: 0, y: 0, width: 320, height: 130)
imageView.autoresizingMask = .flexibleWidth
self.frame = CGRect(x: 0, y: 0, width: 320, height: 130)
imageView.contentMode = .scaleAspectFit
addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 252e091d865e768932f0122d6d8edc7a | 38.946136 | 229 | 0.425309 | 5.590626 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.